<?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;

$db = new Database();
$siteManager = SiteManager::getInstance($db);

// Handle form submissions
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'assign_market':
                    // Get market info to populate market_name
                    $marketStmt = $db->getConnection()->prepare("
                        SELECT market_code, market_name FROM market_schedules WHERE BINARY market_code = BINARY ?
                    ");
                    $marketStmt->execute([$_POST['market_code']]);
                    $marketInfo = $marketStmt->fetch(PDO::FETCH_ASSOC);
                    
                    if ($marketInfo) {
                        $stmt = $db->getConnection()->prepare("
                            INSERT IGNORE INTO site_markets (site_id, market_code, market_name, is_active, display_order, created_at) 
                            VALUES (?, ?, ?, 1, ?, NOW())
                        ");
                        
                        // Get next display order
                        $orderStmt = $db->getConnection()->prepare("
                            SELECT COALESCE(MAX(display_order), 0) + 1 FROM site_markets WHERE site_id = ?
                        ");
                        $orderStmt->execute([$_POST['site_id']]);
                        $nextOrder = $orderStmt->fetchColumn();
                        
                        $stmt->execute([
                            $_POST['site_id'], 
                            $marketInfo['market_code'], 
                            $marketInfo['market_name'],
                            $nextOrder
                        ]);
                        
                        $message = "Market berhasil ditambahkan ke site!";
                        $messageType = "success";
                    } else {
                        $message = "Market code tidak ditemukan!";
                        $messageType = "error";
                    }
                    break;
                    
                case 'remove_market':
                    $stmt = $db->getConnection()->prepare("
                        DELETE FROM site_markets WHERE site_id = ? AND market_code = ?
                    ");
                    $stmt->execute([$_POST['site_id'], $_POST['market_code']]);
                    $message = "Market berhasil dihapus dari site!";
                    $messageType = "success";
                    break;
                    
                case 'bulk_assign':
                    $siteId = $_POST['bulk_site_id'];
                    $markets = $_POST['markets'] ?? [];
                    
                    // Clear existing markets for this site
                    $stmt = $db->getConnection()->prepare("DELETE FROM site_markets WHERE site_id = ?");
                    $stmt->execute([$siteId]);
                    
                    // Add selected markets with proper data structure
                    if (!empty($markets)) {
                        $stmt = $db->getConnection()->prepare("
                            INSERT INTO site_markets (site_id, market_code, market_name, is_active, display_order, created_at)
                            SELECT ?, ms.market_code, ms.market_name, 1, ?, NOW()
                            FROM market_schedules ms
                            WHERE BINARY ms.market_code = BINARY ?
                        ");
                        
                        foreach ($markets as $index => $marketCode) {
                            $displayOrder = $index + 1;
                            $stmt->execute([$siteId, $displayOrder, $marketCode]);
                        }
                    }
                    
                    $message = "Bulk assignment berhasil! " . count($markets) . " market ditambahkan.";
                    $messageType = "success";
                    break;
            }
        }
    } catch (Exception $e) {
        $message = "Error: " . $e->getMessage();
        $messageType = "error";
    }
}

// Get data
$allSites = $siteManager->getAllSites();
$allMarkets = $siteManager->getAllMarkets();

// Get site markets mapping
$siteMarkets = [];
foreach ($allSites as $site) {
    $siteMarkets[$site['id']] = $siteManager->getSiteMarkets($site['id']);
}

$pageTitle = 'Assignment Pasaran ke Situs';

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

<!-- Main Content -->
<div class="main-content" style="margin-left: 0 !important;">
    <div class="container-fluid p-0">
        <!-- Page Header -->
        <div class="row g-0">
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-3 px-2">
                    <div>
                        <h1 class="h3 mb-0 text-gray-800">
                            <i class="bi bi-diagram-3 me-2"></i>Assignment Pasaran ke Situs
                        </h1>
                        <p class="mb-0 text-muted">Kelola assignment pasaran ke setiap situs dalam sistem multi-site</p>
                    </div>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="markets.php">Kelola Pasaran</a></li>
                            <li class="breadcrumb-item active">Assignment</li>
                        </ol>
                    </nav>
                </div>
            </div>
        </div>

        <!-- Tab Navigation -->
        <div class="row g-0">
            <div class="col-12">
                <div class="card shadow-sm mb-3 mx-2">
                    <div class="card-body py-2">
                        <ul class="nav nav-pills nav-fill">
                            <li class="nav-item">
                                <a class="nav-link" href="markets.php">
                                    <i class="bi bi-shop me-2"></i>Kelola Pasaran
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link active" href="site-markets.php">
                                    <i class="bi bi-diagram-3 me-2"></i>Assign Pasaran ke Situs
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Success/Error Messages -->
        <?php if ($message): ?>
        <div class="row g-0">
            <div class="col-12">
                <div class="alert alert-<?php echo $messageType === 'success' ? 'success' : 'danger'; ?> alert-dismissible fade show mx-2" role="alert">
                    <i class="bi bi-<?php echo $messageType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> me-2"></i>
                    <?php echo htmlspecialchars($message); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Summary Statistics -->
        <div class="row g-2 mb-3 mx-1">
            <div class="col-xl-3 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="text-uppercase text-muted mb-2">Total Sites</h6>
                                <h2 class="text-primary mb-0"><?php echo count($allSites); ?></h2>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-globe fs-2 text-primary"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="text-uppercase text-muted mb-2">Available Markets</h6>
                                <h2 class="text-success mb-0"><?php echo count($allMarkets); ?></h2>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-shop fs-2 text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="text-uppercase text-muted mb-2">Total Assignments</h6>
                                <h2 class="text-warning mb-0">
                                    <?php 
                                    $totalAssignments = 0;
                                    foreach ($siteMarkets as $markets) {
                                        $totalAssignments += count($markets);
                                    }
                                    echo $totalAssignments;
                                    ?>
                                </h2>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-diagram-3 fs-2 text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-xl-3 col-md-6">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col">
                                <h6 class="text-uppercase text-muted mb-2">Avg Markets/Site</h6>
                                <h2 class="text-info mb-0">
                                    <?php echo $totalAssignments > 0 && count($allSites) > 0 ? round($totalAssignments / count($allSites), 1) : 0; ?>
                                </h2>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-bar-chart fs-2 text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Quick Assignment -->
        <div class="row g-0">
            <div class="col-12">
                <div class="card shadow-sm mb-3 mx-2">
                    <div class="card-header bg-primary text-white">
                        <h5 class="card-title mb-0">
                            <i class="bi bi-lightning me-2"></i>Quick Market Assignment
                        </h5>
                        <small>Assign individual markets to sites</small>
                    </div>
                    <div class="card-body">
                        <form method="POST" class="row g-3">
                            <input type="hidden" name="action" value="assign_market">
                            <div class="col-md-5">
                                <label class="form-label fw-semibold">Select Site *</label>
                                <select name="site_id" class="form-select" required>
                                    <option value="">Choose Site...</option>
                                    <?php foreach ($allSites as $site): ?>
                                    <option value="<?php echo $site['id']; ?>">
                                        <?php echo htmlspecialchars($site['site_name']); ?> (<?php echo $site['site_code']; ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-5">
                                <label class="form-label fw-semibold">Select Market *</label>
                                <select name="market_code" class="form-select" required>
                                    <option value="">Choose Market...</option>
                                    <?php foreach ($allMarkets as $market): ?>
                                    <option value="<?php echo htmlspecialchars($market['market_code']); ?>">
                                        <?php echo htmlspecialchars($market['market_name']); ?> (<?php echo htmlspecialchars($market['market_code']); ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2 d-flex align-items-end">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-plus-circle me-1"></i>Assign
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Bulk Assignment -->
        <div class="row g-0">
            <div class="col-12">
                <div class="card shadow-sm mb-3 mx-2">
            <div class="card-header bg-success text-white">
                <h5 class="card-title mb-0">
                    <i class="bi bi-list-check me-2"></i>Bulk Market Assignment
                </h5>
                <small>Assign multiple markets to a site at once</small>
            </div>
            <div class="card-body">
                <form method="POST">
                    <input type="hidden" name="action" value="bulk_assign">
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Select Site *</label>
                        <select name="bulk_site_id" class="form-select" required onchange="loadCurrentMarkets(this.value)">
                            <option value="">Choose Site...</option>
                            <?php foreach ($allSites as $site): ?>
                            <option value="<?php echo $site['id']; ?>">
                                <?php echo htmlspecialchars($site['site_name']); ?> (<?php echo $site['site_code']; ?>)
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Select Markets</label>
                        <div class="alert alert-warning">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <strong>Warning:</strong> Current assignments will be replaced with your selection.
                        </div>
                        <div class="border rounded p-3 bg-light" style="max-height: 300px; overflow-y: auto;" id="marketCheckboxes">
                            <div class="row g-2">
                                <?php foreach ($allMarkets as $market): ?>
                                <div class="col-md-6 col-lg-4">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" name="markets[]" 
                                               value="<?php echo htmlspecialchars($market['market_code']); ?>" 
                                               id="market_<?php echo $market['id']; ?>">
                                        <label class="form-check-label small" for="market_<?php echo $market['id']; ?>">
                                            <strong><?php echo htmlspecialchars($market['market_name']); ?></strong>
                                            <br><span class="text-muted">(<?php echo htmlspecialchars($market['market_code']); ?>)</span>
                                        </label>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2 d-md-flex justify-content-md-start">
                        <button type="button" class="btn btn-outline-secondary me-md-2" onclick="checkAll(true)">
                            <i class="bi bi-check-all me-1"></i>Select All
                        </button>
                        <button type="button" class="btn btn-outline-secondary me-md-2" onclick="checkAll(false)">
                            <i class="bi bi-x-square me-1"></i>Clear All
                        </button>
                        <button type="submit" class="btn btn-success" onclick="return confirm('This will replace all current market assignments for the selected site. Continue?')">
                            <i class="bi bi-arrow-repeat me-1"></i>Update Site Markets
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Sites and Their Markets -->
        </div>
    </div>
    
    <div class="row g-0">
        <div class="col-12">
            <div class="card shadow-sm mx-2">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">
                        <i class="bi bi-card-list me-2"></i>Sites and Their Markets
                    </h5>
                    <small>Overview of all sites and their assigned markets</small>
                </div>
            <div class="card-body">
                <?php if (empty($allSites)): ?>
                <div class="text-center py-5">
                    <i class="bi bi-info-circle display-1 text-muted"></i>
                    <h5 class="mt-3">No Sites Found</h5>
                    <p class="text-muted">
                        <a href="sites.php" class="btn btn-primary btn-sm">
                            <i class="bi bi-plus-circle me-1"></i>Add Sites First
                        </a>
                    </p>
                </div>
                <?php else: ?>
                <div class="row g-4">
                    <?php foreach ($allSites as $site): ?>
                    <div class="col-xl-6">
                        <div class="card border h-100">
                            <div class="card-header">
                                <div class="d-flex align-items-center">
                                    <div class="flex-shrink-0">
                                        <div class="avatar bg-primary text-white rounded-circle d-flex align-items-center justify-content-center" 
                                             style="width: 40px; height: 40px; background-color: <?php echo $site['primary_color'] ?? '#007bff'; ?> !important;">
                                            <i class="bi bi-globe"></i>
                                        </div>
                                    </div>
                                    <div class="flex-grow-1 ms-3">
                                        <h6 class="mb-0"><?php echo htmlspecialchars($site['site_name']); ?></h6>
                                        <small class="text-muted">
                                            <strong>Code:</strong> <?php echo htmlspecialchars($site['site_code']); ?> | 
                                            <strong>Domain:</strong> <?php echo htmlspecialchars($site['domain']); ?>
                                        </small>
                                    </div>
                                    <div class="flex-shrink-0">
                                        <span class="badge bg-warning text-dark">
                                            <?php echo count($siteMarkets[$site['id']]); ?> Markets
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body">
                                <?php if (empty($siteMarkets[$site['id']])): ?>
                                <div class="text-center text-muted py-3">
                                    <i class="bi bi-inbox fs-2"></i>
                                    <p class="small mb-0">No markets assigned</p>
                                </div>
                                <?php else: ?>
                                <div class="market-list" style="max-height: 200px; overflow-y: auto;">
                                    <?php foreach ($siteMarkets[$site['id']] as $index => $market): ?>
                                    <div class="d-flex justify-content-between align-items-center py-2 <?php echo $index > 0 ? 'border-top' : ''; ?>">
                                        <div>
                                            <span class="fw-medium"><?php echo htmlspecialchars($market['market_name']); ?></span>
                                            <br><small class="text-muted"><?php echo htmlspecialchars($market['market_code']); ?></small>
                                        </div>
                                        <form method="POST" class="d-inline" 
                                              onsubmit="return confirm('Remove <?php echo htmlspecialchars($market['market_name']); ?> from <?php echo htmlspecialchars($site['site_name']); ?>?');">
                                            <input type="hidden" name="action" value="remove_market">
                                            <input type="hidden" name="site_id" value="<?php echo $site['id']; ?>">
                                            <input type="hidden" name="market_code" value="<?php echo htmlspecialchars($market['market_code']); ?>">
                                            <button type="submit" class="btn btn-outline-danger btn-sm">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </form>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <?php endif; ?>
                            </div>
                            <div class="card-footer text-center">
                                <button class="btn btn-outline-primary btn-sm" 
                                        onclick="selectSiteForBulkEdit('<?php echo $site['id']; ?>', '<?php echo htmlspecialchars($site['site_name']); ?>')">
                                    <i class="bi bi-gear me-1"></i>Manage Markets
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        </div>
    </div>
</div>
    </div>
    
<!-- JavaScript -->
<script>
    // Store site markets data for JavaScript
    const siteMarketsData = <?php echo json_encode($siteMarkets); ?>;
    
    // Load current markets when site is selected
    function loadCurrentMarkets(siteId) {
        const checkboxes = document.querySelectorAll('input[name="markets[]"]');
        checkboxes.forEach(cb => cb.checked = false);
        
        if (siteId && siteMarketsData[siteId]) {
            const assignedMarkets = siteMarketsData[siteId].map(m => m.market_code);
            checkboxes.forEach(cb => {
                if (assignedMarkets.includes(cb.value)) {
                    cb.checked = true;
                }
            });
        }
        
        // Update counter
        updateSelectionCounter();
    }
    
    // Select site for bulk edit from overview
    function selectSiteForBulkEdit(siteId, siteName) {
        const bulkForm = document.querySelector('select[name="bulk_site_id"]');
        bulkForm.value = siteId;
        bulkForm.scrollIntoView({ behavior: 'smooth', block: 'center' });
        
        loadCurrentMarkets(siteId);
        
        // Show notification
        showNotification(`Selected ${siteName} for bulk editing`, 'info');
        
        // Highlight the form
        const card = bulkForm.closest('.card');
        card.classList.add('border-warning');
        setTimeout(() => {
            card.classList.remove('border-warning');
        }, 3000);
    }
    
    // Check all/none functionality
    function checkAll(check = true) {
        const checkboxes = document.querySelectorAll('input[name="markets[]"]');
        checkboxes.forEach(cb => cb.checked = check);
        updateSelectionCounter();
    }
    
    // Update selection counter
    function updateSelectionCounter() {
        const checkedBoxes = document.querySelectorAll('input[name="markets[]"]:checked');
        const totalBoxes = document.querySelectorAll('input[name="markets[]"]');
        
        // Find or create counter display
        let counter = document.getElementById('selectionCounter');
        if (!counter) {
            counter = document.createElement('div');
            counter.id = 'selectionCounter';
            counter.className = 'small text-muted mt-2';
            const marketCheckboxes = document.getElementById('marketCheckboxes');
            marketCheckboxes.parentNode.insertBefore(counter, marketCheckboxes.nextSibling);
        }
        
        counter.innerHTML = `Selected: <strong>${checkedBoxes.length}</strong> of ${totalBoxes.length} markets`;
    }
    
    // Show notification
    function showNotification(message, type = 'success') {
        const alertClass = type === 'success' ? 'alert-success' : 
                          type === 'error' ? 'alert-danger' : 'alert-info';
        
        const notification = document.createElement('div');
        notification.className = `alert ${alertClass} alert-dismissible fade show position-fixed`;
        notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
        notification.innerHTML = `
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        `;
        
        document.body.appendChild(notification);
        
        // Auto remove after 3 seconds
        setTimeout(() => {
            if (notification.parentNode) {
                notification.remove();
            }
        }, 3000);
    }
    
    // Initialize event listeners
    document.addEventListener('DOMContentLoaded', function() {
        // Add change listeners to checkboxes
        const checkboxes = document.querySelectorAll('input[name="markets[]"]');
        checkboxes.forEach(cb => {
            cb.addEventListener('change', updateSelectionCounter);
        });
        
        // Initial counter update
        updateSelectionCounter();
        
        // Form submission enhancements
        const forms = document.querySelectorAll('form');
        forms.forEach(form => {
            form.addEventListener('submit', function(e) {
                const submitBtn = form.querySelector('button[type="submit"]');
                if (submitBtn) {
                    submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Processing...';
                    submitBtn.disabled = true;
                }
            });
        });
    });
</script>

<!-- Bootstrap JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

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