<?php
// admin/reopen.php

session_start();

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

require_admin_auth($config); // ensures $_SESSION['user'] exists or redirects

if ($pdo instanceof PDO) {
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

// Current user / tenancy
$me         = $_SESSION['user'] ?? [];
$orgId      = isset($me['organisation_id']) ? (int)$me['organisation_id'] : 0;
$companyId  = isset($me['company_id'])      ? (int)$me['company_id']      : 0;
$isOrgAdmin = !empty($me['is_org_admin']);

if ($orgId <= 0) {
    http_response_code(403);
    exit('Forbidden: no organisation scope.');
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    header('Location: index.php?msg=' . urlencode('Invalid ID.'));
    exit;
}

/**
 * Tenancy rules:
 * - Org admin can reopen any request in their organisation.
 * - Normal user can only reopen requests in their own org + company.
 */
if ($isOrgAdmin) {
    $stmt = $pdo->prepare("
        SELECT status
        FROM requests
        WHERE id = ?
          AND organisation_id = ?
        LIMIT 1
    ");
    $stmt->execute([$id, $orgId]);
} else {
    $stmt = $pdo->prepare("
        SELECT status
        FROM requests
        WHERE id = ?
          AND organisation_id = ?
          AND company_id = ?
        LIMIT 1
    ");
    $stmt->execute([$id, $orgId, $companyId]);
}

$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    // Either it doesn't exist, or it's outside this user's scope → don't leak which
    header('Location: index.php?msg=' . urlencode('Not found.'));
    exit;
}

if (!in_array($row['status'], ['closed', 'expired'], true)) {
    header('Location: index.php?msg=' . urlencode('Only closed or expired requests can be reopened.'));
    exit;
}

// Scoped UPDATE so we never touch another tenant’s row
if ($isOrgAdmin) {
    $up = $pdo->prepare("
        UPDATE requests
        SET status = 'open'
        WHERE id = ?
          AND organisation_id = ?
          AND status IN ('closed','expired')
        LIMIT 1
    ");
    $up->execute([$id, $orgId]);
} else {
    $up = $pdo->prepare("
        UPDATE requests
        SET status = 'open'
        WHERE id = ?
          AND organisation_id = ?
          AND company_id = ?
          AND status IN ('closed','expired')
        LIMIT 1
    ");
    $up->execute([$id, $orgId, $companyId]);
}

if ($up->rowCount() < 1) {
    // Should be rare: race condition or scope mismatch
    $msg = 'Unable to reopen request (it may have changed or is out of scope).';
} else {
    $msg = 'Request #' . $id . ' reopened.';
}

header('Location: index.php?msg=' . urlencode($msg));
exit;
