<?php
// /api/towlens/review.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

session_start();

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) { http_response_code(500); echo json_encode(['error'=>'Server error']); exit; }

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';
require $ROOT . '/lib/helpers.php';

require_admin_auth($config);

if (!($pdo instanceof PDO)) { http_response_code(500); echo json_encode(['error'=>'DB unavailable']); exit; }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$user = $_SESSION['user'] ?? [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin','org_admin'], true)) {
    http_response_code(403);
    echo json_encode(['error'=>'Forbidden']);
    exit;
}

function jresp($d,$s=200){ http_response_code($s); echo json_encode($d,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; }

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    header('Allow: POST');
    jresp(['error'=>'Method not allowed'],405);
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true) ?? [];

$id     = (int)($data['request_id'] ?? 0);
$status = $data['status'] ?? '';
$notes  = trim($data['notes'] ?? '');

$allowed = ['not_required','pending','in_review','approved','rejected'];
if ($id <= 0 || !in_array($status, $allowed, true)) {
    jresp(['error'=>'Invalid input'],400);
}

$stmt = $pdo->prepare("SELECT id FROM requests WHERE id = ?");
$stmt->execute([$id]);
if (!$stmt->fetch()) jresp(['error'=>'Not found'],404);

$upd = $pdo->prepare("
  UPDATE requests
  SET review_status = ?, review_notes = ?, reviewed_by = ?, reviewed_at = NOW()
  WHERE id = ?
");
$upd->execute([
    $status,
    $notes,
    $user['email'] ?? $user['id'] ?? 'system',
    $id
]);

$ev = $pdo->prepare("
  INSERT INTO towlens_events (request_id, event_type, details, created_by)
  VALUES (?, 'REVIEW_UPDATED', ?, ?)
");
$ev->execute([
    $id,
    json_encode(['status'=>$status]),
    $user['email'] ?? 'system'
]);

jresp(['status'=>'ok']);