<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
require '../config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: ../login.php");
    exit;
}

$username = $_SESSION['username'] ?? 'Admin';
$role     = $_SESSION['role'] ?? 'HR Admin';

// Pre-fill employee if passed via URL
$pre_emp_id = (int)($_GET['employee_id'] ?? 0);

// Fetch employees who do not have an active ID card (or fetch target employee)
$emp_query = "SELECT e.id, e.employee_no, e.name, e.designation, d.name AS department_name 
              FROM employees e 
              LEFT JOIN departments d ON (d.id = e.department_id OR d.name = e.department_id)
              ORDER BY e.name ASC";
$emp_res = $conn->query($emp_query);

// Auto-generate next Card Number (IDC-YYYY-XXXX)
$year = date('Y');
$count_res = $conn->query("SELECT COUNT(*) AS total FROM id_cards");
$next_num = ($count_res->fetch_assoc()['total'] ?? 0) + 1;
$auto_card_no = sprintf("IDC-%s-%04d", $year, $next_num);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Issue New ID Card - HR System</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=Mulish:ital,wght=0,200..1000;1,200..1000&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = { theme: { extend: { fontFamily: { sans: ['Mulish', 'sans-serif'] } } } }
    </script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-stone-100/60 min-h-screen text-slate-800 antialiased selection:bg-indigo-600 selection:text-white font-sans">

    <div class="flex">
        <?php include '../components/sidebar.php'; ?>
        <div id="sidebar-overlay" class="fixed inset-0 bg-slate-900/40 hidden z-40 transition-opacity duration-300" onclick="toggleSidebar()"></div>

        <div id="main-content" class="flex-1 min-w-0 md:pl-60 transition-all duration-300 min-h-screen flex flex-col">
            
            <header class="sticky top-0 bg-white/90 backdrop-blur-md border-b border-slate-300/80 h-14 flex items-center justify-between px-4 sm:px-6 z-30 shadow-xs">
                <div class="flex items-center gap-3">
                    <button onclick="toggleSidebar()" class="p-1.5 rounded-lg text-slate-600 hover:bg-slate-200/80 transition active:scale-95">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M4 6h16M4 12h16M4 18h16"></path></svg>
                    </button>
                    <div>
                        <h1 class="text-sm font-black tracking-tight text-slate-950">Issue ID Card</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Credential Assignment</p>
                    </div>
                </div>
                <div class="flex items-center gap-4">
                    <a href="index.php" class="text-xs font-bold text-slate-600 hover:text-slate-900 transition flex items-center gap-1">
                        ← Back to Dashboard
                    </a>
                </div>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-3xl w-full mx-auto space-y-6">
                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    <div class="px-6 py-4 border-b border-slate-200 bg-stone-50/50">
                        <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">Card Issuance Details</h3>
                        <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Assign physical credential parameters to an active employee.</p>
                    </div>

                    <form action="save.php" method="POST" class="p-6 space-y-4">
                        <div>
                            <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Select Employee *</label>
                            <select name="employee_id" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                                <option value="">-- Choose Employee --</option>
                                <?php if ($emp_res): while ($e = $emp_res->fetch_assoc()): ?>
                                    <option value="<?= $e['id'] ?>" <?= $pre_emp_id == $e['id'] ? 'selected' : '' ?>>
                                        <?= htmlspecialchars($e['name']) ?> (<?= htmlspecialchars($e['employee_no']) ?>) — <?= htmlspecialchars($e['designation'] ?? 'Staff') ?>
                                    </option>
                                <?php endwhile; endif; ?>
                            </select>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Card Serial Number *</label>
                                <input type="text" name="card_number" value="<?= htmlspecialchars($auto_card_no); ?>" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-mono font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                            </div>

                            <div>
                                <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Template Style</label>
                                <select name="template" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                                    <option value="default">Best Western Corporate (Default)</option>
                                    <option value="minimal">Executive Minimalist</option>
                                </select>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Issue Date *</label>
                                <input type="date" name="issue_date" value="<?= date('Y-m-d'); ?>" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                            </div>

                            <div>
                                <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Expiry Date *</label>
                                <input type="date" name="expiry_date" value="<?= date('Y-m-d', strtotime('+3 years')); ?>" required class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                            </div>
                        </div>

                        <div>
                            <label class="block text-[10px] font-extrabold uppercase text-slate-600 mb-1">Card Status</label>
                            <select name="status" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none">
                                <option value="Active">Active</option>
                                <option value="Suspended">Suspended</option>
                                <option value="Expired">Expired</option>
                            </select>
                        </div>

                        <div class="pt-4 border-t border-slate-200 flex items-center justify-end gap-3">
                            <a href="index.php" class="px-4 py-2 bg-stone-100 hover:bg-slate-200 text-slate-700 font-bold text-xs rounded-lg transition">Cancel</a>
                            <button type="submit" class="px-4 py-2 bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-xs rounded-lg shadow-sm transition active:scale-95">Generate & Save Card</button>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>
    <script src="../components/sidebar.js"></script>
    <?php include '../loader_overlay.php'; ?>
</body>
</html>