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

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_SESSION['user_id']) || $_SESSION['role'] != 'hod') {
    header("Location: ../login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $request_id    = intval($_POST['request_id']);
    $technician_id = intval($_POST['technician_id']);

    if ($request_id <= 0 || $technician_id <= 0) {
        die("Invalid data.");
    }

    /* ===============================
       GET EQUIPMENT ID
    =================================*/
    $stmt = mysqli_prepare($conn, "
        SELECT equipment_id 
        FROM maintenance_request 
        WHERE id = ?
    ");
    mysqli_stmt_bind_param($stmt, "i", $request_id);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $data = mysqli_fetch_assoc($res);

    if (!$data) die("Request not found.");

    $equipment_id = $data['equipment_id'];

    /* ===============================
       START TRANSACTION (SAFE UPDATE)
    =================================*/
    mysqli_begin_transaction($conn);

    try {

        /* 1. UPDATE REQUEST STATUS */
        $update = mysqli_prepare($conn,
            "UPDATE maintenance_request 
             SET status = 'Approved' 
             WHERE id = ?"
        );
        mysqli_stmt_bind_param($update, "i", $request_id);
        mysqli_stmt_execute($update);

        /* 2. INSERT MAINTENANCE RECORD */
        $insert = mysqli_prepare($conn,
            "INSERT INTO maintenance_record 
            (equipment_id, request_id, technician_id, status) 
            VALUES (?, ?, ?, 'In Progress')"
        );
        mysqli_stmt_bind_param($insert, "iii",
            $equipment_id,
            $request_id,
            $technician_id
        );
        mysqli_stmt_execute($insert);

        /* 3. UPDATE EQUIPMENT STATUS (NEW) */
        $equip = mysqli_prepare($conn,
            "UPDATE equipment 
             SET status = 'Under Maintenance' 
             WHERE id = ?"
        );
        mysqli_stmt_bind_param($equip, "i", $equipment_id);
        mysqli_stmt_execute($equip);

        /* COMMIT ALL */
        mysqli_commit($conn);

        header("Location: maintenance_details.php?id=" . $request_id . "&success=1");
        exit();

    } catch (Exception $e) {

        mysqli_rollback($conn);
        die("Error: " . $e->getMessage());
    }
}