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

// Only admin / superadmin can approve
if (!isset($_SESSION['user_id'])) {
    $_SESSION['error'] = "Please log in.";
    header("Location: index.php");
    exit();
}

$admin_id = (int)$_SESSION['user_id'];

// Check role
$role_sql = "SELECT role FROM users WHERE id = ?";
$stmt = $conn->prepare($role_sql);
$stmt->bind_param("i", $admin_id);
$stmt->execute();
$res = $stmt->get_result();
if ($res->num_rows === 0) {
    $_SESSION['error'] = "Invalid user.";
    header("Location: index.php");
    exit();
}
$row_role = $res->fetch_assoc();
$user_role = strtolower(trim($row_role['role']));
$stmt->close();

if ($user_role !== 'admin' && $user_role !== 'superadmin') {
    $_SESSION['error'] = "You are not authorized to approve leaves.";
    header("Location: leave_dashboard.php");
    exit();
}

// Read request params
$leave_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$status   = isset($_GET['status']) ? $_GET['status'] : '';

if ($leave_id <= 0 || !in_array($status, ['Approved', 'Rejected'])) {
    $_SESSION['error'] = "Invalid request.";
    header("Location: leave_dashboard.php");
    exit();
}

// Fetch leave details
$sql = "SELECT * FROM leave_requests WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $leave_id);
$stmt->execute();
$leave_res = $stmt->get_result();
if ($leave_res->num_rows === 0) {
    $_SESSION['error'] = "Leave request not found.";
    header("Location: leave_dashboard.php");
    exit();
}
$leave = $leave_res->fetch_assoc();
$stmt->close();

if ($leave['status'] !== 'Pending') {
    $_SESSION['error'] = "This leave request is already processed.";
    header("Location: leave_dashboard.php");
    exit();
}

// Update status
$update_sql = "UPDATE leave_requests SET status = ?, approved_by = ?, approved_on = NOW() WHERE id = ?";
$stmt = $conn->prepare($update_sql);
$stmt->bind_param("sii", $status, $admin_id, $leave_id);

if (!$stmt->execute()) {
    $_SESSION['error'] = "Error updating leave status: " . $stmt->error;
    $stmt->close();
    header("Location: leave_dashboard.php");
    exit();
}
$stmt->close();

// If approved and leave type is PL / SL -> deduct balance from leave_balance
if ($status === 'Approved' && in_array($leave['leave_type'], ['PL', 'SL'])) {

    $employee_id = (int)$leave['employee_id'];
    $leave_type  = $leave['leave_type'];
    $start_date  = $leave['start_date'];
    $end_date    = $leave['end_date'];

    // Calculate number of days (inclusive)
    $start = new DateTime($start_date);
    $end   = new DateTime($end_date);
    $days  = $start->diff($end)->days + 1;

    $conn->begin_transaction();
    try {
        // Fetch current balance row for that user & leave_type
        $userIdStr = (string)$employee_id;
        $sql_lb = "SELECT id, balance FROM leave_balance WHERE user_id = ? AND leave_type = ? FOR UPDATE";
        $stmt = $conn->prepare($sql_lb);
        $stmt->bind_param("ss", $userIdStr, $leave_type);
        $stmt->execute();
        $res_lb = $stmt->get_result();
        $row_lb = $res_lb->fetch_assoc();
        $stmt->close();

        if ($row_lb) {
            $currentBalance = (int)$row_lb['balance'];
            $newBalance = $currentBalance - $days;
            if ($newBalance < 0) {
                $newBalance = 0; // don't go negative
            }

            $up = $conn->prepare("UPDATE leave_balance SET balance = ? WHERE id = ?");
            $up->bind_param("ii", $newBalance, $row_lb['id']);
            $up->execute();
            $up->close();
        } else {
            // If no row exists, we can either create with 0 or create with (0 - days) capped to 0
            $newBalance = 0;
            $ins = $conn->prepare("INSERT INTO leave_balance (user_id, leave_type, balance) VALUES (?, ?, ?)");
            $ins->bind_param("ssi", $userIdStr, $leave_type, $newBalance);
            $ins->execute();
            $ins->close();
        }

        $conn->commit();
    } catch (Exception $e) {
        $conn->rollback();
        $_SESSION['error'] = "Leave approved but error updating balance: " . $e->getMessage();
        header("Location: leave_dashboard.php");
        exit();
    }
}

$_SESSION['message'] = "Leave request " . strtolower($status) . " successfully.";
header("Location: leave_dashboard.php");
exit();
