<?php
session_start();
require_once "config.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function sanitizeInput($input) {
    return htmlspecialchars(strip_tags(trim($input)));
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $employee_id = sanitizeInput($_POST['employee_id']);
    $attDate = sanitizeInput($_POST['date']);
    $check_in = sanitizeInput($_POST['check_in']);
    $check_out = sanitizeInput($_POST['check_out']);
    $status = sanitizeInput($_POST['status']);   

    if (isset($_GET['action'])) {
        $action = $_GET['action'];

        if ($action == 'add') {
            $sql = "INSERT INTO attendance (employee_id, date, check_in, check_out, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "sssss", $employee_id, $attDate, $check_in, $check_out, $status);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    $_SESSION['success_message'] = "Attendance added successfully.";
                    header("location: attendance.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        } elseif ($action == 'edit') {
            $att_id = sanitizeInput($_POST['att_id']);
            $sql = "UPDATE attendance SET employee_id=?, date=?, check_in=?, check_out=?, status=?, updated_at=NOW() WHERE id=?";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "sssssi", $employee_id, $attDate, $check_in, $check_out, $status, $att_id);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    $_SESSION['success_message'] = "Attendance updated successfully.";
                    header("location: attendance.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        } elseif ($action == 'delete') {
            $att_id = sanitizeInput($_POST['delete_id']);
            $sql = "DELETE FROM attendance WHERE id=?";
            if ($stmt = mysqli_prepare($conn, $sql)) {
                mysqli_stmt_bind_param($stmt, "i", $att_id);
                if (mysqli_stmt_execute($stmt)) {
                    mysqli_stmt_close($stmt);
                    mysqli_close($conn);
                    header("Location: attendance.php");
                    exit();
                } else {
                    echo "Error: " . mysqli_error($conn);
                }
            }
        }
    }
}


?>