<?php
// /api/towlens/stats.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') !== 'GET') {
    header('Allow: GET'); jresp(['error'=>'Method not allowed'],405);
}

// Example stats (tune to taste):

$totReq = (int)$pdo->query("SELECT COUNT(*) FROM requests")->fetchColumn();

$completedShares = (int)$pdo->query("
  SELECT COUNT(DISTINCT request_id)
  FROM request_shares
  WHERE status IN ('completed')
")->fetchColumn();

$openedShares = (int)$pdo->query("
  SELECT COUNT(*)
  FROM request_shares
  WHERE open_count > 0
")->fetchColumn();

$avgFirstOpen = $pdo->query("
  SELECT AVG(TIMESTAMPDIFF(MINUTE, created_at, first_open_at))
  FROM request_shares
  WHERE first_open_at IS NOT NULL
")->fetchColumn();

jresp([
    'total_requests'            => $totReq,
    'requests_with_completed'   => $completedShares,
    'shares_opened'             => $openedShares,
    'avg_minutes_to_first_open' => $avgFirstOpen !== null ? (float)$avgFirstOpen : null,
]);