<?php
header('Content-Type: application/json');
include '../connection.php';

$orderId = $_POST['order_id'] ?? null;
$deliverymanId = $_POST['deliveryman_id'] ?? null;
$assignedBy = $_POST['assigned_by'] ?? null;

if (!$orderId || !$deliverymanId || !$assignedBy) {
    echo json_encode(["success" => false, "message" => "Missing required parameters"]);
    exit;
}

// Check if order is already assigned
$sqlCHK = "SELECT * FROM tbl_delevery_assign WHERE order_id = ?";
$stmtCHK = mysqli_prepare($conn, $sqlCHK);
mysqli_stmt_bind_param($stmtCHK, "i", $orderId);
mysqli_stmt_execute($stmtCHK);
$resultCHK = mysqli_stmt_get_result($stmtCHK);

if (mysqli_num_rows($resultCHK) > 0) {
    echo json_encode(["success" => false, "message" => "The Order is already assigned"]);
    exit;
}
mysqli_stmt_close($stmtCHK);

// Insert into assignment table with status_id = 1 (Pending)
$sql1 = "INSERT INTO tbl_delevery_assign (order_id, deliveryman_id, assigned_by, status_id) VALUES (?, ?, ?, 1)";
$stmt1 = mysqli_prepare($conn, $sql1);
mysqli_stmt_bind_param($stmt1, "iii", $orderId, $deliverymanId, $assignedBy);

if (mysqli_stmt_execute($stmt1)) {
    mysqli_stmt_close($stmt1);

    // Check if tracking record exists for this order_id
    $sqlTrackChk = "SELECT * FROM tbl_track WHERE order_id = ?";
    $stmtTrackChk = mysqli_prepare($conn, $sqlTrackChk);
    mysqli_stmt_bind_param($stmtTrackChk, "i", $orderId);
    mysqli_stmt_execute($stmtTrackChk);
    $resultTrackChk = mysqli_stmt_get_result($stmtTrackChk);

    $trackingStatus = 'One Delivery man Assigned for Pickup';

    if (mysqli_num_rows($resultTrackChk) > 0) {
        // Update existing tracking record
        mysqli_stmt_close($stmtTrackChk);

        $sqlUpdateTrack = "UPDATE tbl_track SET status = ?, updated_by = ? WHERE order_id = ?";
        $stmtUpdateTrack = mysqli_prepare($conn, $sqlUpdateTrack);
        mysqli_stmt_bind_param($stmtUpdateTrack, "sii", $trackingStatus, $assignedBy, $orderId);

        if (!mysqli_stmt_execute($stmtUpdateTrack)) {
            echo json_encode(["success" => false, "message" => "Tracking update failed"]);
            mysqli_stmt_close($stmtUpdateTrack);
            mysqli_close($conn);
            exit;
        }
        mysqli_stmt_close($stmtUpdateTrack);
    } else {
        // Insert new tracking record
        mysqli_stmt_close($stmtTrackChk);

        $sqlInsertTrack = "INSERT INTO tbl_track (order_id, status, updated_by) VALUES (?, ?, ?)";
        $stmtInsertTrack = mysqli_prepare($conn, $sqlInsertTrack);
        mysqli_stmt_bind_param($stmtInsertTrack, "isi", $orderId, $trackingStatus, $assignedBy);

        if (!mysqli_stmt_execute($stmtInsertTrack)) {
            echo json_encode(["success" => false, "message" => "Tracking insert failed"]);
            mysqli_stmt_close($stmtInsertTrack);
            mysqli_close($conn);
            exit;
        }
        mysqli_stmt_close($stmtInsertTrack);
    }

    // Update order table
    $sqlupdt = "UPDATE tbl_order SET assign_del_status = 'Assigned' WHERE id = ?";
    $stmtupdt = mysqli_prepare($conn, $sqlupdt);
    mysqli_stmt_bind_param($stmtupdt, "i", $orderId);
    if (mysqli_stmt_execute($stmtupdt)) {
        echo json_encode(["success" => true, "message" => "Assigned successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Order update failed"]);
    }
    mysqli_stmt_close($stmtupdt);
} else {
    echo json_encode(["success" => false, "message" => "Assignment failed"]);
}

mysqli_close($conn);










/*

include '../connection.php';

$orderId = $_POST['order_id'];
$deliverymanId = $_POST['deliveryman_id'];
$assignedBy = $_POST['assigned_by'];

$sqlCHK = "SELECT * FROM tbl_delevery_assign WHERE order_id = '$orderId'";
$resultCHK = mysqli_query($conn, $sqlCHK);
if(mysqli_num_rows($resultCHK) > 0){
    echo json_encode(["success" => false, "message" => "The Order already assigned"]);
}else{
    // Insert into assignment table
    $sql1 = "INSERT INTO tbl_delevery_assign (order_id, deliveryman_id, assigned_by) 
         VALUES ('$orderId', '$deliverymanId', '$assignedBy')";

    if (mysqli_query($conn, $sql1)) {
        // Also insert tracking record
        $sql2 = "INSERT INTO tbl_track (order_id, status, updated_by)
                 VALUES ('$orderId', 'One Delivery man Assigned for Pickup', '$assignedBy')";
    
        if (mysqli_query($conn, $sql2)) {
            //update order table
            $sqlupdt = "update tbl_order set assign_del_status = 'Assigned' where id = $orderId";
            if(mysqli_query($conn, $sqlupdt)){
                echo json_encode(["success" => true, "message" => "Assigned successfully"]);
            }else{
                echo json_encode(["success" => false, "message" => "Order update failed"]);
            }
        } else {
            echo json_encode(["success" => false, "message" => "Tracking insert failed"]);
        }
    } else {
        echo json_encode(["success" => false, "message" => "Assignment failed"]);
    }   
}

*/
?>
