<?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'],
    'planning'    => ['table' => 'planning',    '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; }
    </style>
</head>
<body>
<div class="container mt-2">
    <h2 class="mb-4 text-center">Update Database</h2>
    <div class="row">
        <?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">
                    <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>
                </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="showUpdateModal(this)" title="Click to edit">
                        <?= htmlspecialchars($row[$info['column']]) ?>
                    </li>
                    <?php endforeach; ?>
                </ul>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Update Modal -->
<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>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
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() { showUpdateModal(li); };
            ul.appendChild(li);
            form.reset();
        } else {
            alert(res.error || 'Failed to add.');
        }
    });
    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>