<?php

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

// استقبال المتغيرات
$driver_id = filterRequest("driver_id");
$order_id  = filterRequest("order_id");
$status    = filterRequest("status");

// التحقق من وجود order_id مسبقًا
$checkSql = "SELECT `order_id` FROM `driver_orders` WHERE `order_id` = ?";
$checkStmt = $con->prepare($checkSql);
$checkStmt->execute([$order_id]);

if ($checkStmt->rowCount() > 0) {
    // تحديث السجل إذا كان موجودًا
    $updateSql = "UPDATE `driver_orders` SET `driver_id` = ?, `status` = ?, `created_at` = NOW() WHERE `order_id` = ?";
    $updateStmt = $con->prepare($updateSql);
    $updateStmt->execute([$driver_id, $status, $order_id]);

    if ($updateStmt->rowCount() > 0) {
        jsonSuccess(null, "Driver order data updated successfully");
    } else {
        jsonError("Failed to update driver order data");
    }
} else {
    // إدخال سجل جديد إذا لم يكن موجودًا
    $insertSql = "INSERT INTO `driver_orders` (`driver_id`, `order_id`, `created_at`, `status`) VALUES (?, ?, NOW(), ?)";
    $insertStmt = $con->prepare($insertSql);
    $insertStmt->execute([$driver_id, $order_id, $status]);

    if ($insertStmt->rowCount() > 0) {
        jsonSuccess(null, "Driver order data saved successfully");
    } else {
        jsonError("Failed to save driver order data");
    }
}
?>