<?php
// attendance_daily.php
session_start();
require_once("../config/config.php");

if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$success = $error = "";
$selected_date = $_POST['attendance_date'] ?? ($_GET['date'] ?? date('Y-m-d'));

// Fetch all active employees
$employees = $conn->query("SELECT id, employee_id, full_name, designation FROM employee_master WHERE status = 'active' ORDER BY employee_id");

// Load existing attendance for selected date
$existing = [];
$att_res = $conn->query("SELECT employee_id, status, in_time, out_time, overtime_hours, notes 
                         FROM attendance WHERE attendance_date = '$selected_date'");
while ($row = $att_res->fetch_assoc()) {
    $existing[$row['employee_id']] = $row;
}

// Handle Save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_attendance'])) {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        $error = "Invalid request.";
    } else {
        $attendance_date = $_POST['attendance_date'];
        $stmt = $conn->prepare("INSERT INTO attendance 
            (employee_id, attendance_date, status, in_time, out_time, overtime_hours, notes)
            VALUES (?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
            status=VALUES(status), in_time=VALUES(in_time), out_time=VALUES(out_time),
            overtime_hours=VALUES(overtime_hours), notes=VALUES(notes)");

        $count = 0;
        foreach ($_POST['status'] as $emp_id => $status) {
            $in = !empty($_POST['in_time'][$emp_id]) ? $_POST['in_time'][$emp_id] : null;
            $out = !empty($_POST['out_time'][$emp_id]) ? $_POST['out_time'][$emp_id] : null;
            $ot = (float)($_POST['overtime'][$emp_id] ?? 0);
            $notes = trim($_POST['notes'][$emp_id] ?? '');

            $stmt->bind_param("issssds", $emp_id, $attendance_date, $status, $in, $out, $ot, $notes);
            if ($stmt->execute()) $count++;
        }
        $stmt->close();
        $success = "Attendance successfully saved for $count employees on " . date('d M Y', strtotime($attendance_date));
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Daily Attendance</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --primary: #8b5cf6; --primary-light: #a78bfa; --text: #e0e7ff; --success: #34d399; --error: #f87171; }
        * { margin:0; padding:0; box-sizing:border-box; }
        body { font-family:'Segoe UI',sans-serif; min-height:100vh; background:linear-gradient(rgba(0,0,0,0.6),rgba(0,0,0,0.6)),url('../background.jpeg') center/cover no-repeat fixed; color:var(--text); padding:20px; }
        .container { max-width:1400px; margin:0 auto; background:rgba(255,255,255,0.1); backdrop-filter:blur(16px); border-radius:24px; border:1px solid rgba(255,255,255,0.2); box-shadow:0 20px 50px rgba(0,0,0,0.4); overflow:hidden; }
        .header { background:rgba(255,255,255,0.15); padding:40px; text-align:center; position:relative; }
        .header h1 { font-size:2.5rem; margin-bottom:10px; }
        .back-btn { position:absolute; top:30px; left:40px; padding:12px 20px; background:rgba(139,92,246,0.3); border:1px solid var(--primary-light); border-radius:14px; color:white; text-decoration:none; font-weight:600; transition:.3s; }
        .back-btn:hover { background:rgba(139,92,246,0.5); }
        .form-area { padding:40px; }
        .message { padding:16px 20px; border-radius:14px; margin-bottom:30px; display:flex; align-items:center; gap:12px; font-weight:600; backdrop-filter:blur(8px); }
        .success { background:rgba(52,211,153,0.2); border:1px solid rgba(74,222,128,0.4); }
        .error { background:rgba(239,68,68,0.2); border:1px solid rgba(252,165,165,0.4); }
        .section-title { font-size:1.8rem; margin:40px 0 25px; padding-bottom:12px; border-bottom:1px solid rgba(255,255,255,0.3); }
        .form-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(320px,1fr)); gap:24px; margin-bottom:30px; }
        label { display:block; margin-bottom:8px; font-weight:600; }
        input, select { width:100%; padding:16px 18px; background:rgba(255,255,255,0.15); border:1px solid rgba(255,255,255,0.3); border-radius:14px; color:white; font-size:16px; transition:all .3s; }
        input:focus, select:focus { outline:none; border-color:var(--primary-light); background:rgba(255,255,255,0.25); box-shadow:0 0 0 4px rgba(167,139,250,0.3); }
        .table-area { overflow-x:auto; margin-top:30px; }
        table { width:100%; border-collapse:collapse; }
        th, td { padding:18px; text-align:left; border-bottom:1px solid rgba(255,255,255,0.15); }
        th { background:rgba(139,92,246,0.3); font-weight:600; }
        tr:hover { background:rgba(255,255,255,0.08); }
        .submit-btn { width:100%; padding:18px; margin-top:40px; background:linear-gradient(135deg,var(--primary),var(--primary-light)); color:white; border:none; border-radius:14px; font-size:1.2rem; font-weight:700; cursor:pointer; box-shadow:0 10px 30px rgba(139,92,246,0.4); transition:.4s; }
        .submit-btn:hover { transform:translateY(-5px); box-shadow:0 20px 40px rgba(139,92,246,0.5); }
        .date-nav { display:flex; justify-content:center; gap:20px; margin:30px 0; }
        .date-nav a { padding:14px 24px; background:rgba(255,255,255,0.15); border-radius:14px; text-decoration:none; transition:.3s; }
        .date-nav a:hover { background:rgba(255,255,255,0.25); }
        .today-btn { background:var(--primary) !important; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <a href="employee-management.php" class="back-btn">
                <i class="fas fa-arrow-left"></i> Back
            </a>
            <h1>Daily Attendance</h1>
            <p>Mark attendance for all employees</p>
        </div>

        <div class="form-area">
            <?php if ($success): ?>
                <div class="message success"><i class="fas fa-check-circle"></i> <?= $success ?></div>
            <?php endif; ?>
            <?php if ($error): ?>
                <div class="message error"><i class="fas fa-exclamation-triangle"></i> <?= htmlspecialchars($error) ?></div>
            <?php endif; ?>

            <div class="date-nav">
                <a href="?date=<?= date('Y-m-d', strtotime($selected_date . ' -1 day')) ?>">← Previous</a>
                <a href="?date=<?= date('Y-m-d') ?>" class="<?= $selected_date == date('Y-m-d') ? 'today-btn' : '' ?>">Today</a>
                <a href="?date=<?= date('Y-m-d', strtotime($selected_date . ' +1 day')) ?>">Next →</a>
            </div>

            <h2 class="section-title">
                <i class="fas fa-calendar-day"></i> 
                <?= date('l, d F Y', strtotime($selected_date)) ?>
            </h2>

            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                <input type="hidden" name="attendance_date" value="<?= $selected_date ?>">

                <div class="table-area">
                    <table>
                        <thead>
                            <tr>
                                <th>Employee ID</th>
                                <th>Full Name</th>
                                <th>Designation</th>
                                <th>Status</th>
                                <th>In Time</th>
                                <th>Out Time</th>
                                <th>Overtime (hrs)</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($emp = $employees->fetch_assoc()):
                                $data = $existing[$emp['employee_id']] ?? null;
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars($emp['employee_id']) ?></strong></td>
                                <td><?= htmlspecialchars($emp['full_name']) ?></td>
                                <td><?= htmlspecialchars($emp['designation']) ?></td>
                                <td>
                                    <select name="status[<?= $emp['employee_id'] ?>]" required>
                                        <?php foreach(['Present', 'Absent', 'Half Day', 'Leave', 'Holiday'] as $opt): ?>
                                            <option value="<?= $opt ?>" <?= ($data['status'] ?? 'Present') === $opt ? 'selected' : '' ?>>
                                                <?= $opt ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </td>
                                <td><input type="time" name="in_time[<?= $emp['employee_id'] ?>]" value="<?= $data['in_time'] ?? '' ?>"></td>
                                <td><input type="time" name="out_time[<?= $emp['employee_id'] ?>]" value="<?= $data['out_time'] ?? '' ?>"></td>
                                <td><input type="number" step="0.25" min="0" name="overtime[<?= $emp['employee_id'] ?>]" value="<?= $data['overtime_hours'] ?? '0' ?>" style="width:100px;"></td>
                                <td><input type="text" name="notes[<?= $emp['employee_id'] ?>]" value="<?= htmlspecialchars($data['notes'] ?? '') ?>" placeholder="Optional"></td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>

                <button type="submit" name="save_attendance" class="submit-btn">
                    <i class="fas fa-save"></i> Save Attendance
                </button>
            </form>
        </div>
    </div>
</body>
</html>