<?php
require_once __DIR__ . '/security.php';

if (!headers_sent()) {
    header('Content-Type: application/json; charset=utf-8');
}

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../' . $tenant . '/config.php')) {
    require_once('../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

$response = [
    'success' => false,
    'message' => '',
    'data'    => []
];

try {
    if (!isset($GLOBALS['con']) || !$GLOBALS['con'] instanceof mysqli || $GLOBALS['con']->connect_error) {
        throw new Exception('Database connection is not available.');
    }

    enrep_require_user();

    $con = $GLOBALS['con'];
    $reportStartDate = enrep_request_string('report_start_date', '', 30);
    $reportEndDate = enrep_request_string('report_end_date', '', 30);
    $clientRaw = enrep_request_string('client_id', 'all', 20);
    $clientId = ($clientRaw !== '' && strtolower($clientRaw) !== 'all' && filter_var($clientRaw, FILTER_VALIDATE_INT) !== false)
        ? (int)$clientRaw
        : 0;

    $startUnix = null;
    $endUnix = null;
    if ($reportStartDate !== '' && $reportEndDate !== '') {
        $tmpStart = strtotime($reportStartDate . ' 00:00:00');
        $tmpEnd = strtotime($reportEndDate . ' 23:59:59');
        if ($tmpStart !== false && $tmpEnd !== false) {
            $startUnix = $tmpStart;
            $endUnix = $tmpEnd;
        } else {
            error_log('Invalid date format for report filter: ' . $reportStartDate . ' - ' . $reportEndDate);
        }
    }

    $bind = function (mysqli_stmt $stmt, string $types, array $params): void {
        if ($types === '') {
            return;
        }

        $refs = [];
        foreach ($params as $key => &$value) {
            $refs[$key] = &$value;
        }
        array_unshift($refs, $types);
        call_user_func_array([$stmt, 'bind_param'], $refs);
    };

    $countQuery = function (string $sql, string $types = '', array $params = []) use ($con, $bind): int {
        $stmt = $con->prepare($sql);
        if (!$stmt) {
            throw new Exception('Unable to prepare dashboard total query.');
        }
        $bind($stmt, $types, $params);
        $stmt->execute();
        $result = $stmt->get_result();
        $stmt->close();
        $row = $result ? $result->fetch_assoc() : [];
        return (int)($row['total'] ?? 0);
    };

    $clientCondition = '';
    $clientTypes = '';
    $clientParams = [];
    if ($clientId > 0) {
        $clientCondition = ' AND clientnumber = ?';
        $clientTypes = 'i';
        $clientParams = [$clientId];
    }

    $reportDateCondition = '';
    $reportDateTypes = '';
    $reportDateParams = [];
    if ($startUnix !== null && $endUnix !== null) {
        $reportDateCondition = ' AND insdate BETWEEN ? AND ?';
        $reportDateTypes = 'ii';
        $reportDateParams = [$startUnix, $endUnix];
    }

    $response['data']['totalActiveClients'] = $countQuery(
        "SELECT COUNT(*) AS total FROM clientdetails WHERE statuslive = 1 {$clientCondition}",
        $clientTypes,
        $clientParams
    );

    $response['data']['totalArchivedClients'] = $countQuery(
        "SELECT COUNT(*) AS total FROM clientdetails WHERE statuslive = 0 {$clientCondition}",
        $clientTypes,
        $clientParams
    );

    $response['data']['totalAssets'] = $countQuery(
        "SELECT COUNT(*) AS total FROM itemdetails WHERE statuslive = 1 {$clientCondition}",
        $clientTypes,
        $clientParams
    );

    $response['data']['totalWrittenSchemes'] = $countQuery(
        "SELECT COUNT(*) AS total FROM writtenscheme WHERE 1=1 {$clientCondition}",
        $clientTypes,
        $clientParams
    );

    $response['data']['totalReportsCreated'] = $countQuery(
        "SELECT COUNT(*) AS total FROM reportitems WHERE 1=1 {$clientCondition}{$reportDateCondition}",
        $clientTypes . $reportDateTypes,
        array_merge($clientParams, $reportDateParams)
    );

    if ($startUnix !== null && $endUnix !== null) {
        $itemDueCondition = '';
        $itemDueTypes = 'ii';
        $itemDueParams = [$startUnix, $endUnix];
        if ($clientId > 0) {
            $itemDueCondition = ' AND i.clientnumber = ?';
            $itemDueTypes .= 'i';
            $itemDueParams[] = $clientId;
        }

        $response['data']['totalItemsDueInPeriod'] = $countQuery(
            "SELECT COUNT(*) AS total
             FROM itemdetails i
             INNER JOIN clientdetails c ON i.clientnumber = c.clientnumber
             WHERE i.statuslive = 1
               AND c.statuslive = 1
               AND i.duedate BETWEEN ? AND ?
               {$itemDueCondition}",
            $itemDueTypes,
            $itemDueParams
        );

        $jobsCondition = '';
        $jobsTypes = 'ii';
        $jobsParams = [$startUnix, $endUnix];
        if ($clientId > 0) {
            $jobsCondition = ' AND r.clientnumber = ?';
            $jobsTypes .= 'i';
            $jobsParams[] = $clientId;
        }

        $response['data']['totalJobsCompletedInPeriod'] = $countQuery(
            "SELECT COUNT(DISTINCT r.repnumber) AS total
             FROM reportitems r
             INNER JOIN itemdetails i ON r.itemnumber = i.itemnumber
             INNER JOIN clientdetails c ON r.clientnumber = c.clientnumber
             WHERE i.statuslive = 1
               AND c.statuslive = 1
               AND r.insdate BETWEEN ? AND ?
               {$jobsCondition}",
            $jobsTypes,
            $jobsParams
        );
    } else {
        $response['data']['totalItemsDueInPeriod'] = 0;
        $response['data']['totalJobsCompletedInPeriod'] = 0;
    }

    $reportResultsTypes = ['PASS', 'WARNING', 'URGENT', 'OBS', 'PNA'];
    $response['data']['reportsByResult'] = [];
    foreach ($reportResultsTypes as $resultType) {
        $response['data']['reportsByResult'][$resultType] = $countQuery(
            "SELECT COUNT(*) AS total FROM reportitems WHERE result = ? {$clientCondition}{$reportDateCondition}",
            's' . $clientTypes . $reportDateTypes,
            array_merge([$resultType], $clientParams, $reportDateParams)
        );
    }

    $stmt = $con->prepare("
        SELECT `desc`, COUNT(*) AS total
        FROM itemdetails
        WHERE statuslive = 1
        {$clientCondition}
        GROUP BY `desc`
        ORDER BY `desc` ASC
    ");
    if (!$stmt) {
        throw new Exception('Unable to prepare dashboard asset type query.');
    }
    $bind($stmt, $clientTypes, $clientParams);
    $stmt->execute();
    $assetTypeResult = $stmt->get_result();
    $stmt->close();

    $response['data']['assetTypes'] = [];
    while ($row = $assetTypeResult->fetch_assoc()) {
        $response['data']['assetTypes'][(string)$row['desc']] = (int)$row['total'];
    }

    $activeClientsResult = $con->query("
        SELECT clientnumber, clientname
        FROM clientdetails
        WHERE statuslive = 1
        ORDER BY clientname ASC
    ");
    if (!$activeClientsResult) {
        throw new Exception('Unable to load active client list.');
    }

    $response['data']['activeClientsList'] = [];
    while ($row = $activeClientsResult->fetch_assoc()) {
        $response['data']['activeClientsList'][] = [
            'id'   => (int)$row['clientnumber'],
            'name' => (string)$row['clientname']
        ];
    }

    $response['success'] = true;
} catch (Exception $e) {
    $response['message'] = 'Unable to load system totals.';
    error_log('get_system_totals.php error: ' . $e->getMessage());
}

echo json_encode($response);
