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

if (session_status() === PHP_SESSION_NONE && !headers_sent()) { session_start(); }
session_write_close();

// 1. Authentication & Access Control
$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    header("Location: ../login.php");
    exit;
}

// 2. Resolve user_id to Internally Recognized employee_id
$empStmt = $conn->prepare("SELECT id, shift_id FROM employees WHERE user_id = ? LIMIT 1");
if (!$empStmt) {
    die("Database setup mapping fault.");
}
$empStmt->bind_param("i", $userId);
$empStmt->execute();
$empRes = $empStmt->get_result()->fetch_assoc();
$empStmt->close();

if (!$empRes) {
    die("Error: No employee profile record matches this user session account.");
}

$employeeId     = intval($empRes['id']);
$defaultShiftId = $empRes['shift_id'];

// 3. Timeline Window Modifier Management
$periodType = $_GET['type'] ?? 'weekly';
$selectedDate = $_GET['start'] ?? date('Y-m-d');

if ($periodType === 'weekly') {
    $startDate = date('Y-m-d', strtotime('monday this week', strtotime($selectedDate)));
} else {
    $startDate = date('Y-m-01', strtotime($selectedDate));
}

// 4. Build Matrix Timeline Date Array
$days = [];
if ($periodType === 'weekly') {
    for ($i = 0; $i < 7; $i++) {
        $days[] = date('Y-m-d', strtotime("$startDate +$i day"));
    }
} else {
    $daysInMonth = date('t', strtotime($startDate));
    for ($i = 0; $i < $daysInMonth; $i++) {
        $days[] = date('Y-m-d', strtotime("$startDate +$i day"));
    }
}
$endDate = end($days);

// 5. Load Shifts Dictionary for Meta Lookups
$shifts = [];
$res = $conn->query("SELECT * FROM shifts ORDER BY name");
while ($row = $res->fetch_assoc()) {
    $shifts[$row['id']] = $row;
}

$defaultShiftName = isset($shifts[$defaultShiftId]) ? $shifts[$defaultShiftId]['name'] : '— NA —';

// 6. Color Engine Compiler Rules
function shiftColor($shiftName) {
    $shiftName = strtolower(trim((string)$shiftName));
    if (str_contains($shiftName, 'morning') || $shiftName === 'am') return '#16a34a'; // Slate green
    if (str_contains($shiftName, 'afternoon') || $shiftName === 'pm') return '#2563eb'; // Slate blue
    if (str_contains($shiftName, 'night') || $shiftName === 'mod') return '#1e293b'; // Slate gray-900
    if (str_contains($shiftName, 'off')) return '#dc2626'; // Deep slate red
    if ($shiftName === 'ph') return '#7c3aed';
    if ($shiftName === 'sl') return '#d97706';
    if ($shiftName === 'w') return '#334155';
    return '#64748b';
}

$shiftColors = [];
foreach ($shifts as $shift) {
    $shiftColors[(string)$shift['id']] = shiftColor($shift['name']);
}

// 7. Query Custom Active Target Roster Overrides
$customOverrides = [];
$stmt = $conn->prepare("
    SELECT ds.schedule_date, ds.shift_id, s.name as shift_name
    FROM department_schedules ds
    LEFT JOIN shifts s ON s.id = ds.shift_id
    WHERE ds.employee_id = ? AND ds.schedule_date BETWEEN ? AND ?
");
$stmt->bind_param("iss", $employeeId, $startDate, $endDate);
$stmt->execute();
$res = $stmt->get_result();

while ($row = $res->fetch_assoc()) {
    $customOverrides[$row['schedule_date']] = [
        'shift_id'   => $row['shift_id'],
        'shift_name' => $row['shift_name']
    ];
}
$stmt->close();
$conn->close();

// 8. Matrix Builder Applying Strategic System Overrides or Fallbacks
$schedule = [];
foreach ($days as $day) {
    if (isset($customOverrides[$day])) {
        $schedule[$day] = $customOverrides[$day];
    } else {
        $schedule[$day] = [
            'shift_id'   => $defaultShiftId,
            'shift_name' => $defaultShiftName
        ];
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Work Schedule Roster - Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="../components/sidebar.css">
    <style>
        .custom-scrollbar::-webkit-scrollbar { height: 6px; width: 6px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 99px; }
        
        @media print {
            .no-print, #sidebar, #sidebar-overlay, header { display: none !important; }
            body { background: white !important; color: #0f172a !important; }
            #main-content { padding: 0 !important; margin: 0 !important; width: 100% !important; max-width: 100% !important; }
            .desktop-matrix-view { display: table !important; width: 100% !important; table-layout: fixed !important; }
            .mobile-card-view { display: none !important; }
        }
    </style>
</head>
<body class="bg-stone-100 min-h-screen text-slate-800 antialiased 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 no-print" 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 no-print">
                <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" aria-label="Toggle Side Area Menu">
                        <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 uppercase">Deployment</h1>
                        <p class="text-[10px] text-slate-500 font-bold uppercase tracking-wider">My Work Schedule</p>
                    </div>
                </div>
                <button onclick="window.print()" class="bg-slate-900 hover:bg-slate-800 text-white font-bold text-[10px] uppercase tracking-wider px-3 py-1.5 rounded-lg transition shadow-xs flex items-center gap-2">
                    🖨️ Print Sheet
                </button>
            </header>

            <main class="flex-1 p-4 sm:p-6 max-w-7xl w-full mx-auto space-y-6">

                <div class="bg-white border border-slate-300/80 p-5 rounded-xl shadow-xs flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                    <div>
                        <h2 class="text-sm font-black text-slate-950 uppercase tracking-tight">Personal Schedule Matrix</h2>
                        <p class="text-[11px] text-slate-500 font-medium mt-0.5">Read-only institutional deployment calendar, tactical shift mapping indices, and dynamic assignment grids.</p>
                    </div>
                </div>

                <!-- Parameters Controls Panel -->
                <div class="bg-white border border-slate-300/80 p-4 rounded-xl shadow-xs no-print">
                    <form method="GET" class="grid grid-cols-1 sm:grid-cols-3 gap-4 items-end">
                        <div class="flex flex-col gap-1">
                            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Scope Window Framework</label>
                            <select name="type" class="border border-slate-300 p-2 rounded-lg bg-stone-50 text-xs font-bold text-slate-800 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                                <option value="weekly" <?= $periodType == 'weekly' ? 'selected' : '' ?>>Weekly View Matrix</option>
                                <option value="monthly" <?= $periodType == 'monthly' ? 'selected' : '' ?>>Monthly View Matrix</option>
                            </select>
                        </div>

                        <div class="flex flex-col gap-1">
                            <label class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Target Initialization Date</label>
                            <input type="date" name="start" value="<?= $periodType === 'weekly' ? $startDate : $selectedDate ?>" class="border border-slate-300 p-2 rounded-lg bg-stone-50 text-xs font-mono font-bold text-slate-800 focus:outline-none focus:border-slate-400 focus:bg-white transition">
                        </div>

                        <button type="submit" class="bg-slate-900 hover:bg-slate-800 text-white py-2 rounded-lg font-bold text-[11px] uppercase tracking-wider transition shadow-xs">
                            Sync Timeline Matrix
                        </button>
                    </form>
                </div>

                <!-- Color Engine System Legend -->
                <div class="bg-white px-4 py-3 rounded-xl border border-slate-300/80 shadow-xs no-print flex flex-wrap gap-3 items-center">
                    <span class="text-[10px] font-black text-slate-400 uppercase tracking-wider">Matrix Legend Directory:</span>
                    <div class="flex flex-wrap gap-2">
                        <?php foreach ($shifts as $shift): ?>
                            <div class="text-white px-2 py-0.5 border border-black/10 text-[9px] font-black tracking-wide uppercase rounded font-mono shadow-xs flex items-center justify-center min-w-[42px]" 
                                 style="background: <?= shiftColor($shift['name']) ?>" 
                                 title="<?= htmlspecialchars($shift['name']) ?> (<?= substr($shift['checkin'], 0, 5) ?> - <?= substr($shift['checkout'], 0, 5) ?>)">
                                <?= htmlspecialchars(str_contains(strtolower($shift['name']), 'off') ? 'OFF' : substr(trim($shift['name']), 0, 3)) ?>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Responsive Mobile Card Viewports -->
                <div class="mobile-card-view grid grid-cols-2 sm:grid-cols-3 gap-3 md:hidden">
                    <?php foreach ($days as $day): 
                        $currentShiftId = $schedule[$day]['shift_id'] ?? '';
                        $currentShiftName = $schedule[$day]['shift_name'] ?? '— NA —';
                        $bg = $currentShiftId ? ($shiftColors[$currentShiftId] ?? '#64748b') : '#94a3b8';
                        $isToday = ($day === date('Y-m-d')) ? 'border-2 border-slate-900' : 'border border-slate-300/80';
                    ?>
                        <div class="bg-white rounded-xl p-3 shadow-xs flex flex-col justify-between min-h-[100px] <?= $isToday ?>">
                            <div class="flex items-center justify-between border-b border-slate-100 pb-1 mb-2">
                                <span class="text-[11px] font-black text-slate-950 uppercase"><?= date('D', strtotime($day)) ?></span>
                                <span class="text-[10px] text-slate-400 font-mono font-bold"><?= date('d M', strtotime($day)) ?></span>
                            </div>
                            <div class="text-white text-center py-1.5 px-1 rounded-lg font-black text-[10px] uppercase tracking-wider shadow-xs truncate" style="background: <?= $bg ?>">
                                <?= htmlspecialchars($currentShiftName) ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- Master Enterprise Desktop Schedule Table Viewport -->
                <div class="desktop-matrix-view hidden md:block bg-white rounded-xl shadow-xs border border-slate-300/80 overflow-hidden">
                    <div class="overflow-x-auto w-full custom-scrollbar">
                        <table class="w-full border-collapse table-fixed min-w-[700px]">
                            <thead>
                                <tr class="bg-stone-50 border-b border-slate-300/80 text-[10px] font-black uppercase tracking-wider text-slate-400">
                                    <?php foreach ($days as $day): 
                                        $thToday = ($day === date('Y-m-d')) ? 'bg-slate-200/50 border-b-2 border-b-slate-900' : '';
                                    ?>
                                        <th class="p-3 text-center border-r border-slate-200 last:border-0 min-w-[90px] transition-all <?= $thToday ?>">
                                            <div class="text-[11px] font-black text-slate-950 tracking-tight"><?= date('D', strtotime($day)) ?></div>
                                            <div class="text-[10px] text-slate-400 font-mono mt-0.5"><?= date('d M', strtotime($day)) ?></div>
                                        </th>
                                    <?php endforeach; ?>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="divide-x divide-slate-200">
                                    <?php foreach ($days as $day): ?>
                                        <?php
                                        $currentShiftId = $schedule[$day]['shift_id'] ?? '';
                                        $currentShiftName = $schedule[$day]['shift_name'] ?? '— NA —';
                                        $bg = $currentShiftId ? ($shiftColors[$currentShiftId] ?? '#64748b') : '#94a3b8';
                                        $tdToday = ($day === date('Y-m-d')) ? 'p-2.5 bg-slate-100/50' : 'p-2';
                                        ?>
                                        <td class="<?= $tdToday ?> transition-all">
                                            <div class="w-full h-14 rounded-lg flex flex-col items-center justify-center text-white select-none shadow-xs border border-black/5 transition-all duration-150 hover:scale-[1.02] cursor-help px-1.5" 
                                                 style="background: <?= $bg ?>"
                                                 title="Assigned Deployment Module: <?= htmlspecialchars($currentShiftName) ?>">
                                                <span class="text-[10px] font-black tracking-wider uppercase text-center drop-shadow-xs truncate w-full">
                                                    <?= htmlspecialchars($currentShiftName) ?>
                                                </span>
                                            </div>
                                        </td>
                                    <?php endforeach; ?>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>

            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center no-print">
                <p class="text-[9px] text-slate-500 font-mono tracking-wider">&copy; 2026 Core HR Engine System Platform • Dynamic Secure Architecture Protocol.</p>
            </footer>

        </div>
    </div>

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