<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include '../connection.php';

$response = array();

if (isset($_POST['user_id'], $_POST['delivery_mode_id'], $_POST['pickup_datetime'], $_POST['delivery_datetime'], $_POST['final_total'], $_POST['delivery_charge'])) {
    
    $user_id = intval($_POST['user_id']);
    $delivery_mode_id = intval($_POST['delivery_mode_id']);
    $pickup_datetime = $_POST['pickup_datetime'];
    $delivery_datetime = $_POST['delivery_datetime'];
    $final_total = $_POST['final_total'];
    $delivery_charge = $_POST['delivery_charge'];
    
    $sqlchk = "select * from tbl_schedule where user_id = $user_id and pickup_datetime = '$pickup_datetime'";
    $rchk = $conn->query($sqlchk);
    if ($rchk && $rchk->num_rows > 0){
        $sqlDEL = "delete from tbl_schedule where user_id = $user_id and pickup_datetime = '$pickup_datetime'";
        $conn->query($sqlDEL);
    }

    $query = "INSERT INTO tbl_schedule (user_id, delivery_mode_id, pickup_datetime, delivery_datetime, final_total, delivery_charge, created_at)
              VALUES ('$user_id','$delivery_mode_id','$pickup_datetime','$delivery_datetime','$final_total','$delivery_charge', NOW())";

    if (mysqli_query($conn, $query)) {
        $response['success'] = true;
        $response['message'] = "Schedule saved successfully.";
    } else {
        $response['success'] = false;
        $response['message'] = "Error: " . mysqli_error($conn);
    }
} else {
    $response['success'] = false;
    $response['message'] = "Missing fields.";
}

echo json_encode($response);
?>
