<?php
// admin/close.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'] is set or redirects

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

// Current user context
$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.');
}

// Collect IDs (single or bulk)
$ids = $_POST['ids'] ?? [];
if (isset($_POST['id'])) { // single close button
    $ids[] = (int)$_POST['id'];
}

$ids = array_values(array_unique(array_filter(array_map('intval', (array)$ids))));
if (!$ids) {
    header('Location: index.php?msg=' . urlencode('No requests selected.'));
    exit;
}

// Build scoped UPDATE
$in = implode(',', array_fill(0, count($ids), '?'));

if ($isOrgAdmin) {
    // Org admin: can close any open/submitted in their organisation across all companies
    $sql = "
        UPDATE requests
        SET status = 'closed'
        WHERE id IN ($in)
          AND organisation_id = ?
          AND status IN ('open','submitted')
    ";
    $params = array_merge($ids, [$orgId]);
} else {
    // Normal user: only their own company
    $sql = "
        UPDATE requests
        SET status = 'closed'
        WHERE id IN ($in)
          AND organisation_id = ?
          AND company_id = ?
          AND status IN ('open','submitted')
    ";
    $params = array_merge($ids, [$orgId, $companyId]);
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);

// Only report how many were actually closed within scope
$closed = (int)$stmt->rowCount();

$msg = $closed > 0
    ? "$closed request(s) closed."
    : "No requests were closed (not found, not open/submitted, or out of scope).";

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