<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Disposal.php';
require_once __DIR__ . '/../../classes/Logger.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$auth->requireLogin();

if (!$auth->isSuperAdmin($_SESSION['user_id']) && !$auth->isWarehousePersonnel($_SESSION['user_id'])) {
    header('Location: /IMS/unauthorized.php');
    exit;
}

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

$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
$disposal = new Disposal($conn, $logger);
$disposalId = (int)($_POST['disposal_id'] ?? 0);
$status = $_POST['status'] ?? '';
$notes = trim($_POST['notes'] ?? '');

if ($disposalId && $disposal->updateStatus($disposalId, $status, $_SESSION['user_id'], $notes)) {
    header('Location: index.php?success=' . urlencode("Disposal request #{$disposalId} updated."));
    exit;
}

header('Location: index.php?success=' . urlencode('No disposal update was made.'));
exit;
