<?php

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');

require_once('../lib/dbclass.php');

// Helper function to safely fetch first row or default value
function getFirstRowValue($array, $key, $default = 0)
{
    return $array[0][$key] ?? $default;
}

// Initialize response
$response = [
    'Status' => 'true',
    'data'   => [],
];

// Step 1: Check for an active challenge
$activeChallenge = findQuery('SELECT * FROM tbl_challenge WHERE status=0 AND CURDATE() BETWEEN challenge_startdate AND challenge_enddate');

if (!empty($activeChallenge)) {
    $challengeId = $activeChallenge[0]['id'];

    // Fetch data
    $volunteerQty = findQuery("
        SELECT IFNULL(SUM(Totqty), 0) AS QTY
        FROM tbl_transactiondetails
        INNER JOIN tbl_transaction ON tbl_transaction.id = tbl_transactiondetails.hdrid
        WHERE tbl_transaction.challengeid = $challengeId
        AND tbl_transaction.sponsorship = 0
        AND volunteer > 0
    ");

    $customerQty = findQuery("
        SELECT IFNULL(SUM(Totqty), 0) AS QTY
        FROM tbl_transactiondetails
        INNER JOIN tbl_transaction ON tbl_transaction.id = tbl_transactiondetails.hdrid
        WHERE tbl_transaction.challengeid = $challengeId
        AND tbl_transaction.sponsorship = 0
        AND volunteer = 0
        AND Received > 0
    ");

    $totalReceived = findQuery("
        SELECT IFNULL(SUM(Received), 0) AS Received
        FROM tbl_transaction
        WHERE challengeid = $challengeId AND sponsorship = 0
    ");

    $units  = getFirstRowValue($volunteerQty, 'QTY') + getFirstRowValue($customerQty, 'QTY');
    $amount = getFirstRowValue($totalReceived, 'Received');

    $response['data'][] = [
        'Count'       => (string) $units,
        'Description' => 'Challenge',
        'unit'        => 'Packets',
        'Received'    => $amount,
    ];
} else {
    // No active challenge — check for donations
    $donationAmount = findQuery('SELECT SUM(Received) AS Received FROM tbl_transaction WHERE donation = 1 AND Received > 0');
    $donationData   = findQuery('SELECT * FROM tbl_transaction WHERE donation = 1 AND Received > 0');

    $amount = getFirstRowValue($donationAmount, 'Received');

    if ($amount > 0) {
        $donorCount = count($donationData);

        $response['data'][] = [
            'Count'       => (string) $donorCount,
            'Description' => 'Donation',
            'unit'        => 'Donors',
            'Received'    => $amount,
        ];
    } else {
        // Fallback to most recent challenge
        $latestChallenge = findQuery('SELECT * FROM tbl_challenge WHERE status = 0 ORDER BY id DESC LIMIT 1');

        if (!empty($latestChallenge)) {
            $challengeId = $latestChallenge[0]['id'];

            $volunteerQty = findQuery("
                SELECT IFNULL(SUM(Totqty), 0) AS QTY
                FROM tbl_transactiondetails
                INNER JOIN tbl_transaction ON tbl_transaction.id = tbl_transactiondetails.hdrid
                WHERE tbl_transaction.challengeid = $challengeId
                AND tbl_transaction.sponsorship = 0
                AND volunteer > 0
            ");

            $customerQty = findQuery("
                SELECT IFNULL(SUM(Totqty), 0) AS QTY
                FROM tbl_transactiondetails
                INNER JOIN tbl_transaction ON tbl_transaction.id = tbl_transactiondetails.hdrid
                WHERE tbl_transaction.challengeid = $challengeId
                AND tbl_transaction.sponsorship = 0
                AND volunteer = 0
                AND Received > 0
            ");

            $totalReceived = findQuery("
                SELECT IFNULL(SUM(Received), 0) AS Received
                FROM tbl_transaction
                WHERE challengeid = $challengeId AND sponsorship = 0
            ");

            $units  = getFirstRowValue($volunteerQty, 'QTY') + getFirstRowValue($customerQty, 'QTY');
            $amount = getFirstRowValue($totalReceived, 'Received');

            $response['data'][] = [
                'Count'       => (string) $units,
                'Description' => 'Challenge',
                'unit'        => 'Packets',
                'Received'    => $amount,
            ];
        }
    }
}

// Output final JSON
echo json_encode($response);

return;
