<?php
/**
 * POST /api/requests/update_status.php
 * Body (JSON): { id, status } — status must be 'fulfilled' or 'cancelled'.
 * The requester can update their own request; admins can moderate any.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

only_post_allowed();
$userId = require_login();

$input = get_json_input();
$id = (int) ($input['id'] ?? 0);
$status = $input['status'] ?? '';

if ($id <= 0 || !in_array($status, ['fulfilled', 'cancelled', 'open'], true)) {
    send_error('A valid request id and status are required.', 422);
}

$pdo = Database::connect();
$stmt = $pdo->prepare('SELECT requester_id FROM item_requests WHERE id = ?');
$stmt->execute([$id]);
$request = $stmt->fetch();

if (!$request) {
    send_error('Request not found.', 404);
}
if ((int) $request['requester_id'] !== $userId && current_account_type() !== 'admin') {
    send_error('You can only update your own requests.', 403);
}

$stmt = $pdo->prepare('UPDATE item_requests SET status = ? WHERE id = ?');
$stmt->execute([$status, $id]);

send_json(true, 'Request updated.');
