<?php
require_once __DIR__ . '/navbar.php';
$pdo = require __DIR__ . '/../config/db.php';
$role = $_SESSION['role'] ?? null;
if ($role !== 'admin' && $role !== 'staff') {
    header('Location: ../ooh_project/index.php?page=login');
    exit;
}

// Helper to fetch table data
function fetch_strings($table, $column)
{
    global $pdo;
    $stmt = $pdo->query("SELECT id, $column FROM $table ORDER BY $column ASC");
    $arr = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $arr[] = $row;
    }
    return $arr;
}

// Table/column mapping
$tables = [
    'suppliers'   => ['table' => 'suppliers',   'column' => 'name'],
    'formats'     => ['table' => 'formats',     'column' => 'name'],
    'market'      => ['table' => 'market',     'column' => 'name'],
    'unilever'    => ['table' => 'unilever',    'column' => 'name'],
    'competitors' => ['table' => 'competitors', 'column' => 'name'],
    'plans'    => ['table' => 'plans',    'column' => 'name'],
];

// Fetch all lists
$data = [];
foreach ($tables as $key => $info) {
    $data[$key] = fetch_strings($info['table'], $info['column']);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OOH Management</title>
    <link rel="icon" type="image/x-icon" href="../ooh_project/favicon.ico">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@flaticon/flaticon-uicons/css/all/all.css">
    <style>
        .add-btn {
            margin-left: 8px;
            cursor: pointer;
        }

        .list-group-item {
            cursor: pointer;
        }

        .modal-backdrop {
            z-index: 1040 !important;
        }

        .market-selection {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #dee2e6;
            border-radius: 0.375rem;
            padding: 10px;
            background-color: #f8f9fa;
        }

        .market-item {
            display: inline-block;
            width: 140px;
            margin: 2px;
            padding: 6px 10px;
            background-color: white;
            border: 1px solid #dee2e6;
            border-radius: 20px;
            font-size: 0.7em;
            transition: all 0.2s;
        }

        .market-item:hover {
            background-color: #e9ecef;
            border-color: #adb5bd;
        }

        .market-item input[type="checkbox"] {
            margin-right: 6px;
        }

        .market-item input[type="checkbox"]:checked+span {
            font-weight: 500;
            color: #007bff;
        }
    </style>
</head>

<body>
    <div class="container mt-2">
        <h2 class="mb-4 text-center">Update Database</h2>
        <div class="row" style="font-size: 85%;">
            <?php foreach ($tables as $key => $info): ?>
                <div class="col-md-2 col-12 mb-4">
                    <div class="card shadow-sm">
                        <div class="card-header text-center">
                            <?php if ($key === 'plans'): ?>
                                <button type="button" class="btn btn-success btn-sm add-btn my-2" onclick="showPlanModal()" title="Add Plan">
                                    <i class="fi fi-rr-plus"></i> Add Plan
                                </button>
                            <?php else: ?>
                                <form class="d-flex align-items-center justify-content-center" onsubmit="return addString('<?= $key ?>', this)">
                                    <input type="text" class="form-control form-control-sm me-2" name="newval" placeholder="Add <?= ucfirst($key) ?>" required>
                                    <button type="submit" class="btn btn-success btn-sm add-btn" title="Add">
                                        <i class="fi fi-rr-plus"></i>
                                    </button>
                                </form>
                            <?php endif; ?>
                        </div>
                        <ul class="list-group list-group-flush" id="list-<?= $key ?>">
                            <?php foreach ($data[$key] as $row): ?>
                                <li class="list-group-item" data-id="<?= $row['id'] ?>" data-table="<?= $key ?>" onclick="<?= $key === 'plans' ? 'showPlanModal(this)' : 'showUpdateModal(this)' ?>" title="Click to edit">
                                    <?= htmlspecialchars($row[$info['column']]) ?>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <!-- Update Modal (for all except plans) -->
    <div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <form class="modal-content" id="updateForm" onsubmit="return updateString()">
                <div class="modal-header">
                    <h5 class="modal-title" id="updateModalLabel">Update Value</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="update_id">
                    <input type="hidden" id="update_table">
                    <div class="mb-3">
                        <label for="update_value" class="form-label">New Name</label>
                        <input type="text" class="form-control" id="update_value" required>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Update</button>
                    <button type="button" class="btn btn-danger" onclick="deleteStringFromModal()">Delete</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Add/Edit Plan Modal -->
    <div class="modal fade" id="planModal" tabindex="-1" aria-labelledby="planModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-centered">
            <form class="modal-content" id="planForm" onsubmit="return savePlan()">
                <div class="modal-header" style="padding:0.5rem 1rem; background: linear-gradient(90deg, #007bff 60%, #0056b3 100%);">
                    <h5 class="modal-title text-white" id="planModalLabel">Add/Edit Plan</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="plan_id">
                    <div class="row g-2">
                        <div class="col-md-5">
                            <label class="form-label text-primary">Plan Name</label>
                            <input type="text" class="form-control" id="plan_name" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label text-primary">Business Unit</label>
                            <select class="form-select" id="plan_category" required></select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label text-primary">Brand</label>
                            <select class="form-select" id="plan_brand" required></select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-primary">Budget</label>
                            <div class="input-group">
                                <span class="input-group-text">€</span>
                                <input type="text" class="form-control" id="plan_budget" inputmode="numeric" pattern="[0-9,]*" placeholder="0" autocomplete="off">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-primary">Status</label>
                            <select class="form-select" id="plan_status">
                                <option value="draft">Draft</option>
                                <option value="active">Active</option>
                                <option value="completed">Completed</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-primary">Start Date</label>
                            <input type="date" class="form-control" id="plan_start">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-primary">End Date</label>
                            <input type="date" class="form-control" id="plan_end">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label text-primary">Objectives</label>
                            <textarea class="form-control" id="plan_desc" rows="2"></textarea>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label text-primary">Notes</label>
                            <textarea class="form-control" id="plan_notes" rows="2"></textarea>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label text-primary">Market Focus</label>
                            <div id="plan_market_checkboxes" class="market-selection"></div>
                            <small class="text-muted">Select one or more markets</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-success">Save</button>
                    <button type="button" class="btn btn-danger" id="planDeleteBtn" style="display:none;">Delete</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Format budget input as EUR with thousand separators, no decimals
        const budgetInput = document.getElementById('plan_budget');
        if (budgetInput) {
            budgetInput.addEventListener('input', function(e) {
                let val = budgetInput.value.replace(/[^\d]/g, '');
                if (val) {
                    let num = parseInt(val, 10);
                    if (!isNaN(num)) {
                        budgetInput.value = num.toLocaleString('en-US');
                    } else {
                        budgetInput.value = '';
                    }
                } else {
                    budgetInput.value = '';
                }
            });
        }

        function addString(table, form) {
            const val = form.newval.value.trim();
            if (!val) return false;
            fetch('/ooh_project/handler/update_table_crud.php', {
                    method: 'POST',
                    body: new URLSearchParams({
                        action: 'add',
                        table,
                        value: val
                    })
                })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        const ul = document.getElementById('list-' + table);
                        const li = document.createElement('li');
                        li.className = 'list-group-item';
                        li.dataset.id = res.id;
                        li.dataset.table = table;
                        li.textContent = val;
                        li.onclick = function() {
                            if (table === 'plans') {
                                showPlanModal(li);
                            } else {
                                showUpdateModal(li);
                            }
                        };
                        ul.appendChild(li);
                        form.reset();
                    } else {
                        alert(res.error || 'Failed to add.');
                    }
                });
            return false;
        }

        // Show Add/Edit Plan Modal
        function showPlanModal(el = null) {
            // Fetch brands and markets for selects
            fetch('/ooh_project/handler/update_table_crud.php', {
                    method: 'POST',
                    body: new URLSearchParams({
                        action: 'get_brands_markets'
                    })
                })
                .then(r => r.json())
                .then(res => {
                    // Populate category
                    const categorySelect = document.getElementById('plan_category');
                    categorySelect.innerHTML = '';
                    res.categories.forEach(c => {
                        const opt = document.createElement('option');
                        opt.value = c.id;
                        opt.textContent = c.name;
                        categorySelect.appendChild(opt);
                    });
                    // Populate brands
                    const brandSelect = document.getElementById('plan_brand');
                    brandSelect.innerHTML = '';
                    res.brands.forEach(b => {
                        const opt = document.createElement('option');
                        opt.value = b.id;
                        opt.textContent = b.name;
                        brandSelect.appendChild(opt);
                    });
                    // Populate markets as checkboxes
                    const marketDiv = document.getElementById('plan_market_checkboxes');
                    marketDiv.innerHTML = res.markets.map(m => `
                        <label class="market-item">
                            <input type="checkbox" name="plan_market" value="${m.id}">
                            <span>${m.name}</span>
                        </label>
                    `).join('');
                    // If editing, populate fields
                    if (el) {
                        // Show Delete button in Edit mode
                        document.getElementById('planDeleteBtn').style.display = '';
                        const id = el.dataset.id;
                        fetch('/ooh_project/handler/update_table_crud.php', {
                                method: 'POST',
                                body: new URLSearchParams({
                                    action: 'get_plan',
                                    id
                                })
                            })
                            .then(r => r.json())
                            .then(plan => {
                                document.getElementById('planModalLabel').textContent = 'Edit Plan';
                                document.getElementById('plan_id').value = plan.id;
                                document.getElementById('plan_name').value = plan.name || '';
                                document.getElementById('plan_desc').value = plan.description || '';
                                document.getElementById('plan_budget').value = plan.budget ? parseInt(plan.budget, 10).toLocaleString('en-US') : '';
                                document.getElementById('plan_start').value = plan.start_date ? plan.start_date.slice(0, 10) : '';
                                document.getElementById('plan_end').value = plan.end_date ? plan.end_date.slice(0, 10) : '';
                                document.getElementById('plan_status').value = plan.status || 'draft';
                                document.getElementById('plan_notes').value = plan.notes || '';
                                document.getElementById('plan_category').value = plan.category || '';
                                document.getElementById('plan_brand').value = plan.target_brand || '';
                                // Market focus (multi)
                                if (plan.target_market) {
                                    const selectedMarkets = plan.target_market.split(',');
                                    document.querySelectorAll('#plan_market_checkboxes input[type="checkbox"]').forEach(cb => {
                                        const marketObj = res.markets.find(m => m.id == cb.value);
                                        cb.checked = marketObj && selectedMarkets.includes(marketObj.name);
                                    });
                                }
                                var modal = new bootstrap.Modal(document.getElementById('planModal'));
                                modal.show();
                            });
                    } else {
                        document.getElementById('planDeleteBtn').style.display = '';
                        document.getElementById('planDeleteBtn').onclick = function() {
                            const id = document.getElementById('plan_id').value;
                            if (!id) return;
                            if (!confirm('Are you sure you want to delete this plan?')) return;
                            fetch('/ooh_project/handler/update_table_crud.php', {
                                    method: 'POST',
                                    body: new URLSearchParams({
                                        action: 'delete',
                                        table: 'plans',
                                        id: id
                                    })
                                })
                                .then(r => r.json())
                                .then(res => {
                                    if (res.success) {
                                        // Remove from list
                                        const ul = document.getElementById('list-plans');
                                        const li = ul.querySelector('li[data-id="' + id + '"]');
                                        if (li) li.remove();
                                        bootstrap.Modal.getInstance(document.getElementById('planModal')).hide();
                                    } else {
                                        alert(res.error || 'Failed to delete plan.');
                                    }
                                });
                        };
                        document.getElementById('planModalLabel').textContent = 'Add Plan';
                        document.getElementById('planForm').reset();
                        document.getElementById('plan_id').value = '';
                        var modal = new bootstrap.Modal(document.getElementById('planModal'));
                        modal.show();
                    }
                });
        }

        // Save Plan
        function savePlan() {
            const id = document.getElementById('plan_id').value;
            const name = document.getElementById('plan_name').value.trim();
            const desc = document.getElementById('plan_desc').value.trim();
            // Parse formatted EUR value to integer
            let budgetRaw = document.getElementById('plan_budget').value.trim();
            let budget = budgetRaw.replace(/[^\d]/g, '');
            const start = document.getElementById('plan_start').value;
            const end = document.getElementById('plan_end').value;
            const status = document.getElementById('plan_status').value;
            const notes = document.getElementById('plan_notes').value.trim();
            const category = document.getElementById('plan_category').value;
            const brand = document.getElementById('plan_brand').value;
            const marketCheckboxes = document.querySelectorAll('#plan_market_checkboxes input[type="checkbox"]');
            const markets = Array.from(marketCheckboxes).filter(cb => cb.checked).map(cb => cb.value).join(',');
            if (!name || !brand) return false;
            const payload = {
                action: id ? 'update_plan' : 'add_plan',
                id,
                name,
                description: desc,
                budget,
                start_date: start,
                end_date: end,
                status,
                notes,
                category: category,
                target_brand: brand,
                target_market: markets
            };
            fetch('/ooh_project/handler/update_table_crud.php', {
                    method: 'POST',
                    body: new URLSearchParams(payload)
                })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        // Update list
                        const ul = document.getElementById('list-plans');
                        if (id) {
                            // Edit
                            const li = ul.querySelector('li[data-id="' + id + '"]');
                            if (li) li.textContent = name;
                        } else {
                            // Add
                            const li = document.createElement('li');
                            li.className = 'list-group-item';
                            li.dataset.id = res.id;
                            li.dataset.table = 'plans';
                            li.textContent = name;
                            li.onclick = function() {
                                showPlanModal(li);
                            };
                            ul.appendChild(li);
                        }
                        bootstrap.Modal.getInstance(document.getElementById('planModal')).hide();
                    } else {
                        alert(res.error || 'Failed to save plan.');
                    }
                });
            return false;
        }

        function showUpdateModal(el) {
            document.getElementById('update_id').value = el.dataset.id;
            document.getElementById('update_table').value = el.dataset.table;
            document.getElementById('update_value').value = el.textContent.trim();
            var modal = new bootstrap.Modal(document.getElementById('updateModal'));
            modal.show();
        }

        function updateString() {
            const id = document.getElementById('update_id').value;
            const table = document.getElementById('update_table').value;
            const value = document.getElementById('update_value').value.trim();
            if (!value) return false;
            fetch('/ooh_project/handler/update_table_crud.php', {
                    method: 'POST',
                    body: new URLSearchParams({
                        action: 'update',
                        table,
                        id,
                        value
                    })
                })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        const ul = document.getElementById('list-' + table);
                        const li = ul.querySelector('li[data-id="' + id + '"]');
                        if (li) li.textContent = value;
                        bootstrap.Modal.getInstance(document.getElementById('updateModal')).hide();
                    } else {
                        alert(res.error || 'Failed to update.');
                    }
                });
            return false;
        }

        function deleteStringFromModal() {
            const id = document.getElementById('update_id').value;
            const table = document.getElementById('update_table').value;
            if (!confirm('Are you sure you want to delete this item? It may affect to other current related Modules!')) return;
            fetch('/ooh_project/handler/update_table_crud.php', {
                    method: 'POST',
                    body: new URLSearchParams({
                        action: 'delete',
                        table,
                        id
                    })
                })
                .then(r => r.json())
                .then(res => {
                    if (res.success) {
                        // Remove the item from the list
                        const ul = document.getElementById('list-' + table);
                        const li = ul.querySelector('li[data-id="' + id + '"]');
                        if (li) li.remove();
                        bootstrap.Modal.getInstance(document.getElementById('updateModal')).hide();
                    } else {
                        alert(res.error || 'Failed to delete.');
                    }
                });
        }
    </script>
</body>

</html>