<?php
include("configa.php");

// Track Number আপডেট করার জন্য
if (isset($_POST['field']) && $_POST['field'] === 'track_number' && isset($_POST['oldTrackNumber']) && isset($_POST['newTrackNumber'])) {
    $oldTrackNumber = mysqli_real_escape_string($conn, $_POST['oldTrackNumber']);
    $newTrackNumber = mysqli_real_escape_string($conn, $_POST['newTrackNumber']);

    // এখানে একটি উপযুক্ত WHERE clause ব্যবহার করতে হবে,
    // যেমন পুরানো ট্র্যাক নাম্বার।
    $sql = "UPDATE final_order_item SET track_number = '$newTrackNumber' WHERE track_number = '$oldTrackNumber'";

    if (mysqli_query($conn, $sql)) {
        echo "Track number updated successfully";
    } else {
        echo "Error: " . mysqli_error($conn);
    }
    exit;
}

// অন্যান্য ফিল্ড আপডেট করার জন্য
if (isset($_POST['id'], $_POST['field'], $_POST['value'], $_POST['trackNumber'])) {
    $id = intval($_POST['id']);
    $field_name = $_POST['field']; // Store the field name in a variable
    $trackNumber = mysqli_real_escape_string($conn, $_POST['trackNumber']);
    $value = mysqli_real_escape_string($conn, $_POST['value']);

    // Map select/textarea names to DB columns
    $map = [
        "TdconfirmNon"   => "confirm",
        "TdorderReady"   => "orderReady",
        "TdcurrierDeliverd" => "currierDeliverd",
        "Tddelivery"     => "delivery",
        "TdcurrierName"  => "currierName",
        "Tdreceive"      => "receive",
        "Tdpaid"         => "paid"
    ];

    if (array_key_exists($field_name, $map)) { // Use $field_name here
        $column = $map[$field_name]; // Use $field_name here
        $sql = "UPDATE final_order_item SET `$column`='$value' WHERE track_number='$trackNumber'";
        if (mysqli_query($conn, $sql)) {
            echo "Updated successfully";
        } else {
            echo "Error: " . mysqli_error($conn);
        }

        // --- Corrected Logic ---
        // Check if the field being updated is 'Tddelivery' and the new value is 'ডেলিভার্ড' or 'ফেরত'
        if ($field_name === 'Tddelivery') {
            if ($value === 'ডেলিভার্ড') {
                mysqli_query($conn, "UPDATE final_order_item SET status='বিক্রয়' WHERE track_number='$trackNumber' AND status != 'রিটার্ণ'") or die(mysqli_error($conn));
            } elseif ($value === 'ফেরত') {
                mysqli_query($conn, "UPDATE final_order_item SET status='অবিক্রয়' WHERE track_number='$trackNumber' AND status != 'রিটার্ণ'") or die(mysqli_error($conn));
            }
        }
        // --- End of Corrected Logic ---

    } else {
        echo "Invalid field name.";
    }
}
?>