<?php
session_start();
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['mobile']) || !isset($_SESSION['otp'])) {
    echo json_encode(["status" => "error", "message" => "not_logged_in"]);
    exit;
}

include("configa.php");

$mobile = $_SESSION['mobile'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    // Arrays
    $product_names = $_POST['product_nameCard'] ?? [];
    $items = $_POST['item_inputCard'] ?? [];
    $gkss = $_POST['gksCard'] ?? [];
    $sellers = $_POST['sellerCard'] ?? [];
    $prices = $_POST['priceCard'] ?? [];
    $discounts = $_POST['discountCard'] ?? [];
    $quantityInputs = $_POST['quantityInputCard'] ?? [];
    $current_prices = $_POST['current_priceCard'] ?? [];

    // User & order info
    $first_name = mysqli_real_escape_string($conn, $_POST['first_name'] ?? '');
    $last_name = mysqli_real_escape_string($conn, $_POST['last_name'] ?? '');
    $mobile = mysqli_real_escape_string($conn, $_SESSION['mobile']);
    $division = mysqli_real_escape_string($conn, $_POST['division'] ?? '');
    $district = mysqli_real_escape_string($conn, $_POST['district'] ?? '');
    $upazila = mysqli_real_escape_string($conn, $_POST['upazila'] ?? '');
    $up = mysqli_real_escape_string($conn, $_POST['up'] ?? '');
    $address = mysqli_real_escape_string($conn, $_POST['address'] ?? '');
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method'] ?? '');

    $track_number = mysqli_real_escape_string($conn, $_POST['track_number'] ?? '');
    $discount_code = mysqli_real_escape_string($conn, $_POST['discount_code'] ?? '');
    $discount_present = mysqli_real_escape_string($conn, $_POST['discount_present'] ?? '');
    $total = mysqli_real_escape_string($conn, $_POST['total'] ?? '0');
    $delivery_charge = mysqli_real_escape_string($conn, $_POST['delivery_charge'] ?? '0');
    $grand_total = mysqli_real_escape_string($conn, $_POST['grand_total'] ?? '0');

    // ---------- Update login_gest ----------
    $stmtUpdate = $conn->prepare("UPDATE login_gest 
        SET first_name = ?, last_name = ?, division = ?, district = ?, upazila = ?, up = ?, address = ?
        WHERE mobile = ?");
    if (!$stmtUpdate) {
        echo json_encode(["status" => "error", "message" => "Prepare failed (update): " . $conn->error]);
        exit;
    }
    $stmtUpdate->bind_param("ssssssss", $first_name, $last_name, $division, $district, $upazila, $up, $address, $mobile);
    if (!$stmtUpdate->execute()) {
        echo json_encode(["status" => "error", "message" => "Execute failed (update): " . $stmtUpdate->error]);
        exit;
    }
    $stmtUpdate->close();

    // ---------- Insert into final_order_item ----------
    $sql = "INSERT INTO final_order_item (
        customerMobile, product_name, item, gks, seller, price,
        discount, quantity, current_price, discount_code, discount_present, track_number
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(["status" => "error", "message" => "Prepare failed (item): " . $conn->error]);
        exit;
    }
    $stmt->bind_param(
        "ssssssssssss",
        $mobile, $product_name, $item, $gks, $seller, $price,
        $discount, $quantity, $current_price, $discount_code, $discount_present, $track_number
    );

    foreach ($product_names as $index => $pname) {
        $product_name = mysqli_real_escape_string($conn, $pname);
        $item = mysqli_real_escape_string($conn, $items[$index] ?? '');
        $gks = mysqli_real_escape_string($conn, $gkss[$index] ?? '');
        $seller = mysqli_real_escape_string($conn, $sellers[$index] ?? '');
        $price = (int)($prices[$index] ?? 0);
        $discount = (int)($discounts[$index] ?? 0);
        $quantity = (int)($quantityInputs[$index] ?? 0);
        $current_price = (int)($current_prices[$index] ?? 0);
        if (!$stmt->execute()) {
            echo json_encode(["status" => "error", "message" => "Insert failed (item): " . $stmt->error]);
            exit;
        }
    }
    $stmt->close();

    // ---------- Insert into final_order_customer ----------
    $sql_customer = "INSERT INTO final_order_customer (
        first_name, last_name, mobile,
        division, district, upazila, up, address, discount_code, discount_present, track_number
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_customer = $conn->prepare($sql_customer);
    if (!$stmt_customer) {
        echo json_encode(["status" => "error", "message" => "Prepare failed (customer): " . $conn->error]);
        exit;
    }
    $stmt_customer->bind_param(
        "sssssssssss",
        $first_name, $last_name, $mobile,
        $division, $district, $upazila, $up, $address, $discount_code, $discount_present, $track_number
    );
    if (!$stmt_customer->execute()) {
        echo json_encode(["status" => "error", "message" => "Insert failed (customer): " . $stmt_customer->error]);
        exit;
    }
    $stmt_customer->close();

    // ---------- Insert into final_order_summary ----------
    $sql_summary = "INSERT INTO final_order_summary (
        track_number, discount_code, discount_present, total, delivery_charge, grand_total
    ) VALUES (?, ?, ?, ?, ?, ?)";
    $stmt_summary = $conn->prepare($sql_summary);
    if (!$stmt_summary) {
        echo json_encode(["status" => "error", "message" => "Prepare failed (summary): " . $conn->error]);
        exit;
    }
    $stmt_summary->bind_param(
        "ssssss",
        $track_number, $discount_code, $discount_present, $total, $delivery_charge, $grand_total
    );
    if ($stmt_summary->execute()) {
        // অস্থায়ী order_table থেকে ডিলিট
        $delete_sql = "DELETE FROM order_table WHERE customerMobile = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        if ($delete_stmt) {
            $delete_stmt->bind_param("s", $mobile);
            $delete_stmt->execute();
            $delete_stmt->close();
        }
    } else {
        echo json_encode(["status" => "error", "message" => "Insert failed (summary): " . $stmt_summary->error]);
        exit;
    }
    $stmt_summary->close();

    $_SESSION['has_order'] = true;

    // ---------- Success response ----------
    echo json_encode([
        "status" => "success",
        "message" => "অর্ডার সফলভাবে সাবমিট হয়েছে।",
        "track_number" => $track_number
    ]);
    exit;
}
?>
