<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_write_close();
require 'attendance_script.php';
$csvMessage = $_GET['csv_message'] ?? '';
$mailStatus = $_GET['mail_status'] ?? '';
$mailError  = $_GET['error'] ?? '';

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

$username = $_SESSION['username'];
$role = $_SESSION['role'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance - 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" 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">Attendance Center</h1>
                        <p class="text-[10px] text-indigo-700 font-bold uppercase tracking-wider">Log Verification</p>
                    </div>
                </div>
                
                <div class="flex items-center gap-4">
                    <div class="hidden sm:flex flex-col text-right">
                        <span class="text-[11px] font-extrabold text-slate-950 leading-tight"><?= htmlspecialchars($username); ?></span>
                        <span class="text-[9px] text-indigo-700 uppercase font-black tracking-wider leading-none mt-0.5"><?= htmlspecialchars($role ?: 'Staff'); ?></span>
                    </div>
                    <div class="w-7 h-7 bg-slate-200 border border-slate-300 rounded-lg flex items-center justify-center font-black text-xs text-slate-700 select-none uppercase">
                        <?= strtoupper(substr($username, 0, 1)); ?>
                    </div>
                </div>
            </header>

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

                <?php if($csvMessage): ?>
                <div id="csv-msg" class="bg-emerald-50 border border-emerald-300 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">✅</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-emerald-950">CSV Data Imported Successfully</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight"><?php echo htmlspecialchars($csvMessage); ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <?php if($mailStatus === 'success'): ?>
                <div class="bg-emerald-50 border border-emerald-300 text-emerald-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">📨</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-emerald-950">Attendance Report Dispatched</h3>
                        <p class="text-[11px] text-emerald-700 font-semibold leading-tight">The attendance log report email was generated and sent successfully.</p>
                    </div>
                </div>
                <?php elseif($mailStatus === 'error'): ?>
                <div class="bg-rose-50 border border-rose-300 text-rose-900 p-4 rounded-xl shadow-xs flex items-start gap-3 transition">
                    <div class="text-base leading-none mt-0.5">⚠️</div>
                    <div class="space-y-0.5">
                        <h3 class="font-black text-xs text-rose-950">Report Dispatch Failed</h3>
                        <p class="text-[11px] text-rose-700 font-semibold leading-tight"><?= htmlspecialchars($mailError ?: 'Unable to send report. Please check email system configuration.') ?></p>
                    </div>
                </div>
                <?php endif; ?>

                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    
                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-indigo-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Attendance Records</p>
                                <h4 class="text-2xl font-black tracking-tight text-slate-950"><?php echo count($attendance); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Total verified logged entries in scope.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-indigo-50 border border-indigo-200 flex items-center justify-center text-sm shrink-0">📅</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm hover:border-slate-400 transition-all">
                        <div class="flex items-start justify-between">
                            <div class="space-y-1">
                                <p class="text-[10px] font-extrabold text-slate-500 uppercase tracking-wider">Current Period Date</p>
                                <h4 class="text-xl font-black tracking-tight text-slate-950 mt-0.5"><?php echo date('d M Y'); ?></h4>
                                <p class="text-[10px] text-slate-600 font-semibold">Active processing server date.</p>
                            </div>
                            <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 flex items-center justify-center text-sm shrink-0">🕒</div>
                        </div>
                    </div>

                    <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm flex flex-col justify-between">
                        <div class="flex items-center justify-between gap-4">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-black text-indigo-700 uppercase tracking-widest">Email Distribution</p>
                                <h4 class="text-xs font-black text-slate-900">Send Report Email</h4>
                            </div>
                            <div class="text-lg">📩</div>
                        </div>
                        <button onclick="openEmailModal()" type="button" class="mt-3.5 w-full bg-indigo-600 hover:bg-indigo-700 text-white transition px-3 py-2 rounded-lg font-bold text-xs flex items-center justify-center gap-2 border border-indigo-700 shadow-xs active:scale-[0.98]">
                            Dispatch Log Report
                        </button>
                    </div>

                    <div class="bg-gradient-to-br from-slate-900 to-indigo-950 border border-slate-800 rounded-xl p-4 shadow-sm text-white flex flex-col justify-between">
                        <div class="flex items-center justify-between gap-4">
                            <div class="space-y-0.5">
                                <p class="text-[9px] font-black text-indigo-300 uppercase tracking-widest">Biometric Sync</p>
                                <h4 class="text-xs font-bold text-slate-100">Import CSV Raw Log</h4>
                            </div>
                            <div class="text-lg">⚡</div>
                        </div>
                        <form id="import-form" method="post" action="import_csv.php" class="mt-3.5">
                            <button id="import-btn" type="submit" class="w-full bg-white/10 hover:bg-white/15 transition px-3 py-2 rounded-lg font-bold text-xs flex items-center justify-center gap-2 border border-white/10 active:scale-[0.98]">
                                <span id="spinner" class="hidden animate-spin border-2 border-white border-t-transparent rounded-full w-3.5 h-3.5"></span>
                                Synchronize CSV Engine
                            </button>
                        </form>
                    </div>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl p-4 shadow-sm space-y-3">
                    <div class="flex items-center justify-between border-b border-slate-200 pb-2">
                        <h3 class="text-[10px] font-black text-slate-500 uppercase tracking-wider">Data Filters</h3>
                        <span class="text-[9px] font-bold text-indigo-700 uppercase">Apply search options</span>
                    </div>
                    <form method="get" class="grid grid-cols-1 sm:grid-cols-3 gap-3">
                        <input type="date" name="date" value="<?php echo htmlspecialchars($selectedDate ?? ''); ?>" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 font-mono font-bold">
                        <input type="text" name="search" placeholder="Search employee username..." value="<?php echo htmlspecialchars($search ?? ''); ?>" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 focus:ring-2 focus:ring-indigo-100 focus:border-indigo-500 outline-none text-xs text-slate-800 placeholder-slate-500 font-bold">
                        <button class="w-full bg-slate-900 hover:bg-slate-800 active:scale-[0.99] transition text-white rounded-lg font-bold py-2 text-xs shadow-sm border border-slate-950">Apply Parameters</button>
                    </form>
                </div>

                <div class="bg-white border border-slate-300/80 rounded-xl shadow-sm overflow-hidden">
                    
                    <div class="px-4 py-3 bg-stone-50/50 border-b border-slate-300/80 flex items-center justify-between">
                        <div>
                            <h3 class="text-xs font-black text-slate-950 uppercase tracking-tight">System Logs</h3>
                            <p class="text-[10px] text-slate-600 font-semibold mt-0.5">Detailed biometric evaluation data points.</p>
                        </div>
                        <span class="bg-indigo-50 text-indigo-800 border border-indigo-200 px-2.5 py-1 rounded-md font-extrabold text-[10px] font-mono shadow-xs">
                            <?php echo count($attendance); ?> Loaded
                        </span>
                    </div>

                    <div class="overflow-x-auto w-full">
                        <table class="w-full min-w-[800px] border-collapse">
                            <thead>
                                <tr class="bg-stone-50 text-slate-500 uppercase text-[9px] font-black tracking-wider border-b border-slate-300/80">
                                    <th class="p-3 text-left w-[250px]">Employee Information</th>
                                    <th class="p-3 text-center">Schedule Shift</th>
                                    <th class="p-3 text-center">Check-In Raw Log</th>
                                    <th class="p-3 text-center">Check-Out Raw Log</th>
                                    <th class="p-3 text-center">Duration</th>
                                    <th class="p-3 text-center">Metric Status</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-200/80 text-xs font-bold">

                            <?php if (empty($attendance)): ?>
                            <tr>
                                <td colspan="6" class="text-center py-12">
                                    <div class="flex flex-col items-center justify-center space-y-2">
                                        <div class="text-3xl">📭</div>
                                        <h4 class="text-xs font-extrabold text-slate-800">No Target Match Logs Found</h4>
                                        <p class="text-[10px] text-slate-600 max-w-xs">Adjust query parameters or apply standard sync processes.</p>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>

                            <?php foreach ($attendance as $name => $data): 
                                $shifts = $data['shifts'] ?? [];
                                foreach ($shifts as $shift): 
                            ?>
                            <tr class="hover:bg-stone-50/50 transition text-slate-800">
                                <td class="p-3 whitespace-nowrap">
                                    <div class="flex items-center gap-3">
                                        <div class="w-8 h-8 rounded-lg bg-stone-100 border border-slate-300 text-slate-700 flex items-center justify-center font-black text-xs select-none">
                                            <?php echo strtoupper(substr($name, 0, 1)); ?>
                                        </div>
                                        <div class="space-y-0.5">
                                            <p class="font-extrabold text-slate-900 leading-tight"><?php echo htmlspecialchars($name); ?></p>
                                            <p class="text-[9px] text-slate-500 uppercase tracking-wider font-black">ID Log Record</p>
                                        </div>
                                    </div>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap">
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-md text-[10px] font-black text-white shadow-xs" style="background-color: <?php echo $data['shift_color'] ?? '#3730a3'; ?>;">
                                        <span class="w-1.5 h-1.5 rounded-full bg-white opacity-90"></span>
                                        <?php echo htmlspecialchars($data['shift_name'] ?? 'No Shift'); ?>
                                    </span>
                                </td>

                                <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                    <?php echo $shift['check_in'] ?? "—"; ?>
                                </td>

                                <td class="p-3 text-center font-mono text-[10px] text-slate-700 whitespace-nowrap">
                                    <?php echo $shift['check_out'] ?? "—"; ?>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap">
                                    <span class="bg-emerald-50 text-emerald-800 border border-emerald-200 px-2 py-0.5 rounded font-black text-[10px] font-mono">
                                        <?php echo $shift['hours'] ?? 0; ?> hrs
                                    </span>
                                </td>

                                <td class="p-3 text-center whitespace-nowrap">
                                    <?php if (!empty($shift['worked_ph'])): ?>
                                        <span class="bg-purple-100 text-purple-900 border border-purple-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Worked on PH</span>
                                    <?php elseif (!empty($shift['late'])): ?>
                                        <span class="bg-amber-50 text-amber-900 border border-amber-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Late Arrival</span>
                                    <?php elseif (!empty($shift['early'])): ?>
                                        <span class="bg-orange-50 text-orange-900 border border-orange-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Early Leave</span>
                                    <?php elseif (!empty($shift['check_in']) && !empty($shift['check_out'])): ?>
                                        <span class="bg-emerald-50 text-emerald-800 border border-emerald-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Present</span>
                                    <?php elseif (!empty($shift['leave_pending'])): ?>
                                        <span class="bg-amber-50 text-amber-800 border border-amber-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Leave Pending</span>
                                    <?php elseif (!empty($shift['leave'])): ?>
                                        <span class="bg-indigo-50 text-indigo-900 border border-indigo-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center max-w-[120px] truncate"><?= htmlspecialchars($shift['leave']) ?></span>
                                    <?php elseif (!empty($shift['holiday'])): ?>
                                        <span class="bg-purple-50 text-purple-900 border border-purple-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center"><?= htmlspecialchars(!empty($shift['holiday_name']) ? $shift['holiday_name'] : 'Public Holiday') ?></span>
                                    <?php elseif (!empty($shift['off_day'])): ?>
                                        <span class="bg-stone-100 text-slate-700 border border-slate-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Day Off</span>
                                    <?php elseif (!empty($shift['not_resumed'])): ?>
                                        <span class="bg-indigo-50 text-indigo-850 border border-indigo-200 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center animate-pulse">Not Resumed</span>
                                    <?php elseif (!empty($shift['absent'])): ?>
                                        <span class="bg-rose-50 text-rose-900 border border-rose-300 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Absent</span>
                                    <?php else: ?>
                                        <span class="bg-stone-100 text-slate-700 px-2 py-1 rounded-md font-black text-[10px] inline-block min-w-[85px] text-center">Incomplete</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                </div>
            </main>

            <footer class="mt-auto border-t border-slate-300 bg-white px-6 py-4 text-center">
                <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>

    <!-- EMAIL DISPATCH MODAL -->
    <div id="emailModal" class="fixed inset-0 bg-slate-900/50 backdrop-blur-xs hidden z-50 flex items-center justify-center p-4">
        <div class="bg-white border border-slate-300 rounded-xl shadow-xl max-w-md w-full p-5 space-y-4">
            <div class="flex items-center justify-between border-b border-slate-200 pb-3">
                <div class="flex items-center gap-2">
                    <span class="text-base">📩</span>
                    <h3 class="text-xs font-black uppercase text-slate-900 tracking-tight">Send Attendance Report</h3>
                </div>
                <button onclick="closeEmailModal()" class="text-slate-400 hover:text-slate-600 font-black text-sm">✕</button>
            </div>
            
            <form method="post" action="send_attendance_report.php" class="space-y-4">
                <input type="hidden" name="date" value="<?= htmlspecialchars($selectedDate ?? '') ?>">
                <input type="hidden" name="search" value="<?= htmlspecialchars($search ?? '') ?>">
                
                <div class="space-y-1">
                    <label class="text-[10px] font-black uppercase tracking-wider text-slate-600">Recipient Email Address</label>
                    <input type="email" name="recipient_email" required placeholder="manager@company.com" class="w-full border border-slate-300 bg-stone-50 rounded-lg px-3 py-2 text-xs font-bold text-slate-800 outline-none focus:ring-2 focus:ring-indigo-500">
                    <p class="text-[9px] font-semibold text-slate-500 mt-1">The active filter state (Date: <?= htmlspecialchars($selectedDate) ?>) will be dispatched as an HTML report.</p>
                </div>

                <div class="flex items-center justify-end gap-2 pt-2">
                    <button type="button" onclick="closeEmailModal()" class="px-3 py-1.5 rounded-lg border border-slate-300 text-xs font-bold text-slate-700 hover:bg-slate-100 transition">Cancel</button>
                    <button type="submit" class="px-4 py-1.5 rounded-lg bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-bold shadow-xs transition">Dispatch Email</button>
                </div>
            </form>
        </div>
    </div>

    <script src="components/sidebar.js"></script>
    <script>
    function openEmailModal() {
        document.getElementById('emailModal').classList.remove('hidden');
    }

    function closeEmailModal() {
        document.getElementById('emailModal').classList.add('hidden');
    }

    document.getElementById('import-form').addEventListener('submit', function() {
        const btn = document.getElementById('import-btn');
        if(btn) btn.disabled = true;

        const overlay = document.getElementById('loadingOverlay');
        if(overlay) {
            overlay.classList.remove('hidden');
        }

        const progressBar = document.getElementById('progressBar');
        const progressText = document.getElementById('loadingText');
        const progressPercent = document.getElementById('progressPercent');

        let percent = 0;
        const messages = [
            'Reading CSV file...',
            'Cleaning attendance data...',
            'Filtering blocked records...',
            'Matching employees...',
            'Checking duplicates...',
            'Saving attendance logs...',
            'Synchronizing database...',
            'Finalizing import...'
        ];
        let msgIndex = 0;

        const interval = setInterval(() => {
            percent += Math.floor(Math.random() * 7) + 2;
            if (percent >= 95) {
                percent = 95;
                clearInterval(interval);
            }

            if(progressBar) progressBar.style.width = percent + '%';
            if(progressPercent) progressPercent.innerText = percent + '%';
            if(progressText) progressText.innerText = messages[msgIndex % messages.length];
            
            msgIndex++;
        }, 700);
    });
    </script>

    <?php include 'loader_overlay.php'; ?>
</body>
</html>