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

// Check if user is logged in and has admin privileges
if (!isset($_SESSION['username']) || ($_SESSION['role'] != 'Admin' && $_SESSION['role'] != 'superadmin')) {
    header("Location: index.php");
    exit();
}

// Handle the attendance update
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data
    $employee_id = $_POST['employee_id'];
    $original_date = $_POST['original_date'];
    $date = $_POST['date'];
    $status = $_POST['attendance'];
    $leave_type = isset($_POST['leave_type']) ? $_POST['leave_type'] : 'None';
    
    // Validate inputs
    if (empty($employee_id) || empty($date) || empty($status)) {
        $_SESSION['error'] = "Required fields are missing";
        header("Location: attendance.php");
        exit();
    }
    
    try {
        // Begin transaction
        $conn->begin_transaction();
        
        // 1. Get the original record to check if we need to adjust leave balances
        $original_query = $conn->prepare("SELECT status, leave_type FROM attendance WHERE employee_id = ? AND date = ?");
        $original_query->bind_param("is", $employee_id, $original_date);
        $original_query->execute();
        $original_result = $original_query->get_result();
        $original_data = $original_result->fetch_assoc();
        
        // 2. Delete the original record if date has changed
        if ($original_date != $date) {
            $delete_query = $conn->prepare("DELETE FROM attendance WHERE employee_id = ? AND date = ?");
            $delete_query->bind_param("is", $employee_id, $original_date);
            $delete_query->execute();
        }
        
        // 3. Check if a record already exists for the new date (if date changed)
        $check_query = $conn->prepare("SELECT id FROM attendance WHERE employee_id = ? AND date = ?");
        $check_query->bind_param("is", $employee_id, $date);
        $check_query->execute();
        $check_result = $check_query->get_result();
        
        if ($check_result->num_rows > 0) {
            // Update existing record
            $update_query = $conn->prepare("UPDATE attendance SET status = ?, leave_type = ? WHERE employee_id = ? AND date = ?");
            $update_query->bind_param("ssis", $status, $leave_type, $employee_id, $date);
            $update_query->execute();
        } else {
            // Insert new record
            $insert_query = $conn->prepare("INSERT INTO attendance (employee_id, date, status, leave_type) VALUES (?, ?, ?, ?)");
            $insert_query->bind_param("isss", $employee_id, $date, $status, $leave_type);
            $insert_query->execute();
        }
        
        // 4. Handle leave balance adjustments
        
        // If original record was absent with leave, we need to restore the leave
        if ($original_data && $original_data['status'] == 'Absent' && $original_data['leave_type'] != 'None') {
            $leave_field = getLeaveField($original_data['leave_type']);
            if ($leave_field) {
                $restore_leave = $conn->prepare("UPDATE leave_balance SET $leave_field = $leave_field + 1 WHERE employee_id = ?");
                $restore_leave->bind_param("i", $employee_id);
                $restore_leave->execute();
            }
        }
        
        // If new record is absent with leave, we need to deduct the leave
        if ($status == 'Absent' && $leave_type != 'None') {
            $leave_field = getLeaveField($leave_type);
            if ($leave_field) {
                // First check if record exists
                $balance_check = $conn->prepare("SELECT $leave_field FROM leave_balance WHERE employee_id = ?");
                $balance_check->bind_param("i", $employee_id);
                $balance_check->execute();
                $balance_result = $balance_check->get_result();
                
                if ($balance_result->num_rows > 0) {
                    // Update existing balance
                    $update_balance = $conn->prepare("UPDATE leave_balance SET $leave_field = $leave_field - 1 WHERE employee_id = ? AND $leave_field > 0");
                    $update_balance->bind_param("i", $employee_id);
                    $update_balance->execute();
                } else {
                    // Insert new balance record with default values minus 1
                    $default_values = [
                        'casual_leave' => 11, // Default 12 minus 1
                        'medical_leave' => 4,  // Default 5 minus 1
                        'sick_leave' => 6      // Default 7 minus 1
                    ];
                    
                    $insert_balance = $conn->prepare("INSERT INTO leave_balance (employee_id, casual_leave, medical_leave, sick_leave) VALUES (?, ?, ?, ?)");
                    $insert_balance->bind_param("iiii", $employee_id, $default_values['casual_leave'], $default_values['medical_leave'], $default_values['sick_leave']);
                    $insert_balance->execute();
                }
            }
        }
        
        // Commit transaction
        $conn->commit();
        
        $_SESSION['success'] = "Attendance record updated successfully";
        header("Location: attendance.php?month=" . date('Y-m', strtotime($date)));
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction on error
        $conn->rollback();
        $_SESSION['error'] = "Error updating attendance: " . $e->getMessage();
        header("Location: attendance.php");
        exit();
    }
} else {
    // Not a POST request
    header("Location: attendance.php");
    exit();
}

// Helper function to get database field name for leave type
function getLeaveField($leave_type) {
    switch ($leave_type) {
        case 'Casual Leave': return 'casual_leave';
        case 'Medical Leave': return 'medical_leave';
        case 'Sick Leave': return 'sick_leave';
        default: return null;
    }
}
?>