<?php
session_start();
include 'config.php';

if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'Admin' && $_SESSION['role'] != 'Super Admin')) {
    header("Location: index.php");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $employee_id = $_POST['employee_id'];
    $date = $_POST['date'];
    $attendance = $_POST['attendance'];
    $leave_type = $_POST['leave_type']; // Capturing leave type
    
    // Insert attendance record
    $stmt = $conn->prepare("INSERT INTO attendance (employee_id, date, status, leave_type) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("isss", $employee_id, $date, $attendance, $leave_type);
    $stmt->execute();
    $stmt->close();

    // Reduce leave balance if leave is applied
    if ($attendance == 'Absent' && $leave_type != 'None') {
        $leave_column = "";
        
        // Map leave type to the correct column in database
        if ($leave_type == "Casual Leave") {
            $leave_column = "casual_leave";
        } elseif ($leave_type == "Medical Leave") {
            $leave_column = "medical_leave";
        } elseif ($leave_type == "Sick Leave") {
            $leave_column = "sick_leave";
        }

        if ($leave_column != "") {
            $update_leave = $conn->prepare("UPDATE leave_balance SET $leave_column = $leave_column - 1 WHERE employee_id = ?");
            $update_leave->bind_param("i", $employee_id);
            $update_leave->execute();
            $update_leave->close();
        }
    }

    header("Location: attendance.php");
    exit();
}
?>
