<?php
require_once 'auth.php';
include 'db.php';
requireLogin($conn);

$role = $_SESSION['role'] ?? 'user';
$draft_id = (int) ($_GET['id'] ?? 0);

$letter_type_pages = [
    'memo_kelulusan' => [
        'label' => 'Memo Kelulusan',
        'file' => 'Memo_Kelulusan.php',
        'icon' => 'fa-file-signature',
        'description' => 'Memo untuk kelulusan dan edaran tandatangan.',
    ],
    'memo' => [
        'label' => 'Memo',
        'file' => 'Memo.php',
        'icon' => 'fa-file-alt',
        'description' => 'Memo biasa untuk kegunaan rasmi dalaman.',
    ],
    'surat_rasmi' => [
        'label' => 'Surat Rasmi',
        'file' => 'Surat_Rasmi.php',
        'icon' => 'fa-envelope-open-text',
        'description' => 'Surat rasmi kepada penerima berkaitan.',
    ],
];

function normalizeLetterTypeKey($value) {
    $value = strtolower(trim((string) $value));
    $value = str_replace([' ', '-'], '_', $value);
    if ($value === 'memo_kelulusan') {
        return 'memo_kelulusan';
    }
    if ($value === 'memo') {
        return 'memo';
    }
    if ($value === 'surat_rasmi') {
        return 'surat_rasmi';
    }
    return '';
}

function getLetterTypeKeyFromDocType($doc_type) {
    $normalized = strtolower(trim((string) $doc_type));
    if ($normalized === 'memo') {
        return 'memo';
    }
    if ($normalized === 'surat rasmi') {
        return 'surat_rasmi';
    }
    return 'memo_kelulusan';
}

function buildLetterTypeUrl($file, $extra = []) {
    $query = $_GET;
    unset($query['type']);
    foreach ($extra as $key => $value) {
        if ($value === null) {
            unset($query[$key]);
        } else {
            $query[$key] = $value;
        }
    }
    return $file . (!empty($query) ? '?' . http_build_query($query) : '');
}

if ($draft_id > 0) {
    if (!currentUserCan($conn, 'draft_letter', 'update')) {
        echo "<script>alert('Anda tidak mempunyai kebenaran untuk mengubah surat ini.'); window.location='draft_letters.php';</script>";
        exit();
    }

    $stmt = mysqli_prepare($conn, "SELECT doc_type FROM letter_drafts WHERE id = ? AND deleted_at IS NULL LIMIT 1");
    if ($stmt) {
        mysqli_stmt_bind_param($stmt, "i", $draft_id);
        mysqli_stmt_execute($stmt);
        $draft = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
        if ($draft) {
            $type_key = getLetterTypeKeyFromDocType($draft['doc_type'] ?? '');
            header('Location: ' . buildLetterTypeUrl($letter_type_pages[$type_key]['file'], ['id' => $draft_id]));
            exit();
        }
    }

    header('Location: draft_letters.php?error=not_found');
    exit();
}

if (!currentUserCan($conn, 'draft_letter', 'create')) {
    echo "<script>alert('Anda tidak mempunyai kebenaran untuk menyediakan surat.'); window.location='draft_letters.php';</script>";
    exit();
}

$selected_type = normalizeLetterTypeKey($_GET['type'] ?? '');
if ($selected_type !== '' && isset($letter_type_pages[$selected_type])) {
    header('Location: ' . buildLetterTypeUrl($letter_type_pages[$selected_type]['file'], ['type' => null]));
    exit();
}

$status_messages = [
    'validation' => ['type' => 'error', 'text' => 'Maklumat surat tidak lengkap. Sila semak semula borang surat.'],
    'folder' => ['type' => 'error', 'text' => 'Fail yang dipilih tidak sah atau tidak ditemui.'],
    'folder_closed' => ['type' => 'error', 'text' => 'Fail ini telah ditutup dan tidak boleh digunakan untuk surat baharu.'],
    'system' => ['type' => 'error', 'text' => 'Ralat sistem berlaku. Sila cuba semula.'],
];
$message = null;
if (isset($_GET['error'], $status_messages[$_GET['error']])) {
    $message = $status_messages[$_GET['error']];
    if (!empty($_GET['msg'])) {
        $message['text'] .= ' ' . htmlspecialchars((string) $_GET['msg']);
    }
}
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pilih Jenis Surat | Sistem Pengurusan Fail</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <?php renderAppShellAssets(); ?>
    <style>
        :root {
            --primary: #0077b6; --primary-dark: #005f99; --secondary: #00b4d8;
            --deep-blue: #023e5f;
            --superadmin: #6c5ce7; --superadmin-dark: #5b4cdb;
            --bg-light: rgba(245, 250, 253, 0.72); --bg-card: rgba(255,255,255,0.68); --text-main: #163447;
            --text-muted: #2d5367; --border: rgba(255,255,255,0.48); --sidebar-width: 280px;
            --glass: rgba(255,255,255,0.58); --glass-strong: rgba(255,255,255,0.76);
            --shadow-soft: 0 24px 70px rgba(2,62,95,0.16);
            --success: #1a9955; --danger: #dc3545; --warning: #ffc107;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', 'Inter', Tahoma, Geneva, Verdana, sans-serif; }
        body {
            background:
                linear-gradient(135deg, rgba(245,250,253,0.90), rgba(222,246,252,0.76)),
                url('assets/auth-bg.png') center/cover no-repeat fixed;
            min-height: 100vh;
            display: flex;
            color: var(--text-main);
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: fixed;
            inset: 0;
            background:
                radial-gradient(circle at 18% 18%, rgba(0,180,216,0.22), transparent 28%),
                radial-gradient(circle at 86% 12%, rgba(0,119,182,0.18), transparent 28%),
                linear-gradient(120deg, rgba(255,255,255,0.28), rgba(255,255,255,0.08));
            pointer-events: none;
            z-index: 0;
        }
        body::after {
            content: '';
            position: fixed;
            width: 520px;
            height: 520px;
            right: -180px;
            bottom: -220px;
            background: rgba(0,180,216,0.18);
            filter: blur(8px);
            transform: rotate(18deg);
            border-radius: 42px;
            pointer-events: none;
            z-index: 0;
        }
        .sidebar { width: var(--sidebar-width); background: linear-gradient(180deg, rgba(2,62,95,0.94), rgba(0,119,182,0.84)); border-right: 1px solid rgba(255,255,255,0.22); position: fixed; height: 100vh; padding: 20px 0; overflow-y: auto; overflow-x: hidden; z-index: 1000; box-shadow: 18px 0 44px rgba(2,38,60,0.20); transition: width 0.3s ease; display: flex; flex-direction: column; backdrop-filter: blur(18px) saturate(1.25); }
        .sidebar.collapsed { width: 70px; }
        .sidebar-header { text-align: center; padding: 0 20px 20px; border-bottom: 1px solid rgba(255,255,255,0.16); margin-bottom: 20px; white-space: nowrap; overflow: hidden; background: transparent !important; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text { display: none; }
        .sidebar-header img { width: 58px; margin-bottom: 10px; transition: margin 0.3s ease; filter: drop-shadow(0 8px 14px rgba(0,0,0,0.22)); }
        .sidebar.collapsed .sidebar-header img { margin: 0 auto 10px; }
        .sidebar-header h3 { font-size: 1rem; font-weight: 800; color: #fff; margin-bottom: 4px; letter-spacing: 0; }
        .sidebar-header p { font-size: 0.75rem; color: rgba(255,255,255,0.72); }
        .role-badge { display: inline-block; padding: 3px 10px; border-radius: 12px; font-size: 0.7rem; font-weight: 600; margin-left: 8px; }
        .role-badge.user { background: #e6f4ff; color: var(--primary); }
        .role-badge.admin { background: #d4edda; color: var(--success); }
        .role-badge.superadmin { background: linear-gradient(90deg, var(--superadmin), var(--superadmin-dark)); color: #fff; }
        .sidebar-menu { list-style: none; padding: 0 10px; display: flex; flex-direction: column; flex: 1; }
        .sidebar-section { padding: 10px 18px 6px; color: rgba(255,255,255,0.56); font-size: 0.72rem; font-weight: 700; text-transform: uppercase; letter-spacing: 0.06em; }
        .sidebar-spacer { margin-top: auto; }
        .sidebar-menu li a { display: flex; align-items: center; gap: 12px; padding: 12px 18px; color: rgba(255,255,255,0.88); text-decoration: none; border-radius: 8px; margin-bottom: 4px; transition: all 0.2s ease; font-size: 0.9rem; white-space: nowrap; }
        .sidebar-menu li a:hover, .sidebar-menu li a.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu li a i { width: 20px; text-align: center; font-size: 1.1rem; }
        .sidebar-menu hr { border: 0; border-top: 1px solid rgba(255,255,255,0.16); margin: 8px 0; }
        .sidebar-menu .dropdown { position: relative; }
        .sidebar-menu .dropdown-toggle { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 12px 18px; color: rgba(255,255,255,0.88); background: none; border: none; border-radius: 8px; cursor: pointer; font-size: 0.9rem; text-align: left; transition: all 0.2s ease; }
        .sidebar-menu .dropdown-toggle:hover, .sidebar-menu .dropdown-toggle.active { background: rgba(255,255,255,0.18); color: #fff; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.18); }
        .sidebar-menu .dropdown-toggle i.chevron { transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); font-size: 0.8rem; }
        .sidebar-menu .dropdown.active .dropdown-toggle i.chevron { transform: rotate(180deg); }
        .sidebar-menu .dropdown-menu { display: flex; flex-direction: column; padding-left: 42px; margin-top: 4px; max-height: 0; opacity: 0; overflow: hidden; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.25s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu { max-height: 260px; opacity: 1; }
        .sidebar-menu .dropdown-menu a { padding: 8px 18px; color: rgba(255,255,255,0.78); text-decoration: none; border-radius: 6px; font-size: 0.85rem; display: flex; align-items: center; gap: 8px; opacity: 0; transform: translateY(-5px); transition: opacity 0.2s ease, transform 0.2s ease; }
        .sidebar-menu .dropdown.active .dropdown-menu a { opacity: 1; transform: translateY(0); }
        .sidebar-menu .dropdown-menu a:hover, .sidebar-menu .dropdown-menu a.active { background: rgba(255,255,255,0.16); color: #fff; }
        .sidebar-toggle { position: absolute; right: 10px; top: 28px; width: 28px; height: 28px; background: rgba(255,255,255,0.18); color: #fff; border: 1px solid rgba(255,255,255,0.22); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 0.7rem; box-shadow: 0 8px 20px rgba(0,0,0,0.15); transition: transform 0.3s ease; z-index: 1001; }
        .sidebar.collapsed .sidebar-toggle { transform: rotate(180deg); }
        .sidebar.collapsed + .main { margin-left: 70px; }
        .sidebar.collapsed .sidebar-header { padding: 0 10px 20px; }
        .sidebar.collapsed .sidebar-header h3, .sidebar.collapsed .sidebar-header p, .sidebar.collapsed .menu-text, .sidebar.collapsed .role-badge, .sidebar.collapsed .dropdown-menu, .sidebar.collapsed .sidebar-section { display: none !important; }
        .sidebar.collapsed .sidebar-menu li a, .sidebar.collapsed .sidebar-menu .dropdown-toggle { justify-content: center; padding: 12px; gap: 0; }
        .main { margin-left: var(--sidebar-width); flex: 1; padding: 28px 32px; transition: margin-left 0.3s ease; position: relative; z-index: 1; }
        .top-bar { background: var(--glass); padding: 16px 24px; border-radius: 18px; box-shadow: var(--shadow-soft); margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; border: 1px solid var(--border); backdrop-filter: blur(22px) saturate(1.28); }
        .top-bar h2 { color: var(--deep-blue); font-size: 1.3rem; font-weight: 800; display: flex; align-items: center; gap: 8px; }
        .user-info { display: flex; align-items: center; gap: 15px; font-size: 0.9rem; color: var(--text-muted); }
        .user-info span { color: var(--primary); font-weight: 600; }
        .user-info a { color: var(--danger); text-decoration: none; font-weight: 500; display: flex; align-items: center; gap: 5px; }
        .user-info a:hover { text-decoration: underline; }
        .card { background: var(--glass); border-radius: 22px; box-shadow: var(--shadow-soft); padding: 24px; margin-bottom: 25px; border: 1px solid var(--border); backdrop-filter: blur(24px) saturate(1.35); }
        .card-header { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; margin-bottom: 18px; padding-bottom: 14px; border-bottom: 1px solid var(--border); }
        .card-title { color: var(--deep-blue); font-size: 1.18rem; font-weight: 800; display: flex; align-items: center; gap: 8px; margin-bottom: 5px; }
        .card-subtitle { color: var(--text-muted); font-size: 0.9rem; line-height: 1.5; max-width: 720px; }
        .type-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }
        .type-card { border: 1px solid rgba(255,255,255,0.56); background: rgba(255,255,255,0.62); border-radius: 18px; padding: 20px; text-decoration: none; color: var(--text-main); display: flex; flex-direction: column; gap: 12px; transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease; min-height: 178px; backdrop-filter: blur(18px) saturate(1.2); }
        .type-card:hover { transform: translateY(-3px); border-color: rgba(0,180,216,0.72); box-shadow: 0 18px 34px rgba(0,119,182,0.16); background: rgba(255,255,255,0.78); }
        .type-icon { width: 48px; height: 48px; border-radius: 14px; display: inline-flex; align-items: center; justify-content: center; color: #fff; background: linear-gradient(135deg, var(--primary), var(--secondary)); font-size: 1.25rem; box-shadow: 0 14px 28px rgba(0,119,182,0.20); }
        .type-card h3 { color: var(--deep-blue); font-size: 1.1rem; font-weight: 800; }
        .type-card p { color: var(--text-muted); line-height: 1.45; font-size: 0.9rem; }
        .type-action { margin-top: auto; color: var(--primary); font-weight: 700; display: inline-flex; align-items: center; gap: 8px; }
        .btn { padding: 9px 20px; border: none; border-radius: 8px; text-decoration: none; font-size: 0.9rem; cursor: pointer; display: inline-flex; align-items: center; gap: 6px; font-weight: 600; transition: opacity 0.2s, transform 0.2s; white-space: nowrap; }
        .btn:hover { opacity: 0.92; transform: translateY(-1px); }
        .btn-light { background: var(--glass-strong); color: var(--primary); border: 1px solid var(--border); }
        .alert { padding: 12px 14px; border-radius: 12px; margin-bottom: 18px; border: 1px solid rgba(220,53,69,0.20); background: rgba(255,245,245,0.82); color: var(--danger); }
        .page-footer { text-align: center; padding: 20px; color: var(--text-muted); font-size: 0.8rem; margin-top: 30px; }
        @media (max-width: 992px) {
            .sidebar { width: 70px; }
            .sidebar .sidebar-header h3, .sidebar .sidebar-header p, .sidebar .menu-text, .sidebar .role-badge, .sidebar .dropdown-menu, .sidebar .sidebar-section { display: none; }
            .main { margin-left: 70px; }
            .sidebar-toggle { display: none; }
            .card-header { flex-direction: column; align-items: stretch; }
        }
        .sidebar {
            overflow: hidden;
        }
        .sidebar-header {
            flex: 0 0 auto;
        }
        .sidebar-menu {
            flex: 1 1 auto;
            min-height: 0;
            overflow-y: auto;
            overflow-x: hidden;
            padding-bottom: 0;
            overscroll-behavior: contain;
            scrollbar-width: thin;
            scrollbar-color: #8f8f8f transparent;
        }
        .sidebar-menu::-webkit-scrollbar {
            width: 10px;
        }
        .sidebar-menu::-webkit-scrollbar-track {
            background: transparent;
        }
        .sidebar-menu::-webkit-scrollbar-thumb {
            background: #8f8f8f;
            border-radius: 999px;
            border: 2px solid transparent;
            background-clip: content-box;
        }
        .sidebar-menu::-webkit-scrollbar-button {
            display: none;
            width: 0;
            height: 0;
        }
    
        /* Button hover animation */
        .main .btn,
        .main .tab-btn,
        .main .action-btn,
        .main .btn-action,
        .main .filter-btn,
        .main .button,
        .main .generate-closing-btn,
        .main .attachment-remove-btn,
        .main .page-add-btn,
        .main .page-delete-btn,
        .main .delete-current-page-btn,
        .main .form-actions a,
        .main .form-actions button,
        .main .filter-actions a,
        .main .filter-actions button,
        .main .document-command a,
        .main .document-command button,
        .main table a[class*="btn"],
        .main table button[class*="btn"],
        .main input[type="submit"],
        .main input[type="button"] {
            transition: transform 0.2s ease, filter 0.2s ease, box-shadow 0.2s ease, background-color 0.2s ease, border-color 0.2s ease !important;
            will-change: transform;
        }

        .main .btn:hover:not(:disabled),
        .main .tab-btn:hover:not(:disabled),
        .main .action-btn:hover:not(:disabled),
        .main .btn-action:hover:not(:disabled),
        .main .filter-btn:hover:not(:disabled),
        .main .button:hover:not(:disabled),
        .main .generate-closing-btn:hover:not(:disabled),
        .main .attachment-remove-btn:hover:not(:disabled),
        .main .page-add-btn:hover:not(:disabled),
        .main .page-delete-btn:hover:not(:disabled),
        .main .delete-current-page-btn:hover:not(:disabled),
        .main .form-actions a:hover,
        .main .form-actions button:hover:not(:disabled),
        .main .filter-actions a:hover,
        .main .filter-actions button:hover:not(:disabled),
        .main .document-command a:hover,
        .main .document-command button:hover:not(:disabled),
        .main table a[class*="btn"]:hover,
        .main table button[class*="btn"]:hover:not(:disabled),
        .main input[type="submit"]:hover:not(:disabled),
        .main input[type="button"]:hover:not(:disabled) {
            transform: translateY(-1px);
            filter: brightness(1.04);
            box-shadow: 0 14px 28px rgba(0, 119, 182, 0.18);
        }

        .main .btn:active:not(:disabled),
        .main .tab-btn:active:not(:disabled),
        .main .action-btn:active:not(:disabled),
        .main .btn-action:active:not(:disabled),
        .main .filter-btn:active:not(:disabled),
        .main .button:active:not(:disabled),
        .main .generate-closing-btn:active:not(:disabled),
        .main .attachment-remove-btn:active:not(:disabled),
        .main .page-add-btn:active:not(:disabled),
        .main .page-delete-btn:active:not(:disabled),
        .main .delete-current-page-btn:active:not(:disabled),
        .main .form-actions a:active,
        .main .form-actions button:active:not(:disabled),
        .main .filter-actions a:active,
        .main .filter-actions button:active:not(:disabled),
        .main .document-command a:active,
        .main .document-command button:active:not(:disabled),
        .main table a[class*="btn"]:active,
        .main table button[class*="btn"]:active:not(:disabled),
        .main input[type="submit"]:active:not(:disabled),
        .main input[type="button"]:active:not(:disabled) {
            transform: translateY(0);
            filter: brightness(0.98);
        }</style>
</head>
<body class="role-<?= htmlspecialchars($role) ?>">
    <aside class="sidebar" id="sidebar">
        <button class="sidebar-toggle" id="sidebarToggle" title="Tutup/Buka Menu">
            <i class="fas fa-chevron-left"></i>
        </button>
        <div class="sidebar-header">
            <img src="mainpp.png" alt="Logo MAINPP">
            <h3>SISTEM PENGURUSAN FAIL</h3>
            <p>Jabatan Teknologi Maklumat</p>
        </div>
        <ul class="sidebar-menu">
            <?php renderUnifiedSidebarMenu($conn, $role, 'draft_letter_form.php'); ?>
        </ul>
    </aside>

    <main class="main">
        <div class="top-bar">
            <h2><i class="fas fa-file-signature"></i> Sediakan Surat</h2>
            <?php renderTopBarUserMenu($conn, $role, 'draft_letter_form.php'); ?>
        </div>

        <?php
        renderBreadcrumb([
            ['label' => 'Dashboard', 'url' => 'dashboard.php'],
            ['label' => 'Modul Surat', 'url' => 'draft_letters.php'],
            ['label' => 'Sediakan Surat', 'url' => 'draft_letter_form.php', 'current' => true]
        ]);
        ?>

        <div class="card">
            <div class="card-header">
                <div>
                    <div class="card-title"><i class="fas fa-file-circle-plus"></i> Pilih Jenis Surat</div>
                    <p class="card-subtitle">Sila pilih format surat yang ingin disediakan.</p>
                </div>
            </div>

            <?php if ($message): ?>
                <div class="alert"><i class="fas fa-triangle-exclamation"></i> <?= $message['text'] ?></div>
            <?php endif; ?>

            <div class="type-grid">
                <?php foreach ($letter_type_pages as $type_key => $type_config): ?>
                    <a class="type-card" href="<?= htmlspecialchars(buildLetterTypeUrl($type_config['file'], ['type' => null])) ?>">
                        <span class="type-icon"><i class="fas <?= htmlspecialchars($type_config['icon']) ?>"></i></span>
                        <h3><?= htmlspecialchars($type_config['label']) ?></h3>
                        <p><?= htmlspecialchars($type_config['description']) ?></p>
                        <span class="type-action">Pilih <i class="fas fa-arrow-right"></i></span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="page-footer">
            Hakcipta Terpelihara &copy; <?= date('Y') ?> Majlis Agama Islam Negeri Pulau Pinang.
        </div>
    </main>

    <script>
        const sidebar = document.getElementById('sidebar');
        const toggleBtn = document.getElementById('sidebarToggle');
        if (toggleBtn) {
            toggleBtn.addEventListener('click', () => sidebar.classList.toggle('collapsed'));
        }
        if (window.innerWidth < 992 && sidebar) sidebar.classList.add('collapsed');
        document.querySelectorAll('.sidebar-menu .dropdown-toggle, .dropdown-toggle').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                const dropdown = this.parentElement;
                const isActive = dropdown.classList.contains('active');
                document.querySelectorAll('.sidebar-menu .dropdown, .dropdown').forEach(item => {
                    if (item !== dropdown) item.classList.remove('active');
                });
                dropdown.classList.toggle('active', !isActive);
            });
        });
        function confirmLogout() {
            return confirm("Adakah anda pasti ingin log keluar?");
        }
    </script>
    <?php renderSessionTimeoutScript(); ?>
</body>
</html>
