<?php
// /admin/poll_status.php

session_start();

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

require_admin_auth($config);

header('Content-Type: application/json');

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

try {
    // Current user / tenancy 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);
        echo json_encode(['ok' => false, 'error' => 'No organisation scope']);
        exit;
    }

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

    if (!is_array($ids) || !$ids) {
        echo json_encode(['ok' => true, 'statuses' => []]);
        exit;
    }

    $ids = array_values(array_unique(array_map('intval', $ids)));
    if (!$ids) {
        echo json_encode(['ok' => true, 'statuses' => []]);
        exit;
    }

    if (count($ids) > 500) {
        $ids = array_slice($ids, 0, 500);
    }

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

    if ($isOrgAdmin) {
        // Org admin: any request in their organisation
        $sql = "
            SELECT id, status, expires_at
            FROM requests
            WHERE id IN ($in)
              AND organisation_id = ?
        ";
        $params = array_merge($ids, [$orgId]);
    } else {
        // Normal user: only their org + company
        $sql = "
            SELECT id, status, expires_at
            FROM requests
            WHERE id IN ($in)
              AND organisation_id = ?
              AND company_id = ?
        ";
        $params = array_merge($ids, [$orgId, $companyId]);
    }

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $out = [];
    foreach ($rows as $r) {
        $out[] = [
            'id'         => (int)$r['id'],
            'status'     => (string)$r['status'],
            'expires_at' => $r['expires_at'] !== null ? (string)$r['expires_at'] : null,
        ];
    }

    echo json_encode(['ok' => true, 'statuses' => $out]);
} catch (Throwable $e) {
    // For debugging you might log: error_log($e->getMessage());
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Server error']);
}
