<?php
ini_set('display_errors',1);
error_reporting(E_ALL & ~E_DEPRECATED);

session_start();
require 'config.php';

/* ================= AUTH CHECK ================= */
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'md') {
    header("Location:index.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location:md_leave_approval.php");
    exit;
}

$md_id    = $_SESSION['user_id'];
$leave_id = isset($_POST['leave_id']) ? (int)$_POST['leave_id'] : 0;
$action   = $_POST['action'] ?? '';
$comment  = trim($_POST['md_comment'] ?? '');

/* ================= VALIDATION ================= */
if ($leave_id <= 0 || empty($action) || empty($comment)) {
    header("Location:md_leave_approval.php?error=invalid_input");
    exit;
}

/* ================= VERIFY LEAVE BELONGS TO MD ================= */
$verify = $conn->prepare("
SELECT id 
FROM leave_requests
WHERE id = ?
AND md_id = ?
AND status = 'Pending'
");
$verify->bind_param("is", $leave_id, $md_id);
$verify->execute();
$verify->store_result();

if ($verify->num_rows === 0) {
    $verify->close();
    header("Location:md_leave_approval.php?error=unauthorized");
    exit;
}
$verify->close();

/* ================= DETERMINE STATUS ================= */
$final_status = ($action === 'approve') ? 'Approved' : 'Rejected';

/* ================= TRANSACTION START ================= */
$conn->begin_transaction();

try {

    $update = $conn->prepare("
    UPDATE leave_requests
    SET 
        status = ?,
        md_comment = ?,
        approved_by = ?,
        approved_on = NOW(),
        md_action_on = NOW()
    WHERE id = ?
    ");

    $update->bind_param(
        "sssi",
        $final_status,
        $comment,
        $md_id,
        $leave_id
    );

    $update->execute();
    $update->close();

    $conn->commit();

} catch (Exception $e) {
    $conn->rollback();
    header("Location:md_leave_approval.php?error=transaction_failed");
    exit;
}

/* ================= REDIRECT ================= */
header("Location:md_leave_approval.php?status=".$final_status);
exit;