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

if (!isset($_GET['id']) || !isset($_GET['status'])) {
    header("Location: bbu_list.php?error=Invalid request");
    exit();
}

$id = (int)$_GET['id'];
$status = $_GET['status'];

// Allowed statuses
$allowed_status = ['Draft', 'Submitted', 'Approved', 'Rejected'];

if (!in_array($status, $allowed_status)) {
    header("Location: bbu_list.php?error=Invalid status");
    exit();
}

// OPTIONAL: status flow control (important 🔥)
$current = $conn->query("SELECT status FROM bbu_master WHERE id = $id")->fetch_assoc()['status'];

$valid_flow = [
    'Draft' => ['Submitted'],
    'Submitted' => ['Approved', 'Rejected'],
    'Rejected' => ['Draft'],
    'Approved' => []
];

if (!in_array($status, $valid_flow[$current])) {
    header("Location: bbu_list.php?error=Invalid status transition");
    exit();
}

// Update status
$stmt = $conn->prepare("UPDATE bbu_master SET status = ?, updated_at = NOW() WHERE id = ?");
$stmt->bind_param("si", $status, $id);

if ($stmt->execute()) {
    header("Location: bbu_list.php?success=Status updated successfully");
} else {
    header("Location: bbu_list.php?error=Failed to update status");
}
exit();