<?php
require '../config.php';
session_start();
session_write_close();

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

$role = strtolower($_SESSION['role'] ?? '');
$username = $_SESSION['username'] ?? 'Executive';

if(!in_array($role, ['superadmin', 'admin', 'hr'])){
    die("Access Denied");
}

if($_SERVER['REQUEST_METHOD']=='POST'){
    $periodId = intval($_POST['period_id']);

    $employees = $conn->query("
    SELECT id 
    FROM employees 
    ORDER BY name
    ");

    while($emp = $employees->fetch_assoc()){
        $employeeId = $emp['id'];

        $check = $conn->query("
        SELECT id 
        FROM employee_appraisals 
        WHERE period_id = $periodId 
        AND employee_id = $employeeId
        ");

        if($check->num_rows == 0){
            $conn->query("
            INSERT INTO employee_appraisals 
            (
                period_id, 
                employee_id
            ) 
            VALUES 
            (
                $periodId, 
                $employeeId
            )
            ");
        }
    }

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

$periods = $conn->query("
SELECT * 
FROM appraisal_periods 
WHERE status='Open'
ORDER BY id DESC
");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Appraisals - Executive HR Boardroom</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
</head>
<body class="bg-gradient-to-br from-slate-100 via-blue-50 to-indigo-100 min-h-screen flex flex-col md:flex-row overflow-x-hidden font-sans">

<?php include '../components/sidebar.php'; ?>

<div id="sidebar-overlay" class="fixed inset-0 bg-black/50 hidden z-40" onclick="toggleSidebar()"></div>

<!-- Responsive Mobile Navigation Bar -->
<div class="mobile-trigger-bar w-full bg-slate-900 text-white flex items-center justify-between p-4 md:hidden sticky top-0 z-30 shadow-md">
    <span class="font-bold tracking-wide">HR Engine</span>
    <button onclick="toggleSidebar()" class="bg-white/10 hover:bg-white/20 px-3 py-2 rounded-lg text-xl transition">
        ☰
    </button>
</div>

<!-- Main Content Area Wrapper -->
<div id="main-content" class="flex-1 content-expanded transition-all duration-300 w-full p-4 sm:p-6 lg:p-8 space-y-6 sm:space-y-8">

    <!-- Top Profile Header Frame -->
    <div class="bg-white/70 backdrop-blur-xl border border-white/40 p-5 rounded-3xl shadow-sm flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
        <div>
            <h1 class="text-2xl sm:text-3xl font-black text-gray-800">Generate Appraisal Cycle</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Batch Target Initialization Engine &bull; Signed in as <span class="font-extrabold text-blue-600"><?= htmlspecialchars($username); ?></span>
            </p>
        </div>
        <div class="bg-blue-100 text-blue-700 px-4 py-2 rounded-xl font-bold text-xs sm:text-sm shadow-sm text-center">
            Role Level: <span class="font-black uppercase"><?= htmlspecialchars($role); ?></span>
        </div>
    </div>

    <!-- Configuration Control Panel Grid -->
    <div class="max-w-xl space-y-3 mx-auto lg:mx-0">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">Initialization Target</h2>
        <div class="bg-white rounded-3xl p-6 sm:p-8 shadow-md border border-white/60 space-y-6">
            <div class="flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-indigo-50 text-indigo-600 flex items-center justify-center font-bold text-lg">⚙️</div>
                <div>
                    <h2 class="text-lg font-extrabold text-gray-800">Operational Scope</h2>
                    <p class="text-xs text-gray-400">Initialize standard evaluations for all active personnel.</p>
                </div>
            </div>

            <form method="POST" class="space-y-6">
                <div>
                    <label class="block mb-2 text-xs font-bold text-gray-500 uppercase tracking-wider">
                        Select Active Target Period
                    </label>
                    <select name="period_id" required 
                            class="w-full bg-slate-50 border border-slate-200 p-3.5 rounded-xl text-sm font-semibold text-gray-700 focus:outline-none focus:border-blue-500 focus:bg-white transition-all shadow-inner appearance-none cursor-pointer">
                        <?php if($periods->num_rows == 0): ?>
                            <option value="" disabled selected>No active operational periods found...</option>
                        <?php else: ?>
                            <?php while($p = $periods->fetch_assoc()): ?>
                            <option value="<?= $p['id'] ?>">
                                <?= htmlspecialchars($p['title']) ?> (<?= date('M Y', strtotime($p['start_date'])) ?>)
                            </option>
                            <?php endwhile; ?>
                        <?php endif; ?>
                    </select>
                </div>

                <div class="bg-amber-50/60 border border-amber-200/60 rounded-2xl p-4 flex gap-3 text-xs text-amber-800 font-medium leading-relaxed">
                    <span class="text-base">⚠️</span>
                    <span><strong>Provisional Action Notice:</strong> This operation iterates through the employee directory and builds matching appraisal tracking matrix cards. Existing configurations remain secure.</span>
                </div>

                <div class="pt-2">
                    <button type="submit" 
                            <?php if($periods->num_rows == 0) echo 'disabled'; ?>
                            class="w-full bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 disabled:from-slate-300 disabled:to-slate-400 disabled:cursor-not-allowed text-white font-bold text-sm px-6 py-4 rounded-xl shadow-md hover:shadow-xl transition-all duration-300 transform hover:-translate-y-0.5 active:translate-y-0">
                        Generate Group Appraisals
                    </button>
                </div>
            </form>
        </div>
    </div>

</div>

<script src="../components/sidebar.js"></script>
</body>
</html>