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

$driver_id = filterRequest("driver_id");
$points = filterRequest("points"); // Reward points amount
$challenge_id = filterRequest("challenge_id");

// Check if already claimed today to prevent spam
$checkSql = "SELECT id FROM driverWallet WHERE driverID = :driver_id AND paymentMethod = :challenge_id AND DATE(dateCreated) = CURDATE()";
$stmtCheck = $con->prepare($checkSql);
$stmtCheck->bindParam(':driver_id', $driver_id, PDO::PARAM_INT);
$stmtCheck->bindParam(':challenge_id', $challenge_id, PDO::PARAM_STR);
$stmtCheck->execute();

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

// Insert into driver wallet
$paymentID = "CHL_" . time();
$sql = "INSERT INTO driverWallet (driverID, paymentID, amount, paymentMethod) VALUES (:driver_id, :paymentID, :amount, :method)";
$stmt = $con->prepare($sql);
$stmt->bindParam(':driver_id', $driver_id, PDO::PARAM_INT);
$stmt->bindParam(':paymentID', $paymentID, PDO::PARAM_STR);
$stmt->bindParam(':amount', $points, PDO::PARAM_STR);
$stmt->bindParam(':method', $challenge_id, PDO::PARAM_STR);

if ($stmt->execute()) {
    jsonSuccess("Reward claimed successfully");
} else {
    jsonError("Failed to claim reward");
}
?>
