<?php
session_start();
require_once __DIR__ . "/../config/db.php";

header('Content-Type: application/json');

// Check login & role
if(!isset($_SESSION['user_id']) || $_SESSION['role'] != 'hod'){
    echo json_encode(['status'=>'error','message'=>'Unauthorized']);
    exit;
}

// Validate POST
$id = intval($_POST['id'] ?? 0);
$action = $_POST['action'] ?? '';
if($id <= 0 || !in_array($action,['approve','reject'])){
    echo json_encode(['status'=>'error','message'=>'Invalid request']);
    exit;
}

// Determine new status
$status = $action == 'approve' ? 'Approved' : 'Rejected';

// Update DB
$stmt = mysqli_prepare($conn, "UPDATE maintenance_request SET status=? WHERE id=?");
mysqli_stmt_bind_param($stmt, "si", $status, $id);
if(mysqli_stmt_execute($stmt)){
    echo json_encode(['status'=>'success']);
}else{
    echo json_encode(['status'=>'error','message'=>'Database error']);
}
?>