<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$request_id = $_GET['id'] ?? '';
$status = $_GET['status'] ?? '';

if (empty($request_id) || empty($status)) {
    header('Location: list_maintenance.php');
    exit();
}

// Validate status
$allowed_statuses = ['Open', 'Assigned', 'In Progress', 'Completed', 'Cancelled'];
if (!in_array($status, $allowed_statuses)) {
    $_SESSION['error_message'] = "Invalid status";
    header('Location: list_maintenance.php');
    exit();
}

// Update status
$sql = "UPDATE maintenance_requests SET status = ?";
$params = [$status];
$types = 's';

// If completing, set completed date
if ($status == 'Completed') {
    $sql .= ", completed_date = NOW()";
}

$sql .= " WHERE request_id = ?";
$params[] = $request_id;
$types .= 'i';

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);

if ($stmt->execute()) {
    $_SESSION['success_message'] = "Status updated successfully!";
} else {
    $_SESSION['error_message'] = "Error updating status: " . $conn->error;
}

header('Location: ' . ($_SERVER['HTTP_REFERER'] ?? 'list_maintenance.php'));
exit();
?>
