<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

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");
}

/*
|--------------------------------------------------------------------------
| CREATE PERIOD
|--------------------------------------------------------------------------
*/
if(isset($_POST['save'])){
    $title = trim($_POST['title']);
    $startDate = $_POST['start_date'];
    $endDate = $_POST['end_date'];

    $stmt = $conn->prepare("
    INSERT INTO appraisal_periods
    (
        title,
        start_date,
        end_date
    )
    VALUES
    (
        ?,?,?
    )
    ");

    $stmt->bind_param(
        "sss",
        $title,
        $startDate,
        $endDate
    );

    $stmt->execute();

    header("Location: appraisal_periods.php?saved=1");
    exit;
}

/*
|--------------------------------------------------------------------------
| CLOSE PERIOD
|--------------------------------------------------------------------------
*/
if(isset($_GET['close'])){
    $id = intval($_GET['close']);

    $conn->query("
    UPDATE appraisal_periods
    SET status='Closed'
    WHERE id=$id
    ");

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

/*
|--------------------------------------------------------------------------
| REOPEN PERIOD
|--------------------------------------------------------------------------
*/
if(isset($_GET['open'])){
    $id = intval($_GET['open']);

    $conn->query("
    UPDATE appraisal_periods
    SET status='Open'
    WHERE id=$id
    ");

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

$periods = $conn->query("
SELECT *
FROM appraisal_periods
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>Appraisal Periods - 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 System</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">Appraisal Periods</h1>
            <p class="text-xs sm:text-sm text-gray-500 mt-1">
                Evaluation Cycle Controls &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>

    <!-- Toast Feedback Alerts -->
    <?php if(isset($_GET['saved'])): ?>
    <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 p-4 rounded-2xl shadow-sm flex items-center gap-3 text-sm font-semibold animate-fade-in">
        <span class="text-lg">✅</span> Appraisal operational cycle generated and logged successfully.
    </div>
    <?php endif; ?>

    <!-- 1. Creation Control Panel -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">1. Provisions Panel</h2>
        <div class="bg-white rounded-3xl p-5 sm:p-6 shadow-md border border-white/60">
            <div class="mb-5 flex items-center gap-3">
                <div class="w-8 h-8 rounded-lg bg-blue-50 text-blue-600 flex items-center justify-center font-bold">➕</div>
                <h2 class="text-lg font-extrabold text-gray-800">Create Appraisal Period</h2>
            </div>
            
            <form method="POST">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-5">
                    <div>
                        <label class="block mb-1.5 text-xs font-bold text-gray-500 uppercase tracking-wider">Title</label>
                        <input type="text" name="title" required placeholder="Annual Appraisal 2026" 
                               class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-sm focus:outline-none focus:border-blue-500 focus:bg-white transition-all">
                    </div>
                    <div>
                        <label class="block mb-1.5 text-xs font-bold text-gray-500 uppercase tracking-wider">Start Date</label>
                        <input type="date" name="start_date" required 
                               class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-sm focus:outline-none focus:border-blue-500 focus:bg-white transition-all">
                    </div>
                    <div>
                        <label class="block mb-1.5 text-xs font-bold text-gray-500 uppercase tracking-wider">End Date</label>
                        <input type="date" name="end_date" required 
                               class="w-full bg-slate-50 border border-slate-200 p-3 rounded-xl text-sm focus:outline-none focus:border-blue-500 focus:bg-white transition-all">
                    </div>
                </div>
                <button name="save" class="mt-6 bg-blue-600 hover:bg-blue-700 text-white font-bold text-sm px-6 py-3 rounded-xl shadow-md hover:shadow-lg transition-all duration-300">
                    Create Period
                </button>
            </form>
        </div>
    </div>

    <!-- 2. Historical Logs Table Block -->
    <div class="space-y-3">
        <h2 class="text-xs font-bold text-slate-500 uppercase tracking-widest px-1">2. Configured Appraisal Ledger</h2>
        <div class="bg-white rounded-3xl shadow-md border border-white/60 overflow-hidden">
            <div class="overflow-x-auto w-full">
                <table class="w-full text-left border-collapse whitespace-nowrap">
                    <thead>
                        <tr class="bg-slate-50 border-b border-slate-100 text-slate-400 text-[11px] font-bold uppercase tracking-wider">
                            <th class="p-4 sm:p-5">Title</th>
                            <th class="p-4 sm:p-5 text-center">Start Date</th>
                            <th class="p-4 sm:p-5 text-center">End Date</th>
                            <th class="p-4 sm:p-5 text-center">Status</th>
                            <th class="p-4 sm:p-5 text-center">Action</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-100 text-sm text-gray-700">
                        <?php while($row = $periods->fetch_assoc()): ?>
                        <tr class="hover:bg-slate-50/80 transition-colors">
                            <td class="p-4 sm:p-5 font-bold text-gray-800">
                                <?= htmlspecialchars($row['title']) ?>
                            </td>
                            <td class="p-4 sm:p-5 text-center text-gray-500 font-mono">
                                <?= date('d M Y', strtotime($row['start_date'])) ?>
                            </td>
                            <td class="p-4 sm:p-5 text-center text-gray-500 font-mono">
                                <?= date('d M Y', strtotime($row['end_date'])) ?>
                            </td>
                            <td class="p-4 sm:p-5 text-center">
                                <?php if($row['status'] == 'Open'): ?>
                                <span class="inline-block bg-emerald-100 text-emerald-800 text-[11px] font-black px-3 py-1 rounded-lg uppercase tracking-wide">
                                    Open
                                </span>
                                <?php else: ?>
                                <span class="inline-block bg-rose-100 text-rose-800 text-[11px] font-black px-3 py-1 rounded-lg uppercase tracking-wide">
                                    Closed
                                </span>
                                <?php endif; ?>
                            </td>
                            <td class="p-4 sm:p-5 text-center">
                                <?php if($row['status'] == 'Open'): ?>
                                <a href="?close=<?= $row['id'] ?>" 
                                   class="inline-block bg-rose-50 hover:bg-rose-600 text-rose-600 hover:text-white font-extrabold text-xs px-4 py-2 rounded-xl transition-all border border-rose-200/50">
                                    Close Cycle
                                </a>
                                <?php else: ?>
                                <a href="?open=<?= $row['id'] ?>" 
                                   class="inline-block bg-emerald-50 hover:bg-emerald-600 text-emerald-600 hover:text-white font-extrabold text-xs px-4 py-2 rounded-xl transition-all border border-emerald-200/50">
                                    Reopen Cycle
                                </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

</div>

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