<?php
// ==========================================
//  Cron Job: Remove Duplicate Records Daily
//  Tables: driverWallet, paymentsDriverPoints
// ==========================================

// Load DB Connection
include "../../jwtconnect.php";

// Function to run cleanup query
function runCleanup($con, $deleteQuery, $tableName) {
    try {
        $stmt = $con->prepare($deleteQuery);
        $stmt->execute();

        echo "Cleanup completed for table: $tableName\n";
        echo "Rows affected: " . $stmt->rowCount() . "\n\n";
    } catch (Exception $e) {
        echo "Error cleaning $tableName: " . $e->getMessage() . "\n\n";
    }
}

// ==========================================
// DELETE DUPLICATES FOR driverWallet
// ==========================================

$deleteDriverWallet = "
DELETE FROM driverWallet
WHERE id NOT IN (
    SELECT id FROM (
        SELECT 
            id,
            ROW_NUMBER() OVER(PARTITION BY driverID ORDER BY dateCreated DESC) AS rn
        FROM driverWallet
    ) AS subquery
    WHERE rn = 1
);";

runCleanup($con, $deleteDriverWallet, "driverWallet");


// ==========================================
// DELETE DUPLICATES FOR paymentsDriverPoints
// ==========================================

$deletePaymentsPoints = "
DELETE FROM paymentsDriverPoints
WHERE id NOT IN (
    SELECT id FROM (
        SELECT 
            id,
            ROW_NUMBER() OVER(PARTITION BY driverID ORDER BY created_at DESC) AS rn
        FROM paymentsDriverPoints
    ) AS subquery
    WHERE rn = 1
);";

runCleanup($con, $deletePaymentsPoints, "paymentsDriverPoints");

echo "Cron job completed successfully.\n";

?>
