<?php
// Filename: admin_links.php
require 'config.php';
requireLogin();

// Permission Check
$roles = explode(',', $_SESSION['role'] ?? '');
if (!in_array('admin', array_map('trim', $roles))) {
    header("Location: dashboard.php"); exit;
}

$msg = ''; $msg_type = '';

// --- ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'delete') {
        $stmt = $pdo->prepare("DELETE FROM important_links WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        $msg = "Link deleted successfully."; $msg_type = "success";
    }
    elseif ($action === 'save') {
        $title = trim($_POST['title']);
        $url = trim($_POST['url']);
        $desc = trim($_POST['description']);
        $cat = trim($_POST['category']);
        $icon = trim($_POST['icon']);
        $color = trim($_POST['color']);
        
        // Handle Roles: If "All" is checked, store "*", otherwise comma-separated
        if (isset($_POST['role_all'])) {
            $rolesStr = '*';
        } else {
            $rolesStr = isset($_POST['roles']) ? implode(',', $_POST['roles']) : '*';
        }

        if (!empty($_POST['id'])) {
            // Update
            $stmt = $pdo->prepare("UPDATE important_links SET title=?, url=?, description=?, category=?, icon=?, color=?, target_roles=? WHERE id=?");
            $stmt->execute([$title, $url, $desc, $cat, $icon, $color, $rolesStr, $_POST['id']]);
            $msg = "Link updated."; $msg_type = "success";
        } else {
            // Insert
            $stmt = $pdo->prepare("INSERT INTO important_links (title, url, description, category, icon, color, target_roles) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$title, $url, $desc, $cat, $icon, $color, $rolesStr]);
            $msg = "New link added."; $msg_type = "success";
        }
    }
}

// Fetch Links
$links = $pdo->query("SELECT * FROM important_links ORDER BY category, sort_order ASC")->fetchAll(PDO::FETCH_ASSOC);

// Helper for Roles Checkbox
$available_roles = ['admin', 'teacher', 'student', 'principal', 'assistant', 'assistant_hem', 'akp', 'discipline_teacher', 'form6_teacher'];

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Links</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
    <style>
        body { background: #f8f9fd; font-family: 'Plus Jakarta Sans', sans-serif; padding-bottom: 80px; }
        .app-header { background: linear-gradient(135deg, #3b82f6, #06b6d4); padding: 30px 20px 80px; border-radius: 0 0 30px 30px; color: white; }
        .card-custom { border:none; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-top: -50px; background: white; }
        .icon-preview { width: 40px; height: 40px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: white; font-size: 1.2rem; }
        .btn-fab { position: fixed; bottom: 90px; right: 20px; width: 56px; height: 56px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; box-shadow: 0 4px 15px rgba(0,0,0,0.2); z-index: 100; }
    </style>
</head>
<body>

<div class="app-header text-center">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
        <h5 class="fw-bold mb-0">Manage Links</h5>
        <div style="width: 24px"></div>
    </div>
</div>

<div class="container">
    <div class="card card-custom p-3">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?>"><?= $msg ?></div><?php endif; ?>

        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th>Icon</th>
                        <th>Title / URL</th>
                        <th>Category</th>
                        <th>Roles</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($links as $l): ?>
                    <tr>
                        <td>
                            <div class="icon-preview" style="background-color: <?= htmlspecialchars($l['color']) ?>">
                                <i class="bi <?= htmlspecialchars($l['icon']) ?>"></i>
                            </div>
                        </td>
                        <td>
                            <div class="fw-bold"><?= htmlspecialchars($l['title']) ?></div>
                            <div class="small text-muted text-truncate" style="max-width: 200px;"><?= htmlspecialchars($l['url']) ?></div>
                        </td>
                        <td><span class="badge bg-light text-dark border"><?= htmlspecialchars($l['category']) ?></span></td>
                        <td>
                            <small class="text-muted">
                                <?= ($l['target_roles'] === '*') ? 'Everyone' : str_replace(',', ', ', $l['target_roles']) ?>
                            </small>
                        </td>
                        <td class="text-end">
                            <button class="btn btn-sm btn-outline-primary me-1" onclick='editLink(<?= json_encode($l) ?>)'><i class="bi bi-pencil"></i></button>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Delete this link?');">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="id" value="<?= $l['id'] ?>">
                                <button class="btn btn-sm btn-outline-danger"><i class="bi bi-trash"></i></button>
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<button class="btn btn-primary btn-fab" onclick="openModal()"><i class="bi bi-plus-lg"></i></button>

<div class="modal fade" id="linkModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content border-0 shadow">
            <div class="modal-header">
                <h5 class="modal-title fw-bold" id="modalTitle">Add Link</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="save">
                <input type="hidden" name="id" id="inp_id">
                
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Title</label>
                        <input type="text" name="title" id="inp_title" class="form-control" required placeholder="e.g. HRMIS">
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">URL</label>
                        <input type="url" name="url" id="inp_url" class="form-control" required placeholder="https://...">
                    </div>
                    <div class="mb-3">
                        <label class="form-label small fw-bold">Description</label>
                        <input type="text" name="description" id="inp_desc" class="form-control" placeholder="Short description">
                    </div>
                    
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label small fw-bold">Category</label>
                            <input type="text" list="catList" name="category" id="inp_cat" class="form-control" required>
                            <datalist id="catList">
                                <option value="KPM SSO (Core)">
                                <option value="HR & Service">
                                <option value="Teaching & Learning">
                                <option value="School Administration">
                            </datalist>
                        </div>
                        <div class="col-6">
                            <label class="form-label small fw-bold">Color</label>
                            <input type="color" name="color" id="inp_color" class="form-control form-control-color w-100" value="#3b82f6">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold">Bootstrap Icon (e.g. bi-globe)</label>
                        <div class="input-group">
                            <span class="input-group-text"><i class="bi bi-link" id="iconPreview"></i></span>
                            <input type="text" name="icon" id="inp_icon" class="form-control" value="bi-link" oninput="document.getElementById('iconPreview').className = 'bi ' + this.value">
                            <a href="https://icons.getbootstrap.com/" target="_blank" class="btn btn-outline-secondary">Find</a>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label small fw-bold">Target Roles</label>
                        <div class="form-check mb-2">
                            <input class="form-check-input" type="checkbox" name="role_all" id="inp_role_all" checked onchange="toggleRoles()">
                            <label class="form-check-label fw-bold" for="inp_role_all">Available to Everyone (*)</label>
                        </div>
                        <div id="roleCheckboxes" style="display:none; padding-left: 10px; border-left: 2px solid #eee;">
                            <?php foreach($available_roles as $r): ?>
                                <div class="form-check form-check-inline">
                                    <input class="form-check-input role-chk" type="checkbox" name="roles[]" value="<?= $r ?>" id="role_<?= $r ?>">
                                    <label class="form-check-label small" for="role_<?= $r ?>"><?= ucfirst(str_replace('_',' ', $r)) ?></label>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <div class="modal-footer border-0">
                    <button type="submit" class="btn btn-primary w-100 rounded-pill">Save Link</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include 'menu.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
const modal = new bootstrap.Modal(document.getElementById('linkModal'));

function toggleRoles() {
    const isAll = document.getElementById('inp_role_all').checked;
    document.getElementById('roleCheckboxes').style.display = isAll ? 'none' : 'block';
}

function openModal() {
    document.getElementById('modalTitle').innerText = "Add Link";
    document.getElementById('inp_id').value = "";
    document.getElementById('inp_title').value = "";
    document.getElementById('inp_url').value = "";
    document.getElementById('inp_desc').value = "";
    document.getElementById('inp_cat').value = "";
    document.getElementById('inp_icon').value = "bi-link";
    document.getElementById('inp_color').value = "#3b82f6";
    
    document.getElementById('inp_role_all').checked = true;
    document.querySelectorAll('.role-chk').forEach(c => c.checked = false);
    toggleRoles();
    
    modal.show();
}

function editLink(l) {
    document.getElementById('modalTitle').innerText = "Edit Link";
    document.getElementById('inp_id').value = l.id;
    document.getElementById('inp_title').value = l.title;
    document.getElementById('inp_url').value = l.url;
    document.getElementById('inp_desc').value = l.description;
    document.getElementById('inp_cat').value = l.category;
    document.getElementById('inp_icon').value = l.icon;
    document.getElementById('inp_color').value = l.color;
    document.getElementById('iconPreview').className = 'bi ' + l.icon;

    if (l.target_roles === '*') {
        document.getElementById('inp_role_all').checked = true;
        document.querySelectorAll('.role-chk').forEach(c => c.checked = false);
    } else {
        document.getElementById('inp_role_all').checked = false;
        const roles = l.target_roles.split(',');
        document.querySelectorAll('.role-chk').forEach(c => {
            c.checked = roles.includes(c.value);
        });
    }
    toggleRoles();
    modal.show();
}
</script>
</body>
</html>