<?php
// attendance.php
session_start();
require_once '../config/config.php';

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

// Current date & month
$current_date = $_GET['date'] ?? date('Y-m-d');
$selected_month = $_GET['month'] ?? date('Y-m');

// Bulk Save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_bulk'])) {
    $attendance_date = $_POST['attendance_date'];
    $count = 0;

    $stmt_check = $conn->prepare("SELECT id FROM attendance WHERE employee_id = ? AND attendance_date = ?");
    $stmt_insert = $conn->prepare("INSERT INTO attendance (attendance_date, employee_id, status, remarks, created_by) VALUES (?, ?, ?, ?, ?)");
    $stmt_update = $conn->prepare("UPDATE attendance SET status = ?, remarks = ?, updated_at = NOW() WHERE employee_id = ? AND attendance_date = ?");

    foreach ($_POST['status'] as $emp_id => $status) {
        $remarks = trim($_POST['remarks'][$emp_id] ?? '');
        $status = trim($status);

        // Check if exists
        $stmt_check->bind_param("is", $emp_id, $attendance_date);
        $stmt_check->execute();
        $exists = $stmt_check->get_result()->num_rows > 0;

        if ($exists) {
            $stmt_update->bind_param("ssis", $status, $remarks, $emp_id, $attendance_date);
            $stmt_update->execute();
        } else {
            $stmt_insert->bind_param("sissi", $attendance_date, $emp_id, $status, $remarks, $_SESSION['user_id']);
            $stmt_insert->execute();
        }
        $count++;
    }

    $_SESSION['success'] = "Attendance saved for $count employees!";
    header("Location: attendance.php?date=$attendance_date");
    exit;
}

// Fetch active employees (you can join with deployments if needed)
$employees = [];
$result = $conn->query("SELECT id, employee_id, full_name, designation FROM employee_master WHERE status = 'active' ORDER BY full_name");
while ($row = $result->fetch_assoc()) {
    $employees[] = $row;
}

// Load today's attendance
$today_att = [];
$att_res = $conn->query("SELECT employee_id, status, remarks FROM attendance WHERE attendance_date = '$current_date'");
while ($row = $att_res->fetch_assoc()) {
    $today_att[$row['employee_id']] = $row;
}

// Monthly summary
$month_start = date('Y-m-01', strtotime($selected_month));
$month_end = date('Y-m-t', strtotime($selected_month));

$summary = [];
$sum_sql = "SELECT 
    e.id, e.employee_id, e.full_name,
    COUNT(a.id) as total_days,
    SUM(CASE WHEN a.status = 'Present' THEN 1 ELSE 0 END) as present,
    SUM(CASE WHEN a.status = 'Absent' THEN 1 ELSE 0 END) as absent,
    SUM(CASE WHEN a.status IN ('Holiday','Weekly Off') THEN 1 ELSE 0 END) as off_days
    FROM employee_master e
    LEFT JOIN attendance a ON e.id = a.employee_id AND a.attendance_date BETWEEN '$month_start' AND '$month_end'
    WHERE e.status = 'active'
    GROUP BY e.id ORDER BY e.full_name";

$sum_result = $conn->query($sum_sql);
while ($row = $sum_result->fetch_assoc()) {
    $summary[] = $row;
}
?>

<!DOCTYPE html>
<html lang="en" class="scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Attendance Management</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <style>
        .glass { background: rgba(255, 255, 255, 0.15); backdrop-filter: blur(12px); border: 1px solid rgba(255, 255, 255, 0.2); }
        .tab-btn { @apply px-6 py-3 rounded-xl font-medium transition-all; }
        .tab-btn.active { @apply bg-emerald-600 text-white shadow-lg; }
        .status-badge { @apply px-3 py-1 rounded-full text-xs font-medium; }
        .status-present { @apply bg-emerald-500/20 text-emerald-300 border border-emerald-500/30; }
        .status-absent { @apply bg-red-500/20 text-red-300 border border-red-500/30; }
        .status-half { @apply bg-amber-500/20 text-amber-300 border border-amber-500/30; }
        .status-off { @apply bg-blue-500/20 text-blue-300 border border-blue-500/30; }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-900 via-blue-900 to-slate-900 text-white min-h-screen">
    <?php include('../header.php'); ?>

    <div class="container mx-auto px-4 py-8 max-w-7xl">
        <div class="flex justify-between items-center mb-8">
            <div>
                <h1 class="text-3xl font-bold flex items-center gap-3">
                    <i class="fas fa-calendar-check text-emerald-400"></i> Attendance Management
                </h1>
                <p class="text-blue-200 mt-1">Mark daily attendance & view monthly reports</p>
            </div>
            <a href="manual_attendance.php" class="px-5 py-3 bg-emerald-600 rounded-xl hover:bg-emerald-700 font-medium flex items-center gap-2">
                <i class="fas fa-user-plus"></i> Manual Entry
            </a>
        </div>

        <!-- Alerts -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="glass rounded-xl p-4 mb-6 flex items-center gap-2 text-emerald-300">
                <i class="fas fa-check-circle"></i> <?= $_SESSION['success'] ?> <?php unset($_SESSION['success']); ?>
            </div>
        <?php endif; ?>

        <!-- Tabs -->
        <div class="glass rounded-xl p-2 mb-6 flex gap-2 overflow-x-auto">
            <button onclick="showTab('daily')" class="tab-btn active" id="daily-tab">Daily Attendance</button>
            <button onclick="showTab('monthly')" class="tab-btn" id="monthly-tab">Monthly Report</button>
        </div>

        <!-- Daily Tab -->
        <div id="daily" class="tab-content">
            <div class="glass rounded-xl p-6 mb-6 flex flex-col md:flex-row justify-between items-center">
                <h3 class="text-xl font-bold"><?= date('l, F j, Y', strtotime($current_date)) ?></h3>
                <div class="flex gap-3 mt-4 md:mt-0">
                    <a href="?date=<?= date('Y-m-d', strtotime($current_date . ' -1 day')) ?>" class="px-4 py-2 bg-white/10 rounded-lg hover:bg-white/20">← Prev</a>
                    <a href="?date=<?= date('Y-m-d') ?>" class="px-4 py-2 bg-emerald-600 rounded-lg hover:bg-emerald-700">Today</a>
                    <a href="?date=<?= date('Y-m-d', strtotime($current_date . ' +1 day')) ?>" class="px-4 py-2 bg-white/10 rounded-lg hover:bg-white/20">Next →</a>
                </div>
            </div>

            <form method="post">
                <input type="hidden" name="attendance_date" value="<?= $current_date ?>">
                <div class="glass rounded-2xl overflow-hidden">
                    <div class="p-5 border-b border-white/10 flex justify-between items-center">
                        <h3 class="text-lg font-bold">Mark Attendance</h3>
                        <button type="submit" name="save_bulk" class="px-6 py-3 bg-emerald-600 hover:bg-emerald-700 rounded-xl font-medium">
                            <i class="fas fa-save"></i> Save All
                        </button>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead class="bg-white/5">
                                <tr>
                                    <th class="px-6 py-4 text-left">Employee</th>
                                    <th class="px-6 py-4 text-left">Designation</th>
                                    <th class="px-6 py-4 text-left">Status</th>
                                    <th class="px-6 py-4 text-left">Remarks</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-white/10">
                                <?php foreach ($employees as $emp): 
                                    $att = $today_att[$emp['id']] ?? null;
                                ?>
                                <tr class="hover:bg-white/5">
                                    <td class="px-6 py-4">
                                        <div class="font-medium"><?= htmlspecialchars($emp['full_name']) ?></div>
                                        <div class="text-sm text-blue-300"><?= $emp['employee_id'] ?></div>
                                    </td>
                                    <td class="px-6 py-4 text-sm"><?= htmlspecialchars($emp['designation']) ?></td>
                                    <td class="px-6 py-4">
                                        <select name="status[<?= $emp['id'] ?>]" class="px-4 py-2 rounded-lg bg-white/10 border border-white/20 focus:ring-2 focus:ring-emerald-500">
                                            <?php foreach(['Present','Absent','Half-day','Holiday','Weekly Off'] as $opt): ?>
                                                <option value="<?= $opt ?>" <?= ($att['status'] ?? '') === $opt ? 'selected' : '' ?>><?= $opt ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td class="px-6 py-4">
                                        <input type="text" name="remarks[<?= $emp['id'] ?>]" value="<?= htmlspecialchars($att['remarks'] ?? '') ?>"
                                               class="w-full px-4 py-2 rounded-lg bg-white/10 border border-white/20 focus:ring-2 focus:ring-emerald-500" placeholder="Optional">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </form>
        </div>

        <!-- Monthly Tab -->
        <div id="monthly" class="tab-content hidden">
            <div class="glass rounded-xl p-6 mb-6">
                <form method="get" class="flex items-center gap-4">
                    <input type="month" name="month" value="<?= $selected_month ?>" class="px-4 py-3 rounded-xl bg-white/10 border border-white/20">
                    <button type="submit" class="px-6 py-3 bg-emerald-600 rounded-xl hover:bg-emerald-700">Go</button>
                </form>
            </div>

            <div class="glass rounded-2xl overflow-hidden">
                <div class="p-5 border-b border-white/10">
                    <h3 class="text-xl font-bold">Monthly Summary - <?= date('F Y', strtotime($selected_month)) ?></h3>
                </div>
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-white/5">
                            <tr>
                                <th class="px-6 py-4 text-left">Employee</th>
                                <th class="px-6 py-4 text-center">Total</th>
                                <th class="px-6 py-4 text-center">Present</th>
                                <th class="px-6 py-4 text-center">Absent</th>
                                <th class="px-6 py-4 text-center">Off</th>
                                <th class="px-6 py-4 text-center">Attendance %</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-white/10">
                            <?php foreach ($summary as $s): 
                                $pct = $s['total_days'] > 0 ? round(($s['present'] / $s['total_days']) * 100, 1) : 0;
                            ?>
                            <tr class="hover:bg-white/5">
                                <td class="px-6 py-4">
                                    <div class="font-medium"><?= htmlspecialchars($s['full_name']) ?></div>
                                    <div class="text-sm text-blue-300"><?= $s['employee_id'] ?></div>
                                </td>
                                <td class="px-6 py-4 text-center"><?= $s['total_days'] ?></td>
                                <td class="px-6 py-4 text-center"><span class="status-badge status-present"><?= $s['present'] ?></span></td>
                                <td class="px-6 py-4 text-center"><span class="status-badge status-absent"><?= $s['absent'] ?></span></td>
                                <td class="px-6 py-4 text-center"><span class="status-badge status-off"><?= $s['off_days'] ?></span></td>
                                <td class="px-6 py-4 text-center font-bold <?= $pct >= 90 ? 'text-emerald-400' : ($pct >= 75 ? 'text-amber-400' : 'text-red-400') ?>">
                                    <?= $pct ?>%
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script>
        function showTab(tab) {
            document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
            document.getElementById(tab).classList.remove('hidden');
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.getElementById(tab + '-tab').classList.add('active');
        }
    </script>
</body>
</html>