<?php
require_once '../auth.php';

restore_login_from_cookie();

if (!isset($_SESSION['user_id']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: ../index.php");
    exit();
}


if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
    }
}

if (!function_exists('initial_letter')) {
    function initial_letter($value) {
        $value = trim((string) $value);
        if ($value === '') return 'A';
        return function_exists('mb_substr') ? mb_substr($value, 0, 1, 'UTF-8') : substr($value, 0, 1);
    }
}

$message = [
    'type' => '',
    'text' => ''
];

function set_message(&$message, $type, $text) {
    $message['type'] = $type;
    $message['text'] = $text;
}

if (isset($_POST['add_user'])) {
    $name = trim($_POST['full_name'] ?? '');
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $role = 'officer';

    if ($name === '' || $username === '' || $password === '') {
        set_message($message, 'error', 'সব তথ্য পূরণ করুন।');
    } else {
        $stmt = $conn->prepare("SELECT id FROM agh_users WHERE username = ? LIMIT 1");
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $exists = $stmt->get_result();
        $stmt->close();

        if ($exists && $exists->num_rows > 0) {
            set_message($message, 'error', 'এই ইউজারনেমটি আগেই ব্যবহার করা হয়েছে।');
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $conn->prepare("
                INSERT INTO agh_users (full_name, username, password, role)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->bind_param("ssss", $name, $username, $hash, $role);

            if ($stmt->execute()) {
                set_message($message, 'success', 'নতুন অফিসার সফলভাবে যোগ হয়েছে।');
            } else {
                set_message($message, 'error', 'অফিসার যোগ করা যায়নি।');
            }

            $stmt->close();
        }
    }
}

if (isset($_POST['update_profile'])) {
    $user_id = (int) ($_POST['user_id'] ?? 0);
    $name = trim($_POST['full_name'] ?? '');
    $username = trim($_POST['username'] ?? '');

    if ($user_id <= 0 || $name === '' || $username === '') {
        set_message($message, 'error', 'আপডেট করার জন্য সঠিক তথ্য দিন।');
    } else {
        $stmt = $conn->prepare("SELECT id FROM agh_users WHERE username = ? AND id != ? LIMIT 1");
        $stmt->bind_param("si", $username, $user_id);
        $stmt->execute();
        $exists = $stmt->get_result();
        $stmt->close();

        if ($exists && $exists->num_rows > 0) {
            set_message($message, 'error', 'এই ইউজারনেমটি অন্য একজন ব্যবহার করছেন।');
        } else {
            $stmt = $conn->prepare("
                UPDATE agh_users
                SET full_name = ?, username = ?
                WHERE id = ? AND role = 'officer'
            ");
            $stmt->bind_param("ssi", $name, $username, $user_id);

            if ($stmt->execute()) {
                set_message($message, 'success', 'অফিসারের তথ্য সফলভাবে আপডেট হয়েছে।');
            } else {
                set_message($message, 'error', 'তথ্য আপডেট করা যায়নি।');
            }

            $stmt->close();
        }
    }
}

if (isset($_POST['update_pass'])) {
    $user_id = (int) ($_POST['user_id'] ?? 0);
    $new_password = $_POST['new_password'] ?? '';

    if ($user_id <= 0 || strlen($new_password) < 4) {
        set_message($message, 'error', 'পাসওয়ার্ড কমপক্ষে ৪ অক্ষরের দিন।');
    } else {
        $hash = password_hash($new_password, PASSWORD_DEFAULT);

        $stmt = $conn->prepare("
            UPDATE agh_users
            SET password = ?
            WHERE id = ? AND role = 'officer'
        ");
        $stmt->bind_param("si", $hash, $user_id);

        if ($stmt->execute()) {
            set_message($message, 'success', 'পাসওয়ার্ড সফলভাবে পরিবর্তন হয়েছে।');
        } else {
            set_message($message, 'error', 'পাসওয়ার্ড পরিবর্তন করা যায়নি।');
        }

        $stmt->close();
    }
}

if (isset($_POST['delete_user'])) {
    $delete_id = (int) ($_POST['user_id'] ?? 0);
    $current_id = (int) $_SESSION['user_id'];

    if ($delete_id > 0 && $delete_id !== $current_id) {
        $stmt = $conn->prepare("DELETE FROM agh_users WHERE id = ? AND role = 'officer'");
        $stmt->bind_param("i", $delete_id);
        $stmt->execute();
        $stmt->close();

        header("Location: users.php");
        exit();
    }
}

$users = [];
$result = $conn->query("SELECT id, full_name, username FROM agh_users WHERE role = 'officer' ORDER BY id DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $users[] = $row;
    }
}

$total_officers = count($users);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Officers - AGH</title>
    <link rel="icon" type="image/png" href="../favicon.png">

    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Bengali:wght@300;400;500;600;700;800&family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">

    <style>
        body {
            font-family: 'Noto Sans Bengali', 'Poppins', sans-serif;
        }

        .page-bg {
            background:
                radial-gradient(circle at top left, rgba(14, 165, 233, 0.18), transparent 34%),
                radial-gradient(circle at bottom right, rgba(16, 185, 129, 0.18), transparent 34%),
                linear-gradient(135deg, #f8fafc 0%, #eff6ff 48%, #ecfdf5 100%);
        }

        .glass {
            background: rgba(255, 255, 255, 0.78);
            backdrop-filter: blur(18px);
            -webkit-backdrop-filter: blur(18px);
        }

        .panel {
            border: 1px solid rgba(226, 232, 240, 0.9);
            background: rgba(255, 255, 255, 0.9);
            box-shadow: 0 24px 70px rgba(15, 23, 42, 0.08);
        }

        .field {
            width: 100%;
            border-radius: 1rem;
            border: 1px solid #e2e8f0;
            background: rgba(248, 250, 252, 0.95);
            padding: 0.9rem 1rem;
            color: #0f172a;
            outline: none;
            transition: 0.2s ease;
        }

        .field:focus {
            border-color: #0ea5e9;
            background: #ffffff;
            box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.13);
        }

        .label {
            display: block;
            margin-bottom: 0.45rem;
            font-size: 0.875rem;
            font-weight: 700;
            color: #475569;
        }

        .modal {
            background: rgba(15, 23, 42, 0.62);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
    </style>
</head>

<body class="page-bg min-h-screen text-slate-800">

    <nav class="sticky top-0 z-50 border-b border-white/70 glass shadow-sm">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
            <div class="flex items-center justify-between gap-4">
                <div class="flex items-center gap-6">
                    <a href="index.php" class="flex items-center gap-3">
                        <div class="h-12 w-12 rounded-2xl bg-gradient-to-br from-sky-700 to-emerald-500 text-white flex items-center justify-center font-extrabold shadow-lg shadow-sky-200">
                            AGH
                        </div>
                        <div>
                            <h1 class="text-lg sm:text-xl font-extrabold text-slate-900">AGH Admin</h1>
                            <p class="text-xs text-slate-500">Officer Management</p>
                        </div>
                    </a>

                    <div class="hidden md:flex items-center gap-2">
                        <a href="index.php" class="rounded-full bg-white border border-slate-100 text-slate-600 hover:text-sky-700 hover:bg-sky-50 px-4 py-2 text-sm font-bold transition">
                            রুগী সার্চ
                        </a>
                        <a href="users.php" class="rounded-full bg-sky-600 text-white px-4 py-2 text-sm font-bold shadow-lg shadow-sky-100">
                            অফিসার ম্যানেজমেন্ট
                        </a>
                    </div>
                </div>

                <a href="../logout.php" class="inline-flex items-center gap-2 rounded-full bg-red-500 hover:bg-red-600 text-white px-4 py-2 text-sm font-bold transition shadow-lg shadow-red-100">
                    <svg width="17" height="17" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                        <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
                        <path d="M16 17l5-5-5-5"></path>
                        <path d="M21 12H9"></path>
                    </svg>
                    লগআউট
                </a>
            </div>
        </div>
    </nav>

    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

        <section class="relative overflow-hidden rounded-[2rem] bg-gradient-to-br from-sky-800 via-blue-700 to-emerald-600 text-white p-6 sm:p-8 lg:p-10 shadow-2xl shadow-sky-200 mb-8">
            <div class="absolute inset-0 opacity-15 bg-[linear-gradient(135deg,white_1px,transparent_1px)] bg-[length:24px_24px]"></div>

            <div class="relative z-10 flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6">
                <div>
                    <p class="text-sm font-semibold uppercase tracking-[0.28em] text-sky-100">Admin Control</p>
                    <h2 class="mt-4 text-3xl sm:text-5xl font-extrabold leading-tight">অফিসার ম্যানেজমেন্ট</h2>
                    <p class="mt-4 max-w-2xl text-sky-50 leading-8">
                        নতুন অফিসার তৈরি, প্রোফাইল আপডেট, পাসওয়ার্ড রিসেট এবং অ্যাকাউন্ট ম্যানেজ করুন।
                    </p>
                </div>

                <div class="rounded-3xl bg-white/15 border border-white/20 p-5 min-w-full sm:min-w-[240px]">
                    <p class="text-sm font-bold text-sky-100">মোট অফিসার</p>
                    <p class="mt-2 text-5xl font-extrabold"><?php echo e($total_officers); ?></p>
                </div>
            </div>
        </section>

        <?php if ($message['text'] !== ''): ?>
            <div class="mb-6 rounded-3xl border px-5 py-4 font-bold flex items-center gap-3 <?php echo $message['type'] === 'success' ? 'border-emerald-200 bg-emerald-50 text-emerald-800' : 'border-red-200 bg-red-50 text-red-700'; ?>">
                <span class="h-10 w-10 rounded-2xl flex items-center justify-center <?php echo $message['type'] === 'success' ? 'bg-emerald-100' : 'bg-red-100'; ?>">
                    <?php if ($message['type'] === 'success'): ?>
                        <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                            <path d="M20 6 9 17l-5-5"></path>
                        </svg>
                    <?php else: ?>
                        <svg width="22" height="22" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                            <path d="M12 9v4"></path>
                            <path d="M12 17h.01"></path>
                            <path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0Z"></path>
                        </svg>
                    <?php endif; ?>
                </span>
                <?php echo e($message['text']); ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">

            <aside class="panel rounded-[2rem] p-5 sm:p-7 h-fit">
                <div class="flex items-center gap-3 mb-6">
                    <div class="h-12 w-12 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center">
                        <svg width="26" height="26" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>
                            <circle cx="9" cy="7" r="4"></circle>
                            <path d="M19 8v6"></path>
                            <path d="M22 11h-6"></path>
                        </svg>
                    </div>
                    <div>
                        <h3 class="text-xl font-extrabold text-slate-900">নতুন অফিসার</h3>
                        <p class="text-sm text-slate-500 mt-1">লগইন অ্যাকাউন্ট তৈরি করুন</p>
                    </div>
                </div>

                <form action="" method="POST" class="space-y-4">
                    <div>
                        <label for="full_name" class="label">পুরো নাম</label>
                        <input id="full_name" type="text" name="full_name" required class="field" placeholder="অফিসারের নাম">
                    </div>

                    <div>
                        <label for="username" class="label">ইউজারনেম</label>
                        <input id="username" type="text" name="username" required class="field" placeholder="যেমন: officer01">
                    </div>

                    <div>
                        <label for="password" class="label">পাসওয়ার্ড</label>
                        <input id="password" type="password" name="password" required class="field" placeholder="নতুন পাসওয়ার্ড">
                    </div>

                    <button type="submit" name="add_user" class="w-full inline-flex items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-sky-600 to-emerald-500 px-5 py-4 font-extrabold text-white shadow-xl shadow-sky-100 transition hover:-translate-y-0.5 hover:shadow-2xl">
                        <svg width="19" height="19" fill="none" stroke="currentColor" stroke-width="2.4" viewBox="0 0 24 24">
                            <path d="M12 5v14"></path>
                            <path d="M5 12h14"></path>
                        </svg>
                        অফিসার সেভ করুন
                    </button>
                </form>
            </aside>

            <section class="lg:col-span-2 panel rounded-[2rem] overflow-hidden">
                <div class="p-6 sm:p-7 border-b border-slate-100 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <p class="text-sm font-bold text-sky-600">Officer List</p>
                        <h3 class="mt-1 text-2xl font-extrabold text-slate-900">সকল অফিসার</h3>
                    </div>

                    <span class="inline-flex items-center justify-center rounded-full bg-slate-100 text-slate-700 px-4 py-2 text-sm font-extrabold">
                        <?php echo e($total_officers); ?> জন অফিসার
                    </span>
                </div>

                <div class="overflow-x-auto">
                    <table class="w-full text-left">
                        <thead>
                            <tr class="bg-slate-50 text-slate-500 text-xs uppercase tracking-wider">
                                <th class="px-6 py-4 font-extrabold">অফিসার</th>
                                <th class="px-6 py-4 font-extrabold text-right">অ্যাকশন</th>
                            </tr>
                        </thead>

                        <tbody class="divide-y divide-slate-100">
                            <?php foreach ($users as $user): ?>
                                <tr class="hover:bg-sky-50/60 transition">
                                    <td class="px-6 py-5">
                                        <div class="flex items-center gap-3">
                                            <div class="h-12 w-12 rounded-2xl bg-sky-100 text-sky-700 flex items-center justify-center font-extrabold">
                                                <?php echo e(initial_letter($user['full_name'])); ?>
                                            </div>
                                            <div>
                                                <p class="font-extrabold text-slate-900"><?php echo e($user['full_name']); ?></p>
                                                <p class="text-sm text-slate-500 mt-1">@<?php echo e($user['username']); ?></p>
                                            </div>
                                        </div>
                                    </td>

                                    <td class="px-6 py-5">
                                        <div class="flex flex-wrap justify-end gap-2">
                                            <button
                                                type="button"
                                                data-id="<?php echo e($user['id']); ?>"
                                                data-name="<?php echo e($user['full_name']); ?>"
                                                data-username="<?php echo e($user['username']); ?>"
                                                onclick="openEditModal(this)"
                                                class="inline-flex items-center gap-2 rounded-2xl bg-sky-50 hover:bg-sky-100 text-sky-700 px-4 py-2 text-sm font-extrabold transition">
                                                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                                                    <path d="M12 20h9"></path>
                                                    <path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"></path>
                                                </svg>
                                                এডিট
                                            </button>

                                            <button
                                                type="button"
                                                data-id="<?php echo e($user['id']); ?>"
                                                data-name="<?php echo e($user['full_name']); ?>"
                                                onclick="openPassModal(this)"
                                                class="inline-flex items-center gap-2 rounded-2xl bg-amber-50 hover:bg-amber-100 text-amber-700 px-4 py-2 text-sm font-extrabold transition">
                                                <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                                                    <rect x="3" y="11" width="18" height="11" rx="2"></rect>
                                                    <path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
                                                </svg>
                                                পাসওয়ার্ড
                                            </button>

                                            <form action="" method="POST" onsubmit="return confirm('আপনি কি নিশ্চিতভাবে এই অফিসার ডিলিট করতে চান?');">
                                                <input type="hidden" name="user_id" value="<?php echo e($user['id']); ?>">
                                                <button type="submit" name="delete_user" class="inline-flex items-center gap-2 rounded-2xl bg-red-50 hover:bg-red-100 text-red-600 px-4 py-2 text-sm font-extrabold transition">
                                                    <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                                                        <path d="M3 6h18"></path>
                                                        <path d="M8 6V4h8v2"></path>
                                                        <path d="M19 6l-1 14H6L5 6"></path>
                                                    </svg>
                                                    ডিলিট
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>

                            <?php if ($total_officers === 0): ?>
                                <tr>
                                    <td colspan="2" class="px-6 py-16 text-center">
                                        <div class="mx-auto h-16 w-16 rounded-3xl bg-slate-100 text-slate-400 flex items-center justify-center mb-4">
                                            <svg width="32" height="32" fill="none" stroke="currentColor" stroke-width="1.8" viewBox="0 0 24 24">
                                                <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"></path>
                                                <circle cx="9" cy="7" r="4"></circle>
                                                <path d="M19 8v6"></path>
                                                <path d="M22 11h-6"></path>
                                            </svg>
                                        </div>
                                        <h4 class="text-lg font-extrabold text-slate-700">এখনো কোনো অফিসার নেই</h4>
                                        <p class="mt-2 text-sm text-slate-400">বাম পাশের ফর্ম থেকে নতুন অফিসার যোগ করুন।</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </section>

        </div>
    </main>

    <div id="editModal" class="modal fixed inset-0 z-[60] hidden items-center justify-center p-4">
        <div class="w-full max-w-md rounded-[2rem] bg-white p-6 shadow-2xl">
            <div class="flex items-center justify-between gap-4 mb-5">
                <div>
                    <p class="text-sm font-bold text-sky-600">Edit Profile</p>
                    <h3 class="text-2xl font-extrabold text-slate-900">তথ্য পরিবর্তন</h3>
                </div>
                <button type="button" onclick="closeEditModal()" class="h-10 w-10 rounded-2xl bg-slate-100 hover:bg-slate-200 text-slate-600 flex items-center justify-center transition">
                    <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                        <path d="M18 6 6 18"></path>
                        <path d="m6 6 12 12"></path>
                    </svg>
                </button>
            </div>

            <form action="" method="POST" class="space-y-4">
                <input type="hidden" name="user_id" id="edit_user_id">

                <div>
                    <label for="edit_name" class="label">নাম</label>
                    <input type="text" name="full_name" id="edit_name" required class="field">
                </div>

                <div>
                    <label for="edit_username" class="label">ইউজারনেম</label>
                    <input type="text" name="username" id="edit_username" required class="field">
                </div>

                <div class="grid grid-cols-2 gap-3 pt-2">
                    <button type="button" onclick="closeEditModal()" class="rounded-2xl bg-slate-100 hover:bg-slate-200 px-5 py-3 font-extrabold text-slate-700 transition">
                        বাতিল
                    </button>
                    <button type="submit" name="update_profile" class="rounded-2xl bg-sky-600 hover:bg-sky-700 px-5 py-3 font-extrabold text-white transition">
                        আপডেট
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div id="passModal" class="modal fixed inset-0 z-[60] hidden items-center justify-center p-4">
        <div class="w-full max-w-md rounded-[2rem] bg-white p-6 shadow-2xl">
            <div class="flex items-center justify-between gap-4 mb-5">
                <div>
                    <p class="text-sm font-bold text-amber-600">Password Reset</p>
                    <h3 class="text-2xl font-extrabold text-slate-900">পাসওয়ার্ড পরিবর্তন</h3>
                    <p id="pass_user_name" class="text-sm text-slate-500 mt-1"></p>
                </div>
                <button type="button" onclick="closePassModal()" class="h-10 w-10 rounded-2xl bg-slate-100 hover:bg-slate-200 text-slate-600 flex items-center justify-center transition">
                    <svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" viewBox="0 0 24 24">
                        <path d="M18 6 6 18"></path>
                        <path d="m6 6 12 12"></path>
                    </svg>
                </button>
            </div>

            <form action="" method="POST" class="space-y-4">
                <input type="hidden" name="user_id" id="pass_user_id">

                <div>
                    <label for="new_password" class="label">নতুন পাসওয়ার্ড</label>
                    <input type="password" name="new_password" id="new_password" required class="field" placeholder="নতুন পাসওয়ার্ড দিন">
                </div>

                <div class="grid grid-cols-2 gap-3 pt-2">
                    <button type="button" onclick="closePassModal()" class="rounded-2xl bg-slate-100 hover:bg-slate-200 px-5 py-3 font-extrabold text-slate-700 transition">
                        বাতিল
                    </button>
                    <button type="submit" name="update_pass" class="rounded-2xl bg-amber-500 hover:bg-amber-600 px-5 py-3 font-extrabold text-white transition">
                        রিসেট
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showModal(id) {
            const modal = document.getElementById(id);
            modal.classList.remove('hidden');
            modal.classList.add('flex');
        }

        function hideModal(id) {
            const modal = document.getElementById(id);
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        }

        function openEditModal(button) {
            document.getElementById('edit_user_id').value = button.dataset.id;
            document.getElementById('edit_name').value = button.dataset.name;
            document.getElementById('edit_username').value = button.dataset.username;
            showModal('editModal');
        }

        function closeEditModal() {
            hideModal('editModal');
        }

        function openPassModal(button) {
            document.getElementById('pass_user_id').value = button.dataset.id;
            document.getElementById('pass_user_name').textContent = button.dataset.name;
            document.getElementById('new_password').value = '';
            showModal('passModal');
        }

        function closePassModal() {
            hideModal('passModal');
        }

        document.addEventListener('keydown', function(event) {
            if (event.key === 'Escape') {
                closeEditModal();
                closePassModal();
            }
        });
    </script>

</body>
</html>
