<?php
/**
 * ajax_actions_for_assypu.php  (office / Assypu-admin AJAX endpoints)
 * =====================================================================
 * CHANGES FROM ORIGINAL:
 *
 *   1. recalculateMachineDatesforassypu() removed — this file's copy was
 *      the one with the stale `end_date >= today` filter instead of
 *      `finished = 0` (see assypu_scheduler_lib.php header for the full
 *      writeup — this was the more consequential of the family-pattern
 *      bugs here, since it lived in the reschedule engine itself, not
 *      just a priority-renumbering query). Now uses
 *      assypu_fullReschedule().
 *
 *   2. select_order_for_assypu's inline shift-walking loop (a 4th copy
 *      of the same scheduling primitive) replaced with
 *      assypu_scheduleNewTaskInline().
 *
 *   3. update_assypu_task_priority: FIX — both the old-machine
 *      renumbering query and the new-machine priority-shift query
 *      filtered `end_date >= today`, the same stale-row bug found in
 *      CNC's/PU's/VAC's equivalent endpoints. Now filters `finished = 0`.
 *
 *   4. add_assypu_break: FIX — `$priority` (meant to place the break
 *      ahead of the selected "highest priority" task) was computed and
 *      then never used; the insert always used `$new_priority`
 *      (MAX+1), silently appending to the back of the queue. The
 *      follow-up priority-shift had no condition beyond machine_id at
 *      all, bumping every row regardless of position. No reschedule call
 *      at all. All three fixed, same pattern as the other three modules.
 *
 *   5. start_machine_breakdown / stop_machine_breakdown now mirror into
 *      assypu_machine_breakdown_log, the table the dashboard's
 *      assypu_isMachineInBreakdown() check actually reads — previously
 *      a breakdown started here was invisible to the tablet. stop now
 *      also calls assypu_fullReschedule() (previously never did).
 *
 *   6. get_machine_breakdown_status now reads assypu_machine_breakdown_log,
 *      consistent with the shared source of truth.
 *
 *   7. get_assypu_task_details: FIX — `$data['is_late']` was computed
 *      against `$row['manufacture_end_date']` / `$row['end_date']`, but
 *      `$row` was never set in this handler (it's a copy-paste leftover
 *      — the fetched row is `$data`, not `$row`). `empty($row[...])` on
 *      an undefined variable is always true, so `is_late` could never
 *      become `true`. Changed to reference `$data`.
 *
 *   8. markBreakdownAffectedWorkOrders() removed from this file — now
 *      the shared assypu_markBreakdownAffectedWorkOrders().
 * =====================================================================
 */
include("../../../include/startup.php");
require_once __DIR__ . '/assypu_scheduler_lib.php';

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

/* =====================================================================
 * select_order_for_assypu
 * ===================================================================== */
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'select_order_for_assypu') {

    $json_data   = $_REQUEST['work_orders'];
    $work_orders = json_decode($json_data, true);

    $inserted           = false;
    $processed_machines = [];
    $shiftsByDay = assypu_getShiftsByDay($conn);

    foreach ($work_orders as $item) {
        $id            = (int) $item['id'];
        $work_order_id = (int) $item['work_order_id'];
        $part_id       = (int) $item['part_id'];
        $machine_id    = (int) $item['machine_id'];

        $processed_machines[$machine_id] = true;

        $selectQuery = "
            SELECT part_id, id, parent_ids, end_date, quantity, product_name, total_hours, set_id
            FROM manufacture_machine_table WHERE id = $id";
        $result = $conn->query($selectQuery);

        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();

            $quantity      = (int) $row['quantity'];
            $manuf_id      = (int) $row['id'];
            $product_name  = $row['product_name'];
            $total_hoursss = $row['total_hours'];
            $set_id        = $row['set_id'];
            $setup_hours   = 0;

            if ($set_id > 0) {
                $query_route = "SELECT operation_time, parts_per_operation, set_time, machine_high_priority FROM set_route_details WHERE set_id = $set_id";
            } else {
                $query_route = "SELECT operation_time, parts_per_operation, set_time, machine_high_priority FROM route_details WHERE item_id = $part_id";
            }
            $result_route = $conn->query($query_route);

            if ($result_route && $result_route->num_rows > 0) {
                $row_route = $result_route->fetch_assoc();
                $set_time = $row_route['set_time'];
                [$hours, $minutes, $seconds] = explode(':', $set_time);
                $setup_hours = $hours + ($minutes / 60) + ($seconds / 3600);

                if (!empty($row_route['operation_time'])) {
                    [$h, $m, $s] = explode(":", $row_route['operation_time']);
                    $operation_time = ($h * 60) + $m + ($s / 60);
                } else {
                    $operation_time = 1;
                }
                $parts_per_operation = (!empty($row_route['parts_per_operation']) && $row_route['parts_per_operation'] > 0)
                    ? (float) $row_route['parts_per_operation'] : 1;
                $cycle = (int) round($operation_time / $parts_per_operation);
            } else {
                $cycle = 1;
            }
            $total_hours = $total_hoursss + $setup_hours;

            $query_priority = "SELECT MAX(priority) AS priority FROM assypu_machine_table WHERE machine_id = $machine_id";
            $result_priority = mysqli_query($conn, $query_priority);
            if ($result_priority && mysqli_num_rows($result_priority) > 0) {
                $rowp = mysqli_fetch_assoc($result_priority);
                $currentPriority = $rowp['priority'] ?? 0;
                $new_priority = $currentPriority + 1;
            } else {
                $new_priority = 1;
            }

            // FIX: was a 4th inline copy of the shift-walking loop; now
            // the shared primitive every other scheduling path uses.
            $scheduleData = assypu_scheduleNewTaskInline($conn, $total_hours, $shiftsByDay);
            $startStr = $scheduleData['start_date'];
            $endStr   = $scheduleData['end_date'];
            $firstShiftUsed = mysqli_real_escape_string($conn, (string) $scheduleData['shift_ids']);
            $remainingHoursStr = mysqli_real_escape_string($conn, $scheduleData['remaining_hours']);

            $insertQuery = "
                INSERT INTO assypu_machine_table
                (machine_id, manuf_id, work_order_id, part_id, end_date, start_date, quantity, shift_ids, product_name, total_hours, total_hours_update, setup_hours, cycle, set_id, priority, remaing_hours)
                VALUES (
                    $machine_id, $manuf_id, $work_order_id, $part_id,
                    '$endStr', '$startStr', $quantity, '$firstShiftUsed', '$product_name',
                    '$total_hours', '$total_hoursss', '$setup_hours', '$cycle', '$set_id', '$new_priority', '$remainingHoursStr'
                )";

            if ($conn->query($insertQuery)) {
                $inserted = true;
                $conn->query("UPDATE manufacture_machine_table SET in_scheduler_check = 1 WHERE id = $id");
            }
        }
    }

    foreach (array_keys($processed_machines) as $machine_id) {
        assypu_fullReschedule($conn, $machine_id);
    }

    echo json_encode($inserted
        ? ['status' => 'success']
        : ['status' => 'failed', 'message' => 'No rows inserted']);
    exit;
}

/* =====================================================================
 * update_assypu_task_priority — drag and drop
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update_assypu_task_priority') {

    $taskId       = intval($_REQUEST['task_id']);
    $newMachineId = intval($_REQUEST['new_machine_id']);
    $leftNeighborPriority = isset($_REQUEST['left_neighbor_priority']) ? intval($_REQUEST['left_neighbor_priority']) : null;

    $draggedTask = $conn->query("SELECT * FROM assypu_machine_table WHERE id = $taskId")->fetch_assoc();
    if (!$draggedTask) {
        echo json_encode(['status' => 'error', 'message' => 'Task not found']);
        exit;
    }

    // FIX: filters `finished = 0`, not `end_date >= today` -- a stale
    // end_date previously kept a row at its old priority number while
    // everything else got renumbered around it.
    $originalTasks = [];
    $originalResult = mysqli_query($conn, "
        SELECT id, priority FROM assypu_machine_table
        WHERE machine_id = {$draggedTask['machine_id']} AND finished = 0
        ORDER BY priority
    ");
    while ($row = mysqli_fetch_assoc($originalResult)) $originalTasks[] = $row;

    $newTasks = [];
    $newResult = mysqli_query($conn, "
        SELECT id, priority FROM assypu_machine_table
        WHERE machine_id = $newMachineId AND finished = 0
        ORDER BY priority
    ");
    while ($row = mysqli_fetch_assoc($newResult)) $newTasks[] = $row;

    $cases = [];
    $newPriority = 1;
    foreach ($originalTasks as $task) {
        if ($task['id'] != $taskId) {
            $cases[] = "WHEN {$task['id']} THEN $newPriority";
            $newPriority++;
        }
    }
    if (!empty($cases)) {
        $ids = implode(',', array_column($originalTasks, 'id'));
        mysqli_query($conn, "
            UPDATE assypu_machine_table
            SET priority = CASE id " . implode(' ', $cases) . " END
            WHERE id IN ($ids)
        ");
    }

    $insertPriority = ($leftNeighborPriority !== null) ? $leftNeighborPriority + 1 : 1;

    mysqli_query($conn, "
        UPDATE assypu_machine_table
        SET priority = priority + 1
        WHERE machine_id = $newMachineId
          AND finished = 0
          AND priority >= $insertPriority
    ");

    mysqli_query($conn, "
        UPDATE assypu_machine_table SET machine_id = $newMachineId, priority = $insertPriority WHERE id = $taskId
    ");

    if ($draggedTask['machine_id'] != $newMachineId) {
        assypu_fullReschedule($conn, $draggedTask['machine_id']);
        assypu_fullReschedule($conn, $newMachineId);
    } else {
        assypu_fullReschedule($conn, $newMachineId);
    }

    echo json_encode(['status' => 'success', 'message' => 'Task priorities and dates updated successfully']);
    exit;
}

/* =====================================================================
 * add_assypu_break — admin Gantt "Add Break" button
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'add_assypu_break') {

    $machineId = intval($_REQUEST['machine_id']);
    $duration  = floatval($_REQUEST['duration']);
    $reason    = mysqli_real_escape_string($conn, $_REQUEST['reason']);
    $highestPriority = isset($_REQUEST['highest_priority']) ? intval($_REQUEST['highest_priority']) : 0;

    if ($machineId <= 0 || $duration < 0.5 || $duration > 10) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid input values']);
        exit;
    }

    // FIX: this is the priority the break should actually land at --
    // just ahead of whichever task the caller flagged as currently
    // highest priority. Previously computed and then discarded; the
    // insert always used MAX(priority)+1 (appending to the back).
    $priority = $highestPriority ? max(1, $highestPriority) : 1;

    mysqli_autocommit($conn, false);
    $error = false;

    $result = mysqli_query($conn, "SELECT MAX(end_date) as last_end_date FROM assypu_machine_table WHERE machine_id = $machineId");
    if (!$result) {
        $error = true;
    } else {
        $row = mysqli_fetch_assoc($result);
        $startDate = $row['last_end_date'] ? $row['last_end_date'] : date('Y-m-d H:i:s');
        $endDate   = date('Y-m-d H:i:s', strtotime($startDate) + ($duration * 3600));

        $startDay = date('Y-m-d', strtotime($startDate));
        $endDay   = date('Y-m-d', strtotime($endDate));
        $remainingHours = $duration;
        if ($startDay != $endDay) {
            $endOfFirstDay = date('Y-m-d 23:59:59', strtotime($startDate));
            $firstDayHours = (strtotime($endOfFirstDay) - strtotime($startDate)) / 3600;
            $remainingHours = $duration - $firstDayHours;
        }

        // FIX: scoped to the rows that actually need to move, instead of
        // every row on the machine regardless of position.
        if (!mysqli_query($conn, "
            UPDATE assypu_machine_table SET priority = priority + 1
            WHERE machine_id = $machineId AND priority >= $priority
        ")) {
            $error = true;
        }

        if (!$error) {
            $insertQuery = "INSERT INTO assypu_machine_table
                (machine_id, start_date, end_date, total_hours, remaing_hours, is_break, break_reason, priority)
                VALUES ($machineId, '$startDate', '$endDate', $duration, $remainingHours, 1, '$reason', $priority)";
            if (!mysqli_query($conn, $insertQuery)) {
                $error = true;
            }
        }
    }

    if ($error) {
        mysqli_rollback($conn);
        echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]);
        mysqli_autocommit($conn, true);
        exit;
    }

    mysqli_commit($conn);
    mysqli_autocommit($conn, true);

    // FIX: previously never called at all for this endpoint.
    assypu_fullReschedule($conn, $machineId);

    echo json_encode(['status' => 'success']);
    exit;
}

/* =====================================================================
 * start_machine_breakdown / stop_machine_breakdown
 * Mirrors into assypu_machine_breakdown_log so the tablet's
 * assypu_isMachineInBreakdown() check sees it immediately.
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'start_machine_breakdown') {
    $machine_id = intval($_REQUEST['machine_id']);
    $breakdown_reason_id = mysqli_real_escape_string($conn, $_REQUEST['breakdown_reason']);
    $now = date('Y-m-d H:i:s');

    $reason_result = mysqli_query($conn, "SELECT code FROM keycode_table WHERE id = '$breakdown_reason_id'");
    $reason_text = ($reason_result && mysqli_num_rows($reason_result) > 0)
        ? mysqli_fetch_assoc($reason_result)['code'] : 'Unknown Reason';

    mysqli_query($conn, "UPDATE machine_breakdown SET is_active = 0, breakdown_end = '$now',
        breakdown_hours = TIMESTAMPDIFF(MINUTE, breakdown_start, '$now') / 60, updated_at = '$now'
        WHERE machine_id = $machine_id AND is_active = 1");

    mysqli_query($conn, "INSERT INTO machine_breakdown (machine_id, breakdown_start, breakdown_reason, is_active, created_at, updated_at)
        VALUES ($machine_id, '$now', '$reason_text', 1, '$now', '$now')");

    assypu_markBreakdownAffectedWorkOrders($conn, $machine_id, $now);

    // Mirror into the tablet's source-of-truth table.
    mysqli_query($conn, "
        INSERT INTO assypu_machine_breakdown_log
        (work_order_id, part_id, machine_id, engineer_id, assypu_machine_table_id, breakdown_reason,
         breakdown_duration, ok_count_at_breakdown, remaining_quantity, status, created_at)
        VALUES (0, 0, $machine_id, 0, 0, '" . mysqli_real_escape_string($conn, $reason_text) . "', 0, 0, 0, 'active', '$now')
    ");

    echo json_encode(['status' => 'success']);
    exit;

} else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'stop_machine_breakdown') {
    $machine_id = intval($_POST['machine_id']);
    $now = date('Y-m-d H:i:s');

    mysqli_query($conn, "UPDATE machine_breakdown SET is_active = 0, breakdown_end = '$now',
        breakdown_hours = TIMESTAMPDIFF(MINUTE, breakdown_start, '$now') / 60, updated_at = '$now'
        WHERE machine_id = $machine_id AND is_active = 1");

    mysqli_query($conn, "UPDATE assypu_machine_table SET is_breakdown_affected = 0 WHERE machine_id = $machine_id AND is_breakdown_affected = 1");

    $lastLog = mysqli_fetch_assoc(mysqli_query($conn, "
        SELECT * FROM assypu_machine_breakdown_log WHERE machine_id = $machine_id AND status = 'active' ORDER BY id DESC LIMIT 1
    "));
    if ($lastLog) {
        mysqli_query($conn, "
            INSERT INTO assypu_machine_breakdown_log
            (work_order_id, part_id, machine_id, engineer_id, assypu_machine_table_id, breakdown_reason,
             breakdown_duration, ok_count_at_breakdown, remaining_quantity, status, created_at)
            VALUES ({$lastLog['work_order_id']}, {$lastLog['part_id']}, $machine_id, {$lastLog['engineer_id']}, {$lastLog['assypu_machine_table_id']},
                    {$lastLog['breakdown_reason']}, {$lastLog['breakdown_duration']}, {$lastLog['ok_count_at_breakdown']},
                    {$lastLog['remaining_quantity']}, 'completed', '$now')
        ");
    }

    // FIX: this endpoint never rescheduled at all before.
    assypu_fullReschedule($conn, $machine_id);

    echo json_encode(['status' => 'success']);
    exit;

} else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_machine_breakdown_status') {
    // FIX: reads assypu_machine_breakdown_log now, consistent with the
    // shared source of truth.
    $sql = "SELECT ab.*, sd.resource_code AS machine_name
            FROM assypu_machine_breakdown_log ab
            LEFT JOIN station_detail_table sd ON ab.machine_id = sd.id
            ORDER BY ab.created_at DESC LIMIT 10";
    $res = mysqli_query($conn, $sql);
    $data = [];
    while ($row = mysqli_fetch_assoc($res)) $data[] = $row;
    echo json_encode(['status' => 'success', 'data' => $data]);
    exit;
}

/* =====================================================================
 * get_assypu_task_details
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_assypu_task_details') {

    $task_id = mysqli_real_escape_string($conn, $_REQUEST['task_id']);
    $work_order_id = mysqli_real_escape_string($conn, $_REQUEST['work_order_id']);

    $query = "SELECT
        mmt.machine_id AS task, mmt.id as task_id, wo.work_order_no, mmt.part_id, mmt.setup_hours,
        mmt.priority, mmt.total_hours AS hours_to_schedule, mmt.total_hours, mmt.work_order_id,
        mmt.product_name, mmt.quantity, mmt.set_id, won.work_order_name, mmt.shift_ids AS shift_name,
        DATE(mmt.start_date) AS start_date, DATE(mmt.end_date) AS end_date, TIME(mmt.start_date) AS start_time,
        mmt.is_break, mmt.break_reason, mmt.is_breakdown_affected, mmt.breakdown_hours,
        mb.id as breakdown_id, mb.breakdown_reason as machine_breakdown_reason,
        m.end_date as manufacture_end_date, m.description as manufacture_description,
        im.part_number as parent_part_number,
        GROUP_CONCAT(DISTINCT wocr.work_order_no ORDER BY wocr.work_order_no SEPARATOR ', ') as customer_order_nos
    FROM assypu_machine_table mmt
    LEFT JOIN work_order wo ON mmt.work_order_id = wo.id
    LEFT JOIN work_order_name won ON mmt.work_order_id = won.work_order_id AND mmt.part_id = won.part_id
    LEFT JOIN machine_breakdown mb ON mmt.machine_id = mb.machine_id AND mb.is_active = 1
    LEFT JOIN (
        SELECT m1.part_id, m1.work_order_id, m1.end_date, m1.description, m1.parent_ids
        FROM manufacture_machine_table m1
        INNER JOIN (SELECT part_id, work_order_id, MAX(end_date) as max_end_date FROM manufacture_machine_table GROUP BY part_id, work_order_id) m2
          ON m1.part_id = m2.part_id AND m1.work_order_id = m2.work_order_id AND m1.end_date = m2.max_end_date
    ) m ON mmt.part_id = m.part_id AND mmt.work_order_id = m.work_order_id
    LEFT JOIN item_management im ON m.parent_ids = im.id
    LEFT JOIN work_order_customer_ref_mapping wocr ON mmt.work_order_id = wocr.work_order_id
    WHERE mmt.id = '$task_id'
    LIMIT 1";

    $result = mysqli_query($conn, $query);

    if ($result && mysqli_num_rows($result) > 0) {
        $data = mysqli_fetch_assoc($result);

        if ($data['set_id'] != 0) {
            $route_query = "SELECT route_desc FROM set_route_details WHERE set_id = '{$data['set_id']}' LIMIT 1";
        } else {
            $route_query = "SELECT route_desc FROM route_details WHERE item_id = '{$data['part_id']}' LIMIT 1";
        }
        $route_result = mysqli_query($conn, $route_query);
        $data['route_desc'] = ($route_result && mysqli_num_rows($route_result) > 0) ? mysqli_fetch_assoc($route_result)['route_desc'] : '-';

        // FIX: was comparing $row['manufacture_end_date']/$row['end_date']
        // — $row was never set in this handler (copy-paste leftover; the
        // fetched row is $data). empty() on an undefined variable is
        // always true, so is_late could never become true. Now compares
        // $data against itself correctly.
        $data['is_late'] = (!empty($data['manufacture_end_date']) && $data['end_date'] > $data['manufacture_end_date']);

        $ppRes = mysqli_query($conn, "
            SELECT customer_reff, GROUP_CONCAT(DISTINCT RefSalesCode ORDER BY RefSalesCode SEPARATOR ', ') AS RefSalesCode
            FROM production_planning WHERE work_order_id = " . intval($work_order_id)
        );
        $ppRow = mysqli_fetch_assoc($ppRes);
        $customer_reff = $ppRow['customer_reff'] ?? '';
        $data['customer_code'] = utility::getTableFieldById("client_management", "customer_code", "id", $customer_reff);
        $data['RefSalesCode']  = $ppRow['RefSalesCode'] ?? '';

        echo json_encode(['success' => true, 'data' => $data]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Task not found']);
    }
    exit;
}

/* =====================================================================
 * update_assypu_task
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'update_assypu_task') {
    $task_id = mysqli_real_escape_string($conn, $_POST['task_id']);
    $priority = mysqli_real_escape_string($conn, $_POST['priority']);
    $machine_id = mysqli_real_escape_string($conn, $_POST['machine_id']);
    $setup_hours = mysqli_real_escape_string($conn, $_POST['setup_hours']);
    $total_hours = mysqli_real_escape_string($conn, $_POST['total_hours']);
    $start_date = mysqli_real_escape_string($conn, $_POST['start_date']);
    $quantity = mysqli_real_escape_string($conn, $_POST['quantity']);

    $update_query = "UPDATE assypu_machine_table SET
        priority = '$priority', machine_id = '$machine_id', setup_hours = '$setup_hours',
        total_hours = '$total_hours', start_date = '$start_date', quantity = '$quantity', updated_at = NOW()
        WHERE id = '$task_id'";

    if (mysqli_query($conn, $update_query)) {
        $result = mysqli_query($conn, "SELECT id, priority FROM assypu_machine_table WHERE machine_id = '$machine_id' AND finished = 0 ORDER BY priority");
        $new_priority = 1;
        while ($row = mysqli_fetch_assoc($result)) {
            mysqli_query($conn, "UPDATE assypu_machine_table SET priority = $new_priority WHERE id = {$row['id']}");
            $new_priority++;
        }
        assypu_fullReschedule($conn, $machine_id);
        echo json_encode(['success' => true, 'message' => 'Work order updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update work order: ' . mysqli_error($conn)]);
    }
    exit;
}

/* =====================================================================
 * delete_assypu_task
 * ===================================================================== */
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'delete_assypu_task') {
    $task_id = mysqli_real_escape_string($conn, $_REQUEST['task_id']);
    $work_order_id = mysqli_real_escape_string($conn, $_REQUEST['work_order_id']);
    $part_id = mysqli_real_escape_string($conn, $_REQUEST['part_id']);

    $machine_result = mysqli_query($conn, "SELECT machine_id FROM assypu_machine_table WHERE id = '$task_id' LIMIT 1");
    $machine_data = mysqli_fetch_assoc($machine_result);
    $machine_id = $machine_data['machine_id'];

    $delete_query = "DELETE FROM assypu_machine_table WHERE id = '$task_id'";
    if (mysqli_query($conn, $delete_query)) {
        $updateQuery = "UPDATE manufacture_machine_table SET in_scheduler_check = 0 WHERE work_order_id = '$work_order_id' AND part_id = '$part_id'";
        $conn->query($updateQuery);
        assypu_fullReschedule($conn, $machine_id);
        echo json_encode(['success' => true, 'message' => 'Work order deleted successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete work order: ' . mysqli_error($conn)]);
    }
    exit;
}
?>