<?php
/**
 * get_s2s_wallet_dashboard.php — Payment Server Endpoint
 * 
 * Returns wallet metrics (challenge points, today's earnings) for a driver.
 * Authenticated via X-S2S-Api-Key header matching the S2S_SHARED_KEY environment variable.
 */

require_once __DIR__ . '/../../jwtconnect.php';

define('S2S_SHARED_KEY', getenv('S2S_SHARED_KEY'));

$providedKey = $_SERVER['HTTP_X_S2S_API_KEY'] ?? '';

if (empty($providedKey) || $providedKey !== S2S_SHARED_KEY) {
    http_response_code(401);
    printFailure("Unauthorized: Invalid or missing X-S2S-Api-Key.");
    exit;
}

$driverID = filterRequest("driverID");

if (empty($driverID)) {
    printFailure("Missing required parameter: driverID");
    exit;
}

try {
    // 1. Calculate Sum of claimed challenge points
    $stmtChallengePoints = $con->prepare("
        SELECT COALESCE(SUM(amount), 0) 
        FROM `paymentsDriverPoints` 
        WHERE driverID = :driver_id 
          AND (payment_method LIKE 'daily_%' OR payment_method LIKE 'weekly_%')
    ");
    $stmtChallengePoints->execute([':driver_id' => $driverID]);
    $challengePoints = (int)($stmtChallengePoints->fetchColumn() ?: 0);

    // 2. Calculate Today's Earnings
    $stmtTodayEarnings = $con->prepare("
        SELECT COALESCE(SUM(amount), 0) 
        FROM payments 
        WHERE driverID = :driver_id 
          AND DATE(created_at) = CURDATE()
    ");
    $stmtTodayEarnings->execute([':driver_id' => $driverID]);
    $todayEarnings = (float)($stmtTodayEarnings->fetchColumn() ?: 0.0);

    // 3. Calculate Total Wallet Balance
    $stmtTotalWallet = $con->prepare("
        SELECT COALESCE(SUM(amount), 0) 
        FROM `driverWallet` 
        WHERE driverID = :driver_id
    ");
    $stmtTotalWallet->execute([':driver_id' => $driverID]);
    $totalWallet = (float)($stmtTotalWallet->fetchColumn() ?: 0.0);

    printSuccess([
        "challengePoints" => $challengePoints,
        "todayEarnings" => $todayEarnings,
        "totalWallet" => $totalWallet
    ]);

} catch (Exception $e) {
    printFailure("An error occurred: " . $e->getMessage());
}
?>
