<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    echo json_encode(['success' => false]);
    exit;
}

require_once '../config/database.php';

function safeCount($pdo, $sql) {
    try { return (int)$pdo->query($sql)->fetchColumn(); }
    catch (Throwable $e) { return 0; }
}

echo json_encode([
    'success'         => true,
    'totalCustomers'  => safeCount($pdo, "SELECT COUNT(*) FROM customers c WHERE NOT EXISTS (SELECT 1 FROM company_staff cs WHERE cs.user_id = c.user_id)"),
    'totalPartners'   => safeCount($pdo, "SELECT COUNT(*) FROM partner_shops"),
    'pendingReqs'     => safeCount($pdo, "SELECT COUNT(*) FROM credit_requests WHERE status='pending'"),
    'todayTx'         => safeCount($pdo, "SELECT COUNT(*) FROM transactions WHERE DATE(created_at)=CURDATE()"),
    'totalCompanies'  => safeCount($pdo, "SELECT COUNT(*) FROM companies WHERE status='active'"),
    'totalStaffAll'   => safeCount($pdo, "SELECT COUNT(*) FROM company_staff"),
    'pendingLeaveAll' => safeCount($pdo, "SELECT COUNT(*) FROM hr_leave WHERE status='pending'"),
]);