<?php
/**
 * add_s2s_reward.php — Payment Server Endpoint
 * 
 * Inserts wallet credit/debit records into driverWallet.
 * 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");
$paymentID     = filterRequest("paymentID");
$amount        = filterRequest("amount");
$paymentMethod = filterRequest("paymentMethod");
$points        = filterRequest("points"); // Optional raw points

if (empty($driverID) || empty($paymentID) || !isset($amount) || empty($paymentMethod)) {
    printFailure("Missing required parameters: driverID, paymentID, amount, paymentMethod");
    exit;
}

try {
    $con->beginTransaction();

    // Prevent duplicate challenge claims using paymentsDriverPoints table
    if (strpos($paymentMethod, 'daily_') === 0 || strpos($paymentMethod, 'weekly_') === 0) {
        $checkSql = "SELECT id FROM paymentsDriverPoints WHERE driverID = :driver_id AND payment_method = :challenge_id AND DATE(created_at) = CURDATE() FOR UPDATE";
        $stmtCheck = $con->prepare($checkSql);
        $stmtCheck->execute([
            ':driver_id' => $driverID,
            ':challenge_id' => $paymentMethod
        ]);

        if ($stmtCheck->rowCount() > 0) {
            $con->rollBack();
            printFailure("Reward already claimed today");
            exit();
        }
    }

    $sql = "INSERT INTO `driverWallet` (
        `driverID`,
        `paymentID`,
        `amount`,
        `paymentMethod`
    ) VALUES (
        :driverID,
        :paymentID,
        :amount,
        :paymentMethod
    );";

    $stmt = $con->prepare($sql);
    $stmt->execute([
        ':driverID' => $driverID,
        ':paymentID' => $paymentID,
        ':amount' => $amount,
        ':paymentMethod' => $paymentMethod
    ]);

    if ($stmt->rowCount() > 0) {
        // If points are provided, also insert into paymentsDriverPoints
        if (!empty($points)) {
            $sqlPoints = "INSERT INTO `paymentsDriverPoints` (
                `amount`,
                `payment_method`,
                `driverID`
            ) VALUES (
                :points,
                :paymentMethod,
                :driverID
            );";
            $stmtPoints = $con->prepare($sqlPoints);
            $stmtPoints->execute([
                ':points' => $points,
                ':paymentMethod' => $paymentMethod,
                ':driverID' => $driverID
            ]);
        }

        $con->commit();
        printSuccess("Record saved successfully");
    } else {
        $con->rollBack();
        printFailure("Failed to save record");
    }
} catch (Exception $e) {
    if ($con->inTransaction()) {
        $con->rollBack();
    }
    printFailure("An error occurred: " . $e->getMessage());
}
?>
