<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';
require_once '../includes/permission-middleware.php';

// Check integrated authentication
$integratedAuth = new IntegratedAdminAuth();
if (!isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: login.php');
    exit;
}

$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    session_destroy();
    header('Location: login.php');
    exit;
}

// Update session data
$_SESSION['admin_data'] = $adminData;

// CRITICAL: Set current site ID for proper data isolation
$_SESSION['current_site_id'] = $adminData['site_id'] ?? 1;

// Check permissions
$permissionMiddleware = new PermissionMiddleware($integratedAuth, $adminData);
if (!$permissionMiddleware->hasPermission('manage_markets')) {
    header('Location: dashboard.php?error=' . urlencode('Access denied.'));
    exit;
}

$db = new Database();

// Handle AJAX request for getting market data (must be before any HTML output)
if (isset($_GET['get_market']) && is_numeric($_GET['get_market'])) {
    $marketId = (int)$_GET['get_market'];
    $market = $db->getMarketScheduleById($marketId);
    
    header('Content-Type: application/json');
    if ($market) {
        echo json_encode(['success' => true, 'market' => $market]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Market not found']);
    }
    exit;
}
$error = '';
$success = '';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    try {
        if ($action === 'add_market') {
            $marketName = trim($_POST['market_name']);
            $marketCode = strtoupper(trim($_POST['market_code']));
            $openTime = $_POST['open_time'];
            $closeTime = $_POST['close_time'];
            $officialSite = trim($_POST['official_site'] ?? '');
            
            // Validate input
            if (empty($marketName) || empty($marketCode) || empty($openTime) || empty($closeTime)) {
                throw new Exception('Semua field harus diisi!');
            }
            
            if ($db->marketCodeExists($marketCode)) {
                throw new Exception('Kode pasaran sudah ada!');
            }
            
            // Handle logo upload
            $logoPath = null;
            if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                $logoPath = handleLogoUpload($_FILES['logo'], $marketCode);
            }
            
            if ($db->addMarketSchedule($marketName, $marketCode, $openTime, $closeTime, $logoPath, $officialSite)) {
                $success = 'Pasaran berhasil ditambahkan!';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'ADD_MARKET', 
                    "Added market: $marketName ($marketCode)", $adminData['type'] ?? 'master');
            } else {
                throw new Exception('Gagal menambahkan pasaran!');
            }
            
        } elseif ($action === 'update_market') {
            $id = (int)$_POST['market_id'];
            $marketName = trim($_POST['market_name']);
            $marketCode = strtoupper(trim($_POST['market_code']));
            $openTime = $_POST['open_time'];
            $closeTime = $_POST['close_time'];
            $officialSite = trim($_POST['official_site'] ?? '');
            
            if (empty($marketName) || empty($marketCode) || empty($openTime) || empty($closeTime)) {
                throw new Exception('Semua field harus diisi!');
            }
            
            // Check if market code exists for other markets
            if ($db->marketCodeExists($marketCode, $id)) {
                throw new Exception('Kode pasaran sudah ada!');
            }
            
            // Handle logo upload
            $logoPath = null;
            $updateLogo = false;
            
            if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
                $logoPath = handleLogoUpload($_FILES['logo'], $marketCode);
                if ($logoPath) {
                    $updateLogo = true;
                }
            }
            
            if ($db->updateMarketScheduleWithLogo($id, $marketName, $marketCode, $openTime, $closeTime, $logoPath, $officialSite, $updateLogo)) {
                $success = 'Pasaran berhasil diupdate!';
                
                // Log activity
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'UPDATE_MARKET', 
                    "Updated market: $marketName ($marketCode)", $adminData['type'] ?? 'master');
            } else {
                throw new Exception('Gagal mengupdate pasaran!');
            }
            
        } elseif ($action === 'delete_market') {
            $id = (int)$_POST['market_id'];
            
            // Get market info for logging
            $market = $db->getMarketScheduleById($id);
            
            if ($db->deleteMarketSchedule($id)) {
                $success = 'Pasaran berhasil dihapus!';
                
                // Log activity
                $marketName = $market ? $market['market_name'] : "ID $id";
                $integratedAuth->logActivity($integratedAuth->getAdminId($adminData), 'DELETE_MARKET', 
                    "Deleted market: $marketName", $adminData['type'] ?? 'master');
            } else {
                throw new Exception('Gagal menghapus pasaran!');
            }
        }
        
    } catch (Exception $e) {
        $error = $e->getMessage();
    }
}

// Handle logo upload function
function handleLogoUpload($file, $marketCode) {
    $uploadDir = '../assets/logos/';
    $dbPath = 'assets/logos/';
    $allowedTypes = ['image/jpeg', 'image/png', 'image/svg+xml', 'image/jpg', 'image/webp'];
    $maxSize = 2 * 1024 * 1024; // 2MB
    
    // Create directory if not exists
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Validate file
    if ($file['size'] > $maxSize) {
        throw new Exception('File terlalu besar (max 2MB)');
    }
    
    if (!in_array($file['type'], $allowedTypes)) {
        throw new Exception('Format file tidak didukung');
    }
    
    // Generate filename
    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $filename = $marketCode . '_' . time() . '.' . $extension;
    $targetPath = $uploadDir . $filename;
    
    // Move uploaded file
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        return $dbPath . $filename;
    }
    
    throw new Exception('Gagal mengupload file');
}

// Get all markets
$markets = $db->getMarketSchedules();

// Get market for editing if edit mode
$editMarket = null;
if (isset($_GET['edit']) && is_numeric($_GET['edit'])) {
    $editMarket = $db->getMarketScheduleById((int)$_GET['edit']);
}

// Set page variables for template
$pageTitle = 'Kelola Pasaran';
$pageDescription = 'Manajemen pasaran togel dan jadwal';
$headerActions = '
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addMarketModal">
        <i class="bi bi-plus-circle me-1"></i>
        Tambah Pasaran
    </button>
';

// Set flash messages
if ($success) {
    $_SESSION['success_message'] = $success;
}
if ($error) {
    $_SESSION['error_message'] = $error;
}

// Include sidebar template
include 'admin-sidebar-template.php';
?>

<!-- Markets Content -->
<div class="row">
    <div class="col-12">
        <!-- Tab Navigation -->
        <div class="card mb-3">
            <div class="card-body py-2">
                <ul class="nav nav-pills nav-fill">
                    <li class="nav-item">
                        <a class="nav-link active" href="markets.php">
                            <i class="bi bi-shop me-1"></i>
                            Kelola Pasaran
                        </a>
                    </li>
                    <?php 
                    // Show assignment tab only for master admin
                    $currentAdmin = $_SESSION['admin_data'] ?? null;
                    $isMasterAdmin = ($currentAdmin && isset($currentAdmin['is_master_admin']) && $currentAdmin['is_master_admin']) ||
                                     (isset($_SESSION['integrated_admin_type']) && $_SESSION['integrated_admin_type'] === 'master') ||
                                     ($currentAdmin && isset($currentAdmin['is_master']) && $currentAdmin['is_master']);
                    
                    if ($isMasterAdmin): 
                    ?>
                    <li class="nav-item">
                        <a class="nav-link" href="site-markets.php">
                            <i class="bi bi-diagram-3 me-1"></i>
                            Assign Pasaran ke Situs
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">
                    <i class="bi bi-shop me-2"></i>
                    Daftar Pasaran
                </h5>
            </div>
            <div class="card-body">
                <?php if (empty($markets)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-shop display-4 text-muted"></i>
                    <h5 class="mt-3">Belum ada Pasaran</h5>
                    <p class="text-muted">Klik tombol "Tambah Pasaran" untuk menambahkan pasaran pertama</p>
                </div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>Logo</th>
                                <th>Nama Pasaran</th>
                                <th>Kode</th>
                                <th>Jam Buka</th>
                                <th>Jam Tutup</th>
                                <th>Official Site</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($markets as $market): ?>
                            <tr>
                                <td>
                                    <?php if (!empty($market['logo_path'])): ?>
                                    <img src="../<?php echo htmlspecialchars($market['logo_path']); ?>" 
                                         alt="Logo" class="img-thumbnail" style="width: 40px; height: 40px; object-fit: cover;">
                                    <?php else: ?>
                                    <div class="bg-light rounded d-flex align-items-center justify-content-center" 
                                         style="width: 40px; height: 40px;">
                                        <i class="bi bi-image text-muted"></i>
                                    </div>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <strong><?php echo htmlspecialchars($market['market_name']); ?></strong>
                                </td>
                                <td>
                                    <span class="badge bg-primary"><?php echo htmlspecialchars($market['market_code']); ?></span>
                                </td>
                                <td><?php echo htmlspecialchars($market['open_time']); ?></td>
                                <td><?php echo htmlspecialchars($market['close_time']); ?></td>
                                <td>
                                    <?php if (!empty($market['official_site'])): ?>
                                    <a href="<?php echo htmlspecialchars($market['official_site']); ?>" 
                                       target="_blank" class="btn btn-sm btn-outline-info">
                                        <i class="bi bi-link-45deg"></i>
                                    </a>
                                    <?php else: ?>
                                    <span class="text-muted">-</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary" 
                                                onclick="editMarket(<?php echo $market['id']; ?>)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" 
                                                onclick="deleteMarket(<?php echo $market['id']; ?>, '<?php echo htmlspecialchars($market['market_name']); ?>')">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Add Market Modal -->
<div class="modal fade" id="addMarketModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Tambah Pasaran Baru</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_market">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nama Pasaran *</label>
                            <input type="text" class="form-control" name="market_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Kode Pasaran *</label>
                            <input type="text" class="form-control" name="market_code" required maxlength="10" style="text-transform: uppercase;">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Jam Buka *</label>
                            <input type="time" class="form-control" name="open_time" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Jam Tutup *</label>
                            <input type="time" class="form-control" name="close_time" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Official Site</label>
                        <input type="url" class="form-control" name="official_site" placeholder="https://example.com">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Logo Pasaran</label>
                        <input type="file" class="form-control" name="logo" accept="image/*">
                        <div class="form-text">Format: JPG, PNG, SVG, WEBP. Max 2MB.</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Tambah Pasaran</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Market Modal -->
<div class="modal fade" id="editMarketModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Pasaran</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" enctype="multipart/form-data" id="editMarketForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_market">
                    <input type="hidden" name="market_id" id="edit_market_id">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Nama Pasaran *</label>
                            <input type="text" class="form-control" name="market_name" id="edit_market_name" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Kode Pasaran *</label>
                            <input type="text" class="form-control" name="market_code" id="edit_market_code" required maxlength="10" style="text-transform: uppercase;">
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Jam Buka *</label>
                            <input type="time" class="form-control" name="open_time" id="edit_open_time" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Jam Tutup *</label>
                            <input type="time" class="form-control" name="close_time" id="edit_close_time" required>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Official Site</label>
                        <input type="url" class="form-control" name="official_site" id="edit_official_site" placeholder="https://example.com">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Logo Pasaran</label>
                        <input type="file" class="form-control" name="logo" accept="image/*">
                        <div class="form-text">Format: JPG, PNG, SVG, WEBP. Max 2MB. Kosongkan jika tidak ingin mengubah logo.</div>
                        <div id="current_logo_preview" class="mt-2"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Pasaran</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php
// Additional JavaScript for markets
$additionalJS = '
<script>
function editMarket(id) {
    // Get market data via AJAX
    fetch("markets.php?get_market=" + id)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const market = data.market;
                document.getElementById("edit_market_id").value = market.id;
                document.getElementById("edit_market_name").value = market.market_name;
                document.getElementById("edit_market_code").value = market.market_code;
                document.getElementById("edit_open_time").value = market.open_time;
                document.getElementById("edit_close_time").value = market.close_time;
                document.getElementById("edit_official_site").value = market.official_site || "";
                
                // Show current logo if exists
                const logoPreview = document.getElementById("current_logo_preview");
                if (market.logo_path) {
                    logoPreview.innerHTML = `
                        <div class="alert alert-info">
                            <strong>Logo saat ini:</strong><br>
                            <img src="../${market.logo_path}" alt="Current Logo" style="max-width: 100px; max-height: 100px;" class="img-thumbnail mt-2">
                        </div>
                    `;
                } else {
                    logoPreview.innerHTML = "<div class=\"alert alert-warning\">Tidak ada logo</div>";
                }
                
                new bootstrap.Modal(document.getElementById("editMarketModal")).show();
            } else {
                showNotification("Error loading market data: " + (data.message || "Market not found"), "danger");
            }
        })
        .catch(error => {
            console.error("Error:", error);
            showNotification("Error loading market data", "danger");
        });
}

function deleteMarket(id, name) {
    if (confirm("Apakah Anda yakin ingin menghapus pasaran: " + name + "?")) {
        const form = document.createElement("form");
        form.method = "POST";
        form.innerHTML = `
            <input type="hidden" name="action" value="delete_market">
            <input type="hidden" name="market_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Auto uppercase market code
document.addEventListener("DOMContentLoaded", function() {
    const codeInputs = document.querySelectorAll("input[name=market_code]");
    codeInputs.forEach(input => {
        input.addEventListener("input", function() {
            this.value = this.value.toUpperCase();
        });
    });
});
</script>';

include 'admin-sidebar-footer.php';
?>