<?php

// Include the database connection file
include "../../connect.php";

// Get the request parameters
$driver_id = filterRequest("driver_id");
$payment_amount = filterRequest("payment_amount");
$timePromo = filterRequest("timePromo");  // Example: 'morning' or 'afternoon'
//$createdAt = date("Y-m-d H:i:s");  // Get the current date and time
$currentDate = date("Y-m-d"); // Current date for comparison

// Check if a promotion record for the same driver already exists today
$sqlCheck = "SELECT COUNT(*) FROM `driver_promotions` WHERE `driver_id` = :driver_id AND DATE(`created_at`) = :current_date
and timePromo=:timePromo
";
$stmtCheck = $con->prepare($sqlCheck);
$stmtCheck->execute(array(
    ':driver_id' => $driver_id,
    ':current_date' => $currentDate
  	':timePromo' =>$timePromo
));

$count = $stmtCheck->fetchColumn();

if ($count > 0) {
    // A record exists for today, so prevent the insertion
    printFailure("A promotion record for this driver already exists for today.");
} else {
    // No record exists for today, so insert the new promotion
    $sqlInsert = "INSERT INTO `driver_promotions` (
                    `driver_id`, 
                    `payment_amount`, 
                    `timePromo`
                  ) VALUES (
                    :driver_id, 
                    :payment_amount, 
                    :timePromo
                  );";

    // Prepare the insert statement
    $stmtInsert = $con->prepare($sqlInsert);
    $stmtInsert->execute(array(
        ':driver_id' => $driver_id,
        ':payment_amount' => $payment_amount,
        ':timePromo' => $timePromo,
        ':createdAt' => $createdAt
    ));

    // Check if the query was successful
    if ($stmtInsert->rowCount() > 0) {
        // Print a success message
        printSuccess("Promotion record saved successfully");
    } else {
        // Print a failure message
        printFailure("Failed to save promotion record");
    }
}

?>