<?php
session_start();
require '../config.php';

$id = intval($_GET['id']);
$action = $_GET['action'];
$user_id = $_SESSION['user_id'];

if ($action === 'manager_approve') {

    db_query($conn,
        "UPDATE leave_request
         SET manager_status='Approved',
             manager_action_on=NOW(),
             hr_status='Pending'
         WHERE id=?",
        [$id]
    );
}

if ($action === 'manager_reject') {

    db_query($conn,
        "UPDATE leave_request
         SET manager_status='Rejected',
             status='Rejected',
             manager_action_on=NOW()
         WHERE id=?",
        [$id]
    );
}

if ($action === 'hr_approve') {

    $leave = db_query($conn,
        "SELECT * FROM leave_request WHERE id=?",
        [$id]
    )->fetch_assoc();

    $days = (strtotime($leave['end_date']) - strtotime($leave['start_date'])) / 86400 + 1;

    db_query($conn,
        "UPDATE leave_balance
         SET balance = balance - ?
         WHERE user_id=? AND leave_type=?",
        [$days, $leave['employee_id'], $leave['leave_type']]
    );

    db_query($conn,
        "UPDATE leave_request
         SET hr_status='Approved',
             status='Approved',
             approved_by=?,
             approved_on=NOW()
         WHERE id=?",
        [$user_id, $id]
    );
}

if ($action === 'hr_reject') {

    db_query($conn,
        "UPDATE leave_request
         SET hr_status='Rejected',
             status='Rejected'
         WHERE id=?",
        [$id]
    );
}

header("Location: ".$_SERVER['HTTP_REFERER']);
exit;
