<?php
session_start();
require_once '../config/db.php';

if (!isset($_SESSION['admin_id'])) {
    if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], ['AC', 'AAC', 'NROI', 'PPSA'])) {
        header("Location: ../officer/dashboard.php");
    } else {
        header("Location: ../index.php");
    }
    exit;
}

// Flash message retrieval
$success = $_SESSION['success_msg'] ?? null;
$error = $_SESSION['error_msg'] ?? null;
unset($_SESSION['success_msg'], $_SESSION['error_msg']);

// Handle Add/Delete Area via POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_area') {
            $areaName = trim($_POST['area_name'] ?? '');
            if (!empty($areaName)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO areas (area_name) VALUES (?)");
                    $stmt->execute([$areaName]);
                    $success = "Area added successfully!";
                } catch (Exception $e) {
                    $error = "Error: Area might already exist.";
                }
            }
        } elseif ($_POST['action'] === 'delete_area') {
            $id = $_POST['area_id'];
            $stmt = $pdo->prepare("DELETE FROM areas WHERE id = ?");
            $stmt->execute([$id]);
            $success = "Area deleted successfully!";
        } elseif ($_POST['action'] === 'add_discipline') {
            $disciplineName = trim($_POST['discipline_name'] ?? '');
            if (!empty($disciplineName)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO disciplines (name) VALUES (?)");
                    $stmt->execute([$disciplineName]);
                    $success = "Discipline added successfully!";
                } catch (Exception $e) {
                    $error = "Error: Discipline might already exist.";
                }
            }
        } elseif ($_POST['action'] === 'delete_discipline') {
            $id = $_POST['discipline_id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM disciplines WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Discipline deleted successfully!";
            }
        } elseif ($_POST['action'] === 'add_procedural') {
            $val = trim($_POST['procedural_name'] ?? '');
            if (!empty($val)) {
                try {
                    $check = $pdo->prepare("SELECT COUNT(*) FROM reference_procedural WHERE name = ?");
                    $check->execute([$val]);
                    if ($check->fetchColumn() > 0) {
                        $error = "Error: Procedural reference already exists.";
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO reference_procedural (name) VALUES (?)");
                        $stmt->execute([$val]);
                        $success = "Procedural reference added successfully!";
                    }
                } catch (Exception $e) {
                    $error = "Error adding procedural reference.";
                }
            }
        } elseif ($_POST['action'] === 'delete_procedural') {
            $id = $_POST['procedural_id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM reference_procedural WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Procedural reference deleted successfully!";
            }
        } elseif ($_POST['action'] === 'edit_procedural') {
            $id = $_POST['procedural_id'] ?? null;
            $newName = trim($_POST['procedural_name'] ?? '');
            if ($id && !empty($newName)) {
                $stmt = $pdo->prepare("UPDATE reference_procedural SET name = ? WHERE id = ?");
                $stmt->execute([$newName, $id]);
                $success = "Procedural reference updated!";
            }
        } elseif ($_POST['action'] === 'add_disqualification') {
            $val = trim($_POST['disqualification_name'] ?? '');
            if (!empty($val)) {
                try {
                    $check = $pdo->prepare("SELECT COUNT(*) FROM reference_disqualification WHERE name = ?");
                    $check->execute([$val]);
                    if ($check->fetchColumn() > 0) {
                        $error = "Error: Disqualification reference already exists.";
                    } else {
                        $stmt = $pdo->prepare("INSERT INTO reference_disqualification (name) VALUES (?)");
                        $stmt->execute([$val]);
                        $success = "Disqualification reference added successfully!";
                    }
                } catch (Exception $e) {
                    $error = "Error adding disqualification reference.";
                }
            }
        } elseif ($_POST['action'] === 'delete_disqualification') {
            $id = $_POST['disqualification_id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM reference_disqualification WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Disqualification reference deleted successfully!";
            }
        } elseif ($_POST['action'] === 'edit_disqualification') {
            $id = $_POST['disqualification_id'] ?? null;
            $newName = trim($_POST['disqualification_name'] ?? '');
            if ($id && !empty($newName)) {
                $stmt = $pdo->prepare("UPDATE reference_disqualification SET name = ? WHERE id = ?");
                $stmt->execute([$newName, $id]);
                $success = "Disqualification reference updated!";
            }
        } elseif ($_POST['action'] === 'add_form') {
            $title = trim($_POST['title'] ?? '');
            $notes = trim($_POST['notes'] ?? '');
            if (!empty($title)) {
                $pdo->beginTransaction();
                try {
                    $stmt = $pdo->prepare("INSERT INTO forms (title, notes) VALUES (?, ?)");
                    $stmt->execute([$title, $notes]);
                    $formId = $pdo->lastInsertId();

                    // Handle PDF uploads
                    if (!empty($_FILES['pdf_files']['name'][0])) {
                        for ($i = 0; $i < count($_FILES['pdf_files']['name']); $i++) {
                            if ($_FILES['pdf_files']['error'][$i] === UPLOAD_ERR_OK) {
                                $name = $_FILES['pdf_files']['name'][$i];
                                $ext = pathinfo($name, PATHINFO_EXTENSION);
                                $newName = 'form_' . $formId . '_pdf_' . time() . '_' . $i . '.' . $ext;
                                $dest = '../storage/forms/pdf/' . $newName;
                                if (move_uploaded_file($_FILES['pdf_files']['tmp_name'][$i], $dest)) {
                                    $stmt = $pdo->prepare("INSERT INTO form_attachments (form_id, file_path, file_type, original_name) VALUES (?, ?, 'pdf', ?)");
                                    $stmt->execute([$formId, 'storage/forms/pdf/' . $newName, $name]);
                                }
                            }
                        }
                    }

                    // Handle Image uploads
                    if (!empty($_FILES['image_files']['name'][0])) {
                        for ($i = 0; $i < count($_FILES['image_files']['name']); $i++) {
                            if ($_FILES['image_files']['error'][$i] === UPLOAD_ERR_OK) {
                                $name = $_FILES['image_files']['name'][$i];
                                $ext = pathinfo($name, PATHINFO_EXTENSION);
                                $newName = 'form_' . $formId . '_img_' . time() . '_' . $i . '.' . $ext;
                                $dest = '../storage/forms/images/' . $newName;
                                if (move_uploaded_file($_FILES['image_files']['tmp_name'][$i], $dest)) {
                                    $stmt = $pdo->prepare("INSERT INTO form_attachments (form_id, file_path, file_type, original_name) VALUES (?, ?, 'image', ?)");
                                    $stmt->execute([$formId, 'storage/forms/images/' . $newName, $name]);
                                }
                            }
                        }
                    }

                    $pdo->commit();
                    $success = "Form added successfully!";
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "Error adding form: " . $e->getMessage();
                }
            }
        } elseif ($_POST['action'] === 'delete_form') {
            $id = $_POST['form_id'] ?? null;
            if ($id) {
                // Fetch attachments to delete files
                $stmt = $pdo->prepare("SELECT file_path FROM form_attachments WHERE form_id = ?");
                $stmt->execute([$id]);
                $files = $stmt->fetchAll();
                foreach ($files as $f) {
                    @unlink('../' . $f['file_path']);
                }

                $stmt = $pdo->prepare("DELETE FROM forms WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Form deleted successfully!";
            }
        } elseif ($_POST['action'] === 'edit_form') {
            $id = $_POST['form_id'] ?? null;
            $title = trim($_POST['title'] ?? '');
            $notes = trim($_POST['notes'] ?? '');
            if ($id && !empty($title)) {
                $pdo->beginTransaction();
                try {
                    $stmt = $pdo->prepare("UPDATE forms SET title = ?, notes = ? WHERE id = ?");
                    $stmt->execute([$title, $notes, $id]);

                    // Handle new PDF uploads
                    if (!empty($_FILES['pdf_files']['name'][0])) {
                        for ($i = 0; $i < count($_FILES['pdf_files']['name']); $i++) {
                            if ($_FILES['pdf_files']['error'][$i] === UPLOAD_ERR_OK) {
                                $name = $_FILES['pdf_files']['name'][$i];
                                $ext = pathinfo($name, PATHINFO_EXTENSION);
                                $newName = 'form_' . $id . '_pdf_' . time() . '_' . $i . '.' . $ext;
                                $dest = '../storage/forms/pdf/' . $newName;
                                if (move_uploaded_file($_FILES['pdf_files']['tmp_name'][$i], $dest)) {
                                    $stmt = $pdo->prepare("INSERT INTO form_attachments (form_id, file_path, file_type, original_name) VALUES (?, ?, 'pdf', ?)");
                                    $stmt->execute([$id, 'storage/forms/pdf/' . $newName, $name]);
                                }
                            }
                        }
                    }

                    // Handle new Image uploads
                    if (!empty($_FILES['image_files']['name'][0])) {
                        for ($i = 0; $i < count($_FILES['image_files']['name']); $i++) {
                            if ($_FILES['image_files']['error'][$i] === UPLOAD_ERR_OK) {
                                $name = $_FILES['image_files']['name'][$i];
                                $ext = pathinfo($name, PATHINFO_EXTENSION);
                                $newName = 'form_' . $id . '_img_' . time() . '_' . $i . '.' . $ext;
                                $dest = '../storage/forms/images/' . $newName;
                                if (move_uploaded_file($_FILES['image_files']['tmp_name'][$i], $dest)) {
                                    $stmt = $pdo->prepare("INSERT INTO form_attachments (form_id, file_path, file_type, original_name) VALUES (?, ?, 'image', ?)");
                                    $stmt->execute([$id, 'storage/forms/images/' . $newName, $name]);
                                }
                            }
                        }
                    }

                    $pdo->commit();
                    $success = "Form updated successfully!";
                } catch (Exception $e) {
                    $pdo->rollBack();
                    $error = "Error updating form: " . $e->getMessage();
                }
            }
        } elseif ($_POST['action'] === 'delete_attachment') {
            $attachmentId = $_POST['attachment_id'] ?? null;
            if ($attachmentId) {
                $stmt = $pdo->prepare("SELECT file_path FROM form_attachments WHERE id = ?");
                $stmt->execute([$attachmentId]);
                $file = $stmt->fetch();
                if ($file) {
                    @unlink('../' . $file['file_path']);
                    $stmt = $pdo->prepare("DELETE FROM form_attachments WHERE id = ?");
                    $stmt->execute([$attachmentId]);
                    $success = "Attachment removed!";
                }
            }
        } elseif ($_POST['action'] === 'add_match_assignment') {
            $val = trim($_POST['assignment_name'] ?? '');
            if (!empty($val)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO reference_match_assignments (name) VALUES (?)");
                    $stmt->execute([$val]);

                    // Auto-create table for this assignment
                    $type = strtolower(str_replace(' ', '_', $val));
                    $table = 'match_' . $type . '_assignments';
                    $pdo->exec("
                        CREATE TABLE IF NOT EXISTS `$table` (
                            `id` INT AUTO_INCREMENT PRIMARY KEY,
                            `match_id` INT NOT NULL,
                            `officer_name` VARCHAR(255) NOT NULL,
                            `role` VARCHAR(100) NULL,
                            `rm_signature` VARCHAR(255) NULL,
                            `submitted_by` INT NOT NULL,
                            `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                            UNIQUE KEY `unique_m_u_$type` (`match_id`, `submitted_by`)
                        )
                    ");

                    $success = "Match Assignment added and table initialized!";
                } catch (Exception $e) {
                    $error = "Error: " . $e->getMessage();
                }
            }
        } elseif ($_POST['action'] === 'delete_match_assignment') {
            $id = $_POST['assignment_id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM reference_match_assignments WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Match Assignment deleted successfully!";
            }
        } elseif ($_POST['action'] === 'edit_match_assignment') {
            $id = $_POST['assignment_id'] ?? null;
            $newName = trim($_POST['assignment_name'] ?? '');
            if ($id && !empty($newName)) {
                $stmt = $pdo->prepare("UPDATE reference_match_assignments SET name = ? WHERE id = ?");
                $stmt->execute([$newName, $id]);

                // Also ensure table exists for NEW name
                $type = strtolower(str_replace(' ', '_', $newName));
                $table = 'match_' . $type . '_assignments';
                $pdo->exec("
                    CREATE TABLE IF NOT EXISTS `$table` (
                        `id` INT AUTO_INCREMENT PRIMARY KEY,
                        `match_id` INT NOT NULL,
                        `officer_name` VARCHAR(255) NOT NULL,
                        `role` VARCHAR(100) NULL,
                        `rm_signature` VARCHAR(255) NULL,
                        `submitted_by` INT NOT NULL,
                        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        UNIQUE KEY `unique_m_u_$type` (`match_id`, `submitted_by`)
                    )
                ");

                $success = "Match Assignment updated and table verified!";
            }
            // Handle Add/Delete Match Role via POST
        } elseif ($_POST['action'] === 'add_match_role') {
            $val = trim($_POST['role_name'] ?? '');
            if (!empty($val)) {
                try {
                    $stmt = $pdo->prepare("INSERT INTO reference_match_roles (name) VALUES (?)");
                    $stmt->execute([$val]);
                    $success = "Match Role added successfully!";
                } catch (Exception $e) {
                    $error = "Error: Role might already exist.";
                }
            }
        } elseif ($_POST['action'] === 'delete_match_role') {
            $id = $_POST['role_id'] ?? null;
            if ($id) {
                $stmt = $pdo->prepare("DELETE FROM reference_match_roles WHERE id = ?");
                $stmt->execute([$id]);
                $success = "Match Role deleted successfully!";
            }
        } elseif ($_POST['action'] === 'edit_match_role') {
            $id = $_POST['role_id'] ?? null;
            $newName = trim($_POST['role_name'] ?? '');
            if ($id && !empty($newName)) {
                $stmt = $pdo->prepare("UPDATE reference_match_roles SET name = ? WHERE id = ?");
                $stmt->execute([$newName, $id]);
                $success = "Match Role updated!";
            }
        }

        // Redirect after POST to prevent resubmission
        if (isset($success))
            $_SESSION['success_msg'] = $success;
        if (isset($error))
            $_SESSION['error_msg'] = $error;
        header("Location: management.php");
        exit;
    }
}
try {
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS disciplines (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL UNIQUE
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS reference_procedural (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name LONGTEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS reference_disqualification (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name LONGTEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS forms (
            id INT AUTO_INCREMENT PRIMARY KEY,
            title VARCHAR(255) NOT NULL,
            notes TEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS form_attachments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            form_id INT NOT NULL,
            file_path VARCHAR(255) NOT NULL,
            file_type ENUM('pdf', 'image') NOT NULL,
            original_name VARCHAR(255) NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (form_id) REFERENCES forms(id) ON DELETE CASCADE
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS reference_match_assignments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL UNIQUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS reference_match_roles (
            id INT AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL UNIQUE,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )
    ");
    // Upgrade name column to LONGTEXT if still VARCHAR or TEXT
    try {
        $pdo->exec("ALTER TABLE reference_procedural DROP INDEX `name`");
    } catch (Exception $e) {
    }
    try {
        $pdo->exec("ALTER TABLE reference_disqualification DROP INDEX `name`");
    } catch (Exception $e) {
    }
    try {
        $pdo->exec("ALTER TABLE reference_procedural MODIFY name LONGTEXT NOT NULL");
    } catch (Exception $e) {
    }
    try {
        $pdo->exec("ALTER TABLE reference_disqualification MODIFY name LONGTEXT NOT NULL");
    } catch (Exception $e) {
    }
} catch (Exception $e) {
    // ignore
}

// Fetch all areas
$stmt = $pdo->query("SELECT * FROM areas");
$areasRaw = $stmt->fetchAll();
// Natural sort areas so 1, 2, 3, 10 appears in correct numeric order
usort($areasRaw, function ($a, $b) {
    return strnatcasecmp($a['area_name'], $b['area_name']);
});
$areas = $areasRaw;

// Fetch all disciplines
$stmtDisc = $pdo->query("SELECT * FROM disciplines WHERE name != 'Bad Record' ORDER BY name ASC");
$disciplines = $stmtDisc->fetchAll();

// Fetch procedural references — natural sort so 10.1 comes after 10, 10.4.1 after 10.4
$stmtProc = $pdo->query("SELECT * FROM reference_procedural");
$procRaw = $stmtProc->fetchAll();
usort($procRaw, function ($a, $b) {
    return strnatcasecmp($a['name'], $b['name']);
});
$procedurals = $procRaw;

// Fetch disqualification references — natural sort
$stmtDq = $pdo->query("SELECT * FROM reference_disqualification");
$dqRaw = $stmtDq->fetchAll();
usort($dqRaw, function ($a, $b) {
    return strnatcasecmp($a['name'], $b['name']);
});
$disqualifications = $dqRaw;

// Fetch all forms
$stmtForms = $pdo->query("SELECT * FROM forms ORDER BY created_at DESC");
$forms = $stmtForms->fetchAll();

// Fetch all attachments grouped by form_id
$stmtAtt = $pdo->query("SELECT * FROM form_attachments");
$attachmentsRaw = $stmtAtt->fetchAll();
$attachments = [];
foreach ($attachmentsRaw as $att) {
    if (!isset($attachments[$att['form_id']])) {
        $attachments[$att['form_id']] = [];
    }
    $attachments[$att['form_id']][] = $att;
}

// Fetch dynamic Match Assignments
$stmtMA = $pdo->query("SELECT * FROM reference_match_assignments ORDER BY name ASC");
$matchAssignments = $stmtMA->fetchAll();

// Fetch dynamic Match Roles
$stmtMR = $pdo->query("SELECT * FROM reference_match_roles ORDER BY name ASC");
$matchRoles = $stmtMR->fetchAll();

// Helper: detect indentation level based on leading number (e.g. 10.4.1 = level 2)
function getRefIndentLevel(string $name): int
{
    if (preg_match('/^(\d+(?:\.\d+)+)/', $name, $m)) {
        return substr_count($m[1], '.');
    }
    return 0;
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Management | NROI Portal</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/loader.css">
    <link rel="stylesheet" href="../assets/css/style.css">
    <link rel="stylesheet" href="../assets/css/dashboard.css">
    <link rel="icon" type="image/png" href="../assets/images/nroi_logo.png">
    <style>
        .mgmt-card {
            background: #fff;
            border-radius: 16px;
            padding: 25px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
            margin-bottom: 30px;
            display: flex;
            flex-direction: column;
            height: 100%;
        }

        .mgmt-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            border-bottom: 1px solid #f1f5f9;
            padding-bottom: 15px;
        }

        .area-list-toggle {
            background: #f8fafc;
            padding: 12px 15px;
            border-radius: 12px;
            border: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .area-list-toggle:hover {
            border-color: var(--primary-color);
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        }

        .area-list-toggle .area-name-wrap {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .area-list-toggle .area-name {
            font-weight: 600;
            color: #1e293b;
        }

        .area-list-toggle .area-chevron {
            color: #94a3b8;
            font-size: 0.75rem;
            transition: transform 0.2s ease;
        }

        .area-list-toggle.expanded .area-chevron {
            transform: rotate(180deg);
        }

        .area-list-wrapper {
            position: relative;
        }

        .area-list-dropdown {
            display: none;
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            margin-top: 8px;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            overflow: hidden;
            background: #fff;
            z-index: 50;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
        }

        .area-list-dropdown.open {
            display: block;
        }

        .area-list {
            max-height: 220px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 0;
            padding-right: 0;
        }

        /* Modal Styles for Forms */
        #formModal {
            display: none;
            position: fixed;
            z-index: 2000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(4px);
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        #formModal .modal-content {
            background: white;
            padding: 30px;
            border-radius: 20px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 50px rgba(0, 0, 0, 0.2);
            animation: slideUp 0.3s ease;
        }

        @keyframes slideUp {
            from {
                transform: translateY(30px);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .area-list::-webkit-scrollbar {
            width: 6px;
        }

        .area-list::-webkit-scrollbar-thumb {
            background: #cbd5e1;
            border-radius: 3px;
        }

        .area-item {
            background: #fff;
            padding: 10px 15px;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 8px;
            transition: background 0.2s;
        }

        .area-item:last-child {
            border-bottom: none;
        }

        .area-item:hover {
            background: #f8fafc;
        }

        .area-item .area-name {
            font-weight: 600;
            color: #1e293b;
            flex: 1;
            min-width: 0;
            word-break: break-word;
            overflow-wrap: anywhere;
            white-space: normal;
            line-height: 1.5;
        }

        .area-item form {
            margin: 0;
        }

        .btn-delete {
            background: none;
            border: none;
            color: #ef4444;
            cursor: pointer;
            padding: 6px 10px;
            border-radius: 8px;
            transition: background 0.2s, opacity 0.2s;
        }

        .btn-delete:hover {
            background: #fef2f2;
            opacity: 1;
        }

        .add-area-form {
            display: flex;
            gap: 10px;
            width: 100%;
            margin-bottom: 25px;
        }

        .add-area-form .form-input {
            flex: 1;
        }

        .alert {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 0.9rem;
        }

        .alert-success {
            background: #d1fae5;
            color: #065f46;
            border: 1px solid #6ee7b7;
        }

        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fca5a5;
        }

        .mgmt-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
            align-items: stretch;
        }

        @media (max-width: 1024px) {
            .mgmt-grid {
                grid-template-columns: 1fr;
            }
        }

        .ref-section {
            margin-top: 30px;
        }

        .ref-section-header {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 18px;
            padding-bottom: 12px;
            border-bottom: 2px solid #e2e8f0;
        }

        .ref-section-header h3 {
            margin: 0;
            font-size: 1.05rem;
            font-weight: 700;
            color: #1e293b;
        }

        .ref-section-header .ref-icon {
            width: 34px;
            height: 34px;
            border-radius: 10px;
            background: linear-gradient(135deg, #6366f1, #8b5cf6);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 0.85rem;
            flex-shrink: 0;
        }

        .ref-inner-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        @media (max-width: 768px) {
            .ref-inner-grid {
                grid-template-columns: 1fr;
            }
        }

        .ref-textarea {
            resize: vertical;
            min-height: 60px;
            font-family: inherit;
            font-size: 0.95rem;
            line-height: 1.5;
            padding: 10px 14px;
        }

        .ref-entry {
            white-space: pre-wrap;
            word-break: break-word;
            line-height: 1.5;
        }
    </style>
</head>

<body class="dashboard-body">
    <?php include '../includes/loader.php'; ?>

    <aside class="sidebar">
        <div class="sidebar-brand-area">
            <div class="sidebar-role-badge">ADMIN</div>
        </div>
        <ul class="sidebar-menu">
            <li class="sidebar-item">
                <a href="dashboard.php" class="sidebar-link">
                    <i class="fas fa-th-large"></i> Overview
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/users.php" class="sidebar-link">
                    <i class="fas fa-user-friends"></i> Accounts
                </a>
            </li>
            <li class="sidebar-item">
                <a href="management.php" class="sidebar-link active">
                    <i class="fas fa-cog"></i> Management
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/matches.php" class="sidebar-link">
                    <i class="fas fa-trophy"></i> Matches
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/request.php" class="sidebar-link">
                    <i class="fas fa-inbox"></i> For Approval
                </a>
            </li>
            <li class="sidebar-item">
                <a href="../api/points_card.php" class="sidebar-link">
                    <i class="fas fa-id-card"></i> Points Card
                </a>
            </li>
            <li class="sidebar-item">
                <a href="system_logs.php" class="sidebar-link">
                    <i class="fas fa-list-alt"></i> System Log
                </a>
            </li>
        </ul>

        <div class="sidebar-profile">
            <div class="sidebar-user-card" id="profileToggle">
                <div class="user-avatar" style="width: 35px; height: 35px; min-width: 35px;">AD</div>
                <div class="sidebar-user-info">
                    <div class="sidebar-user-name">Administrator</div>
                    <div class="sidebar-user-role">System Admin</div>
                </div>
                <i class="fas fa-chevron-up" style="font-size: 0.7rem; color: #94a3b8;"></i>

                <div class="profile-dropdown" id="profileDropdown"
                    style="bottom: 100%; top: auto; right: 10px; left: 10px; width: auto; margin-bottom: 10px;">
                    <a href="profile.php" class="dropdown-item"><i class="far fa-user-circle"></i> My Profile</a>
                    <div style="height: 1px; background: rgba(0,0,0,0.05); margin: 5px 0;"></div>
                    <a href="../logout.php" class="dropdown-item logout"><i class="fas fa-sign-out-alt"></i> Logout</a>
                </div>
            </div>
        </div>
    </aside>

    <div class="main-layout">
        <main class="content-wrapper">
            <header class="welcome-header">
                <div class="header-brand-box">
                    <img src="../assets/images/nroi_logo.png" alt="NROI Logo" class="header-logo">
                    <div class="header-text">
                        <h2>NATIONAL RANGE OFFICERS INSTITUTE</h2>
                        <p>SYSTEM MANAGEMENT</p>
                    </div>
                </div>
            </header>

            <?php if (isset($success)): ?>
                <div class="alert alert-success"><i class="fas fa-check-circle"></i>
                    <?php echo $success; ?>
                </div>
            <?php endif; ?>

            <?php if (isset($error)): ?>
                <div class="alert alert-error"><i class="fas fa-exclamation-circle"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>

            <div class="mgmt-grid">
                <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                    <div class="mgmt-header">
                        <h3 style="margin:0"><i class="fas fa-map-marked-alt" style="color:var(--primary-color);"></i>
                            Area</h3>
                    </div>

                    <form class="add-area-form" method="POST">
                        <input type="hidden" name="action" value="add_area">
                        <input type="text" name="area_name" class="form-input"
                            placeholder="Enter Area Number/Name (e.g. Area 1)" required style="margin:0">
                        <button type="submit" class="btn-primary" style="width:auto; margin:0; white-space:nowrap;">Add
                            Area</button>
                    </form>

                    <div class="area-list-wrapper">
                        <?php if (empty($areas)): ?>
                            <p style="color:#94a3b8; padding:20px;">No areas registered yet.</p>
                        <?php else: ?>
                            <div class="area-list-toggle" id="areaListToggle" tabindex="0" role="button">
                                <div class="area-name-wrap">
                                    <span class="area-name">Available Area</span>
                                    <i class="fas fa-chevron-down area-chevron"></i>
                                </div>
                            </div>
                            <div class="area-list-dropdown" id="areaListDropdown">
                                <div class="area-list">
                                    <?php foreach ($areas as $area): ?>
                                        <div class="area-item">
                                            <span class="area-name"><?php echo htmlspecialchars($area['area_name']); ?></span>
                                            <form method="POST" style="margin:0"
                                                onsubmit="return confirm('Are you sure you want to delete this area?')">
                                                <input type="hidden" name="action" value="delete_area">
                                                <input type="hidden" name="area_id" value="<?php echo $area['id']; ?>">
                                                <button type="submit" class="btn-delete" title="Delete area"><i
                                                        class="fas fa-trash-can"></i></button>
                                            </form>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                    <div class="mgmt-header">
                        <h3 style="margin:0"><i class="fas fa-scale-balanced" style="color:var(--primary-color);"></i>
                            Discipline</h3>
                    </div>

                    <form class="add-area-form" method="POST">
                        <input type="hidden" name="action" value="add_discipline">
                        <input type="text" name="discipline_name" id="discipline_name" class="form-input"
                            placeholder="Enter Discipline (e.g. Noted, Warning, Suspension)" required style="margin:0">
                        <button type="submit" class="btn-primary" style="width:auto; margin:0; white-space:nowrap;">Add
                            Discipline</button>
                    </form>

                    <div class="area-list-wrapper">
                        <?php if (empty($disciplines)): ?>
                            <p style="color:#94a3b8; padding:20px;">No disciplines configured yet.</p>
                        <?php else: ?>
                            <div class="area-list-toggle" id="disciplineListToggle" tabindex="0" role="button">
                                <div class="area-name-wrap">
                                    <span class="area-name">Available Discipline</span>
                                    <i class="fas fa-chevron-down area-chevron"></i>
                                </div>
                            </div>
                            <div class="area-list-dropdown" id="disciplineListDropdown">
                                <div class="area-list">
                                    <?php foreach ($disciplines as $discipline): ?>
                                        <div class="area-item">
                                            <span class="area-name"><?php echo htmlspecialchars($discipline['name']); ?></span>
                                            <form method="POST" style="margin:0"
                                                onsubmit="return confirm('Are you sure you want to delete this discipline?')">
                                                <input type="hidden" name="action" value="delete_discipline">
                                                <input type="hidden" name="discipline_id"
                                                    value="<?php echo $discipline['id']; ?>">
                                                <button type="submit" class="btn-delete" title="Delete discipline"><i
                                                        class="fas fa-trash-can"></i></button>
                                            </form>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div> <!-- CLOSE OUTER GRID -->

            <div class="mgmt-grid" style="margin-top: 25px;">
                <!-- Match Assignment Card -->
                <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                    <div class="mgmt-header">
                        <h3 style="margin:0"><i class="fas fa-clipboard-check" style="color:var(--primary-color);"></i>
                            Match Assignment</h3>
                    </div>

                    <form class="add-area-form" method="POST">
                        <input type="hidden" name="action" value="add_match_assignment">
                        <input type="text" name="assignment_name" class="form-input"
                            placeholder="Enter Assignment (e.g. Stage 1, Chrono)" required style="margin:0">
                        <button type="submit" class="btn-primary"
                            style="width:auto; margin:0; white-space:nowrap;">Add</button>
                    </form>

                    <div
                        style="flex: 1; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; background: #fff;">
                        <div
                            style="background: #f8fafc; padding: 12px 15px; border-bottom: 1px solid #e2e8f0; font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                            Available Match Assignments
                        </div>
                        <div style="max-height: 300px; overflow-y: auto;">
                            <?php if (empty($matchAssignments)): ?>
                                <p style="color:#94a3b8; padding:20px; text-align: center; margin: 0;">No assignments
                                    yet.</p>
                            <?php else: ?>
                                <?php foreach ($matchAssignments as $ma): ?>
                                    <div class="area-item">
                                        <div id="view-match_assignment-<?php echo $ma['id']; ?>"
                                            style="display: flex; width: 100%; justify-content: space-between; align-items: center; gap: 10px;">
                                            <span class="area-name"><?php echo htmlspecialchars($ma['name']); ?></span>
                                            <div style="display: flex; gap: 5px; flex-shrink: 0;">
                                                <button type="button" class="btn-delete"
                                                    style="color: var(--primary-color); background: #f0f3ff;"
                                                    onclick="toggleEdit('match_assignment', <?php echo $ma['id']; ?>)"
                                                    title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" style="margin:0"
                                                    onsubmit="return confirm('Are you sure you want to delete this assignment?')">
                                                    <input type="hidden" name="action" value="delete_match_assignment">
                                                    <input type="hidden" name="assignment_id" value="<?php echo $ma['id']; ?>">
                                                    <button type="submit" class="btn-delete" title="Delete assignment"><i
                                                            class="fas fa-trash-can"></i></button>
                                                </form>
                                            </div>
                                        </div>
                                        <div id="edit-match_assignment-<?php echo $ma['id']; ?>"
                                            style="display: none; width: 100%;">
                                            <form method="POST" style="margin:0; width: 100%; display: flex; gap: 8px;">
                                                <input type="hidden" name="action" value="edit_match_assignment">
                                                <input type="hidden" name="assignment_id" value="<?php echo $ma['id']; ?>">
                                                <input type="text" name="assignment_name" class="form-input"
                                                    value="<?php echo htmlspecialchars($ma['name']); ?>" required
                                                    style="flex:1; margin:0;">
                                                <button type="button" class="btn-secondary"
                                                    style="width: auto; padding: 6px 12px; font-size: 0.8rem;"
                                                    onclick="toggleEdit('match_assignment', <?php echo $ma['id']; ?>)">Cancel</button>
                                                <button type="submit" class="btn-primary"
                                                    style="width: auto; padding: 6px 12px; font-size: 0.8rem; margin: 0;">Save</button>
                                            </form>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Match Role Card -->
                <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                    <div class="mgmt-header">
                        <h3 style="margin:0"><i class="fas fa-user-tag" style="color:var(--primary-color);"></i>
                            Match Role</h3>
                    </div>

                    <form class="add-area-form" method="POST">
                        <input type="hidden" name="action" value="add_match_role">
                        <input type="text" name="role_name" class="form-input"
                            placeholder="Enter Role (e.g. Range Officer, CRO)" required style="margin:0">
                        <button type="submit" class="btn-primary"
                            style="width:auto; margin:0; white-space:nowrap;">Add</button>
                    </form>

                    <div
                        style="flex: 1; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; background: #fff;">
                        <div
                            style="background: #f8fafc; padding: 12px 15px; border-bottom: 1px solid #e2e8f0; font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                            Available Match Roles
                        </div>
                        <div style="max-height: 300px; overflow-y: auto;">
                            <?php if (empty($matchRoles)): ?>
                                <p style="color:#94a3b8; padding:20px; text-align: center; margin: 0;">No roles yet.</p>
                            <?php else: ?>
                                <?php foreach ($matchRoles as $mr): ?>
                                    <div class="area-item">
                                        <div id="view-match_role-<?php echo $mr['id']; ?>"
                                            style="display: flex; width: 100%; justify-content: space-between; align-items: center; gap: 10px;">
                                            <span class="area-name"><?php echo htmlspecialchars($mr['name']); ?></span>
                                            <div style="display: flex; gap: 5px; flex-shrink: 0;">
                                                <button type="button" class="btn-delete"
                                                    style="color: var(--primary-color); background: #f0f3ff;"
                                                    onclick="toggleEdit('match_role', <?php echo $mr['id']; ?>)" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <form method="POST" style="margin:0"
                                                    onsubmit="return confirm('Are you sure you want to delete this role?')">
                                                    <input type="hidden" name="action" value="delete_match_role">
                                                    <input type="hidden" name="role_id" value="<?php echo $mr['id']; ?>">
                                                    <button type="submit" class="btn-delete" title="Delete role"><i
                                                            class="fas fa-trash-can"></i></button>
                                                </form>
                                            </div>
                                        </div>
                                        <div id="edit-match_role-<?php echo $mr['id']; ?>" style="display: none; width: 100%;">
                                            <form method="POST" style="margin:0; width: 100%; display: flex; gap: 8px;">
                                                <input type="hidden" name="action" value="edit_match_role">
                                                <input type="hidden" name="role_id" value="<?php echo $mr['id']; ?>">
                                                <input type="text" name="role_name" class="form-input"
                                                    value="<?php echo htmlspecialchars($mr['name']); ?>" required
                                                    style="flex:1; margin:0;">
                                                <button type="button" class="btn-secondary"
                                                    style="width: auto; padding: 6px 12px; font-size: 0.8rem;"
                                                    onclick="toggleEdit('match_role', <?php echo $mr['id']; ?>)">Cancel</button>
                                                <button type="submit" class="btn-primary"
                                                    style="width: auto; padding: 6px 12px; font-size: 0.8rem; margin: 0;">Save</button>
                                            </form>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div> <!-- CLOSE MATCH ASGN GRID -->

            <!-- Form Section -->
            <div class="ref-section">
                <div class="ref-section-header">
                    <div class="ref-icon" style="background: linear-gradient(135deg, #10b981, #059669);"><i
                            class="fas fa-file-invoice"></i></div>
                    <h3>Form Management</h3>
                    <button class="btn-primary" onclick="showAddForm()" style="width:auto; margin-left:auto;"><i
                            class="fas fa-plus"></i> Add New Form</button>
                </div>

                <div class="mgmt-card animated-fade-in">
                    <div style="overflow-x: auto;">
                        <table class="modern-table">
                            <thead>
                                <tr>
                                    <th>Title</th>
                                    <th>Notes</th>
                                    <th>Attachments</th>
                                    <th style="text-align: right;">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (empty($forms)): ?>
                                    <tr>
                                        <td colspan="4" style="text-align:center; padding:40px; color:#94a3b8;">No forms
                                            available. Click "Add New Form" to create one.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($forms as $form): ?>
                                        <tr>
                                            <td style="font-weight:700; color:#1e293b;">
                                                <?php echo htmlspecialchars($form['title']); ?>
                                            </td>
                                            <td style="color:#64748b; font-size:0.9rem; max-width:300px;">
                                                <?php echo nl2br(htmlspecialchars($form['notes'])); ?>
                                            </td>
                                            <td>
                                                <?php if (isset($attachments[$form['id']])): ?>
                                                    <?php
                                                    $pdfFiles = array_filter($attachments[$form['id']], function ($a) {
                                                        return $a['file_type'] === 'pdf';
                                                    });
                                                    $imgFiles = array_filter($attachments[$form['id']], function ($a) {
                                                        return $a['file_type'] === 'image';
                                                    });
                                                    ?>

                                                    <?php if (!empty($pdfFiles)): ?>
                                                        <div style="margin-bottom: 12px;">
                                                            <div
                                                                style="font-size: 0.65rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; display: flex; align-items: center; gap: 4px;">
                                                                <i class="fas fa-file-pdf" style="font-size: 0.7rem;"></i> PDF
                                                                Documents
                                                            </div>
                                                            <div style="display:flex; flex-wrap:wrap; gap:8px;">
                                                                <?php foreach ($pdfFiles as $att): ?>
                                                                    <a href="../<?php echo $att['file_path']; ?>" target="_blank"
                                                                        title="<?php echo htmlspecialchars($att['original_name']); ?>"
                                                                        style="padding:6px 12px; background:#fdf2f2; border: 1px solid #fee2e2; border-radius:8px; color:#991b1b; text-decoration:none; font-size:0.75rem; display:flex; align-items:center; gap:6px; transition: all 0.2s ease;">
                                                                        <i class="fas fa-file-pdf" style="color:#ef4444;"></i>
                                                                        <span
                                                                            style="max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?php echo htmlspecialchars($att['original_name']); ?></span>
                                                                    </a>
                                                                <?php endforeach; ?>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php if (!empty($imgFiles)): ?>
                                                        <div>
                                                            <div
                                                                style="font-size: 0.65rem; font-weight: 800; color: #94a3b8; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 6px; display: flex; align-items: center; gap: 4px;">
                                                                <i class="fas fa-file-image" style="font-size: 0.7rem;"></i> Image
                                                                Gallery
                                                            </div>
                                                            <div style="display:flex; flex-wrap:wrap; gap:8px;">
                                                                <?php foreach ($imgFiles as $att): ?>
                                                                    <a href="../<?php echo $att['file_path']; ?>" target="_blank"
                                                                        title="<?php echo htmlspecialchars($att['original_name']); ?>"
                                                                        style="padding:6px 12px; background:#f0f7ff; border: 1px solid #e0f2fe; border-radius:8px; color:#075985; text-decoration:none; font-size:0.75rem; display:flex; align-items:center; gap:6px; transition: all 0.2s ease;">
                                                                        <i class="fas fa-file-image" style="color:#3b82f6;"></i>
                                                                        <span
                                                                            style="max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"><?php echo htmlspecialchars($att['original_name']); ?></span>
                                                                    </a>
                                                                <?php endforeach; ?>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php else: ?>
                                                    <span style="color:#cbd5e1; font-size:0.8rem;">No attachments</span>
                                                <?php endif; ?>
                                            </td>
                                            <td style="text-align: right;">
                                                <div style="display:flex; gap:8px; justify-content:flex-end;">
                                                    <button
                                                        onclick='editForm(<?php echo json_encode($form); ?>, <?php echo isset($attachments[$form['id']]) ? json_encode($attachments[$form['id']]) : '[]'; ?>)'
                                                        class="btn-delete"
                                                        style="color: var(--primary-color); background: #f0f3ff;">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <form method="POST" style="margin:0"
                                                        onsubmit="return confirm('Delete this form and all its attachments?')">
                                                        <input type="hidden" name="action" value="delete_form">
                                                        <input type="hidden" name="form_id" value="<?php echo $form['id']; ?>">
                                                        <button type="submit" class="btn-delete"><i
                                                                class="fas fa-trash-can"></i></button>
                                                    </form>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Reference Section -->
            <div class="ref-section">
                <div class="ref-section-header">
                    <div class="ref-icon"><i class="fas fa-book-open"></i></div>
                    <h3>Reference</h3>
                </div>

                <div class="ref-inner-grid">

                    <!-- Procedural Card -->
                    <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                        <div class="mgmt-header">
                            <h3 style="margin:0"><i class="fas fa-list-check" style="color:#6366f1;"></i>
                                Procedural</h3>
                        </div>

                        <form class="add-area-form" method="POST" style="align-items:flex-start;">
                            <input type="hidden" name="action" value="add_procedural">
                            <textarea name="procedural_name" class="form-input ref-textarea"
                                placeholder="Enter procedural reference (e.g. 10.4 Description...)" required
                                style="margin:0; resize:vertical; min-height:60px;"></textarea>
                            <button type="submit" class="btn-primary"
                                style="width:auto; margin:0; white-space:nowrap;">Add</button>
                        </form>

                        <div
                            style="flex: 1; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; background: #fff;">
                            <div
                                style="background: #f8fafc; padding: 12px 15px; border-bottom: 1px solid #e2e8f0; font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                                Available Procedural References
                            </div>
                            <div style="max-height: 400px; overflow-y: auto;">
                                <?php if (empty($procedurals)): ?>
                                    <p style="color:#94a3b8; padding:20px; text-align: center; margin: 0;">No references
                                        yet.</p>
                                <?php else: ?>
                                    <?php foreach ($procedurals as $proc):
                                        $lvl = getRefIndentLevel($proc['name']);
                                        $paddingLeft = $lvl > 0 ? ($lvl * 20) . 'px' : '0px';
                                        ?>
                                        <div class="area-item" style="padding-left: calc(15px + <?php echo $paddingLeft; ?>);">
                                            <div id="view-procedural-<?php echo $proc['id']; ?>"
                                                style="display: flex; width: 100%; justify-content: space-between; align-items: flex-start; gap: 10px;">
                                                <span class="area-name ref-entry"
                                                    style="white-space:pre-wrap; font-size: 0.9rem;"><?php echo htmlspecialchars($proc['name']); ?></span>
                                                <div style="display: flex; gap: 5px; flex-shrink: 0;">
                                                    <button type="button" class="btn-delete"
                                                        style="color: var(--primary-color); background: #f0f3ff;"
                                                        onclick="toggleEdit('procedural', <?php echo $proc['id']; ?>)"
                                                        title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <form method="POST" style="margin:0;"
                                                        onsubmit="return confirm('Delete this procedural reference?')">
                                                        <input type="hidden" name="action" value="delete_procedural">
                                                        <input type="hidden" name="procedural_id"
                                                            value="<?php echo $proc['id']; ?>">
                                                        <button type="submit" class="btn-delete" title="Delete"><i
                                                                class="fas fa-trash-can"></i></button>
                                                    </form>
                                                </div>
                                            </div>
                                            <div id="edit-procedural-<?php echo $proc['id']; ?>"
                                                style="display: none; width: 100%;">
                                                <form method="POST"
                                                    style="margin:0; width: 100%; display: flex; flex-direction: column; gap: 8px;">
                                                    <input type="hidden" name="action" value="edit_procedural">
                                                    <input type="hidden" name="procedural_id"
                                                        value="<?php echo $proc['id']; ?>">
                                                    <textarea name="procedural_name" class="form-input ref-textarea" required
                                                        style="font-size: 0.9rem; min-height: 80px;"><?php echo htmlspecialchars($proc['name']); ?></textarea>
                                                    <div style="display: flex; gap: 8px; justify-content: flex-end;">
                                                        <button type="button" class="btn-secondary"
                                                            style="width: auto; padding: 6px 12px; font-size: 0.8rem;"
                                                            onclick="toggleEdit('procedural', <?php echo $proc['id']; ?>)">Cancel</button>
                                                        <button type="submit" class="btn-primary"
                                                            style="width: auto; padding: 6px 12px; font-size: 0.8rem; margin: 0;">Save
                                                            Changes</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Disqualification Card -->
                    <div class="mgmt-card animated-fade-in" style="margin-bottom: 0;">
                        <div class="mgmt-header">
                            <h3 style="margin:0"><i class="fas fa-ban" style="color:#ef4444;"></i>
                                Disqualification</h3>
                        </div>

                        <form class="add-area-form" method="POST" style="align-items:flex-start;">
                            <input type="hidden" name="action" value="add_disqualification">
                            <textarea name="disqualification_name" class="form-input ref-textarea"
                                placeholder="Enter disqualification reference (e.g. 10.4.1 Description...)" required
                                style="margin:0; resize:vertical; min-height:60px;"></textarea>
                            <button type="submit" class="btn-primary"
                                style="width:auto; margin:0; white-space:nowrap;">Add</button>
                        </form>

                        <div
                            style="flex: 1; border: 1px solid #e2e8f0; border-radius: 12px; overflow: hidden; background: #fff;">
                            <div
                                style="background: #f8fafc; padding: 12px 15px; border-bottom: 1px solid #e2e8f0; font-weight: 600; color: #1e293b; font-size: 0.9rem;">
                                Available Disqualification References
                            </div>
                            <div style="max-height: 400px; overflow-y: auto;">
                                <?php if (empty($disqualifications)): ?>
                                    <p style="color:#94a3b8; padding:20px; text-align: center; margin: 0;">No references
                                        yet.</p>
                                <?php else: ?>
                                    <?php foreach ($disqualifications as $dq):
                                        $lvl = getRefIndentLevel($dq['name']);
                                        $paddingLeft = $lvl > 0 ? ($lvl * 20) . 'px' : '0px';
                                        ?>
                                        <div class="area-item" style="padding-left: calc(15px + <?php echo $paddingLeft; ?>);">
                                            <div id="view-disqualification-<?php echo $dq['id']; ?>"
                                                style="display: flex; width: 100%; justify-content: space-between; align-items: flex-start; gap: 10px;">
                                                <span class="area-name ref-entry"
                                                    style="white-space:pre-wrap; font-size: 0.9rem;"><?php echo htmlspecialchars($dq['name']); ?></span>
                                                <div style="display: flex; gap: 5px; flex-shrink: 0;">
                                                    <button type="button" class="btn-delete"
                                                        style="color: var(--primary-color); background: #f0f3ff;"
                                                        onclick="toggleEdit('disqualification', <?php echo $dq['id']; ?>)"
                                                        title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                    <form method="POST" style="margin:0;"
                                                        onsubmit="return confirm('Delete this disqualification reference?')">
                                                        <input type="hidden" name="action" value="delete_disqualification">
                                                        <input type="hidden" name="disqualification_id"
                                                            value="<?php echo $dq['id']; ?>">
                                                        <button type="submit" class="btn-delete" title="Delete"><i
                                                                class="fas fa-trash-can"></i></button>
                                                    </form>
                                                </div>
                                            </div>
                                            <div id="edit-disqualification-<?php echo $dq['id']; ?>"
                                                style="display: none; width: 100%;">
                                                <form method="POST"
                                                    style="margin:0; width: 100%; display: flex; flex-direction: column; gap: 8px;">
                                                    <input type="hidden" name="action" value="edit_disqualification">
                                                    <input type="hidden" name="disqualification_id"
                                                        value="<?php echo $dq['id']; ?>">
                                                    <textarea name="disqualification_name" class="form-input ref-textarea"
                                                        required
                                                        style="font-size: 0.9rem; min-height: 80px;"><?php echo htmlspecialchars($dq['name']); ?></textarea>
                                                    <div style="display: flex; gap: 8px; justify-content: flex-end;">
                                                        <button type="button" class="btn-secondary"
                                                            style="width: auto; padding: 6px 12px; font-size: 0.8rem;"
                                                            onclick="toggleEdit('disqualification', <?php echo $dq['id']; ?>)">Cancel</button>
                                                        <button type="submit" class="btn-primary"
                                                            style="width: auto; padding: 6px 12px; font-size: 0.8rem; margin: 0;">Save
                                                            Changes</button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </main>
    </div>

    <!-- Add/Edit Form Modal -->
    <div id="formModal">
        <div class="modal-content">
            <div
                style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; border-bottom:1px solid #f1f5f9; padding-bottom:15px;">
                <h3 id="modalTitle" style="margin:0; color:#1e293b;"><i class="fas fa-file-invoice"
                        style="color:#10b981; margin-right:10px;"></i> Add New Form</h3>
                <button onclick="closeFormModal()"
                    style="background:none; border:none; font-size:1.5rem; cursor:pointer; color:#94a3b8;"><i
                        class="fas fa-times"></i></button>
            </div>
            <form id="formActionForm" method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" id="formAction" value="add_form">
                <input type="hidden" name="form_id" id="modalFormId">

                <div style="margin-bottom:20px;">
                    <label
                        style="display:block; margin-bottom:8px; font-weight:600; color:#475569; font-size:0.9rem;">Form
                        Title</label>
                    <input type="text" name="title" id="modalFormTitle" class="form-input"
                        placeholder="Enter form title" required style="width:100%; box-sizing:border-box;">
                </div>

                <div style="margin-bottom:20px;">
                    <label
                        style="display:block; margin-bottom:8px; font-weight:600; color:#475569; font-size:0.9rem;">Notes
                        / Instructions</label>
                    <textarea name="notes" id="modalFormNotes" class="form-input"
                        placeholder="Enter additional notes or instructions"
                        style="width:100%; min-height:100px; box-sizing:border-box; resize:vertical;"></textarea>
                </div>

                <div style="margin-bottom:20px;">
                    <label
                        style="display:block; margin-bottom:8px; font-weight:600; color:#475569; font-size:0.9rem;">PDF
                        Files</label>
                    <input type="file" name="pdf_files[]" id="pdfInput" class="form-input" accept=".pdf" multiple
                        style="width:100%; box-sizing:border-box; padding:8px;">
                    <p style="font-size:0.75rem; color:#94a3b8; margin-top:5px;">You can select multiple PDF files.</p>
                    <div id="pdfPreviewContainer"
                        style="display:flex; flex-direction:column; gap:8px; margin-top:10px;"></div>
                </div>

                <div style="margin-bottom:20px;">
                    <label
                        style="display:block; margin-bottom:8px; font-weight:600; color:#475569; font-size:0.9rem;">Images</label>
                    <input type="file" name="image_files[]" id="imageInput" class="form-input" accept="image/*" multiple
                        style="width:100%; box-sizing:border-box; padding:8px;">
                    <p style="font-size:0.75rem; color:#94a3b8; margin-top:5px;">You can select multiple images.</p>
                    <div id="imagePreviewContainer"
                        style="display:grid; grid-template-columns:repeat(auto-fill, minmax(80px, 1fr)); gap:10px; margin-top:10px;">
                    </div>
                </div>

                <div id="existingAttachments" style="display:none; margin-bottom:20px;">
                    <label
                        style="display:block; margin-bottom:12px; font-weight:600; color:#475569; font-size:0.9rem;">Existing
                        Attachments (Click to remove)</label>
                    <div id="existingPdfs" style="display:flex; flex-direction:column; gap:8px; margin-bottom:15px;">
                    </div>
                    <div id="existingImages"
                        style="display:grid; grid-template-columns:repeat(auto-fill, minmax(80px, 1fr)); gap:10px;">
                    </div>
                </div>

                <div
                    style="display:flex; gap:10px; justify-content:flex-end; margin-top:30px; border-top:1px solid #f1f5f9; padding-top:20px;">
                    <button type="button" onclick="closeFormModal()" class="btn-secondary"
                        style="width:auto;">Cancel</button>
                    <button type="submit" id="modalSubmitBtn" class="btn-primary" style="width:auto; margin:0;">Save
                        Form</button>
                </div>
            </form>
        </div>
    </div>

    <script src="../assets/js/loader.js"></script>
    <script>
        const profileToggle = document.getElementById('profileToggle');
        const profileDropdown = document.getElementById('profileDropdown');
        if (profileToggle) {
            profileToggle.addEventListener('click', (e) => {
                e.stopPropagation();
                profileDropdown.classList.toggle('active');
            });
        }
        document.addEventListener('click', () => profileDropdown?.classList.remove('active'));

        // Area list: click "1" row to open dropdown with 1, 2, 3, ... all areas
        const areaToggle = document.getElementById('areaListToggle');
        const areaDropdown = document.getElementById('areaListDropdown');
        if (areaToggle && areaDropdown) {
            areaToggle.addEventListener('click', function () {
                this.classList.toggle('expanded');
                areaDropdown.classList.toggle('open');
            });
            areaToggle.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); }
            });
        }

        // Discipline list: same
        const discToggle = document.getElementById('disciplineListToggle');
        const discDropdown = document.getElementById('disciplineListDropdown');
        if (discToggle && discDropdown) {
            discToggle.addEventListener('click', function () {
                this.classList.toggle('expanded');
                discDropdown.classList.toggle('open');
            });
            discToggle.addEventListener('keydown', function (e) {
                if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); this.click(); }
            });
        }

        // Toggle Edit Mode for References
        function toggleEdit(type, id) {
            const viewBox = document.getElementById(`view-${type}-${id}`);
            const editBox = document.getElementById(`edit-${type}-${id}`);
            if (viewBox.style.display === 'none') {
                viewBox.style.display = 'flex';
                editBox.style.display = 'none';
            } else {
                viewBox.style.display = 'none';
                editBox.style.display = 'block';
            }
        }

        function showAddForm() {
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-file-invoice" style="color:#10b981; margin-right:10px;"></i> Add New Form';
            document.getElementById('formAction').value = 'add_form';
            document.getElementById('modalFormId').value = '';
            document.getElementById('modalFormTitle').value = '';
            document.getElementById('modalFormNotes').value = '';
            document.getElementById('existingAttachments').style.display = 'none';
            document.getElementById('formModal').style.display = 'flex';
        }

        function editForm(form, formAttachments) {
            document.getElementById('modalTitle').innerHTML = '<i class="fas fa-edit" style="color:#3b82f6; margin-right:10px;"></i> Edit Form';
            document.getElementById('formAction').value = 'edit_form';
            document.getElementById('modalFormId').value = form.id;
            document.getElementById('modalFormTitle').value = form.title;
            document.getElementById('modalFormNotes').value = form.notes;

            const pdfContainer = document.getElementById('existingPdfs');
            const imgContainer = document.getElementById('existingImages');
            pdfContainer.innerHTML = '';
            imgContainer.innerHTML = '';

            if (formAttachments && formAttachments.length > 0) {
                document.getElementById('existingAttachments').style.display = 'block';
                formAttachments.forEach(att => {
                    if (att.file_type === 'pdf') {
                        const div = document.createElement('div');
                        div.style.cssText = 'display:flex; align-items:center; justify-content:space-between; padding:8px 12px; background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; font-size:0.85rem;';
                        div.innerHTML = `
                            <div style="display:flex; align-items:center; gap:8px; overflow:hidden;">
                                <i class="fas fa-file-pdf" style="color:#ef4444;"></i>
                                <span style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis; max-width:200px;">${att.original_name}</span>
                            </div>
                            <div style="display:flex; align-items:center; gap:12px;">
                                <a href="../${att.file_path}" target="_blank" style="color:var(--primary-color); text-decoration:none; font-weight:600; font-size:0.75rem;"><i class="fas fa-eye"></i> View</a>
                                <button type="button" onclick="deleteAttachment(${att.id}, this)" style="background:none; border:none; color:#ef4444; cursor:pointer; padding:0;"><i class="fas fa-times-circle"></i></button>
                            </div>
                        `;
                        pdfContainer.appendChild(div);
                    } else {
                        const div = document.createElement('div');
                        div.style.cssText = 'position:relative; aspect-ratio:1; border-radius:8px; overflow:hidden; border:1px solid #e2e8f0; background:#f8fafc;';
                        div.innerHTML = `
                            <img src="../${att.file_path}" style="width:100%; height:100%; object-fit:cover;">
                            <button type="button" onclick="deleteAttachment(${att.id}, this)" style="position:absolute; top:2px; right:2px; background:white; border-radius:50%; color:#ef4444; border:none; width:18px; height:18px; display:flex; align-items:center; justify-content:center; cursor:pointer; font-size:12px; box-shadow:0 2px 4px rgba(0,0,0,0.1);"><i class="fas fa-times-circle"></i></button>
                            <div style="position:absolute; bottom:0; left:0; right:0; background:rgba(0,0,0,0.5); color:white; font-size:9px; padding:2px 4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                                ${att.original_name}
                            </div>
                        `;
                        imgContainer.appendChild(div);
                    }
                });
            } else {
                document.getElementById('existingAttachments').style.display = 'none';
            }

            document.getElementById('formModal').style.display = 'flex';
        }

        function closeFormModal() {
            document.getElementById('formModal').style.display = 'none';
        }

        function deleteAttachment(id, btn) {
            if (confirm('Are you sure you want to remove this attachment?')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.innerHTML = `
                    <input type="hidden" name="action" value="delete_attachment">
                    <input type="hidden" name="attachment_id" value="${id}">
                `;
                document.body.appendChild(form);
                form.submit();
            }
        }

        // Preview Logic
        const pdfInput = document.getElementById('pdfInput');
        const pdfPreview = document.getElementById('pdfPreviewContainer');
        const imageInput = document.getElementById('imageInput');
        const imagePreview = document.getElementById('imagePreviewContainer');

        pdfInput.addEventListener('change', function () {
            pdfPreview.innerHTML = '';
            if (this.files) {
                Array.from(this.files).forEach(file => {
                    const url = URL.createObjectURL(file);
                    const div = document.createElement('div');
                    div.style.cssText = 'display:flex; align-items:center; justify-content:space-between; padding:8px 12px; background:#f0f9ff; border:1px solid #bae6fd; border-radius:8px; font-size:0.85rem;';
                    div.innerHTML = `
                        <div style="display:flex; align-items:center; gap:8px; overflow:hidden;">
                            <i class="fas fa-file-pdf" style="color:#ef4444;"></i>
                            <span style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">${file.name}</span>
                        </div>
                        <a href="${url}" target="_blank" style="color:var(--primary-color); text-decoration:none; font-weight:600; font-size:0.75rem;"><i class="fas fa-eye"></i> View</a>
                    `;
                    pdfPreview.appendChild(div);
                });
            }
        });

        imageInput.addEventListener('change', function () {
            imagePreview.innerHTML = '';
            if (this.files) {
                Array.from(this.files).forEach(file => {
                    const url = URL.createObjectURL(file);
                    const div = document.createElement('div');
                    div.style.cssText = 'position:relative; aspect-ratio:1; border-radius:8px; overflow:hidden; border:1px solid #e2e8f0;';
                    div.innerHTML = `
                        <img src="${url}" style="width:100%; height:100%; object-fit:cover;">
                        <div style="position:absolute; bottom:0; left:0; right:0; background:rgba(0,0,0,0.5); color:white; font-size:10px; padding:2px 4px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
                            ${file.name}
                        </div>
                    `;
                    imagePreview.appendChild(div);
                });
            }
        });

        // Also clear previews when closing/opening
        const originalCloseFormModal = closeFormModal;
        closeFormModal = function () {
            pdfPreview.innerHTML = '';
            imagePreview.innerHTML = '';
            document.getElementById('existingPdfs').innerHTML = '';
            document.getElementById('existingImages').innerHTML = '';
            pdfInput.value = '';
            imageInput.value = '';
            originalCloseFormModal();
        };

        const originalShowAddForm = showAddForm;
        showAddForm = function () {
            pdfPreview.innerHTML = '';
            imagePreview.innerHTML = '';
            document.getElementById('existingPdfs').innerHTML = '';
            document.getElementById('existingImages').innerHTML = '';
            pdfInput.value = '';
            imageInput.value = '';
            originalShowAddForm();
        };

        const originalEditForm = editForm;
        editForm = function (form, formAttachments) {
            pdfPreview.innerHTML = '';
            imagePreview.innerHTML = '';
            document.getElementById('existingPdfs').innerHTML = '';
            document.getElementById('existingImages').innerHTML = '';
            pdfInput.value = '';
            imageInput.value = '';
            originalEditForm(form, formAttachments);
        };
    </script>
    <script src="../assets/js/dashboard-transitions.js"></script>
</body>

</html>