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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!$conn) {
        die("Connection failed: " . mysqli_connect_error());
    }

    $sql = "INSERT INTO final_order_item 
    (category_picture, product_name, item, person, gks, seller, price, discount, current_price, size, weight, quantity, discount_code, discount_special, customerMobile, track_number) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = mysqli_prepare($conn, $sql);
    
    if ($stmt === false) {
        die("Error preparing statement: " . mysqli_error($conn));
    }
    
    $success = true;

    foreach ($_POST['product_name'] as $key => $val) {
        $quantity = $_POST['quantity'][$key] ?? 1;

        // **সার্ভার-সাইড ভ্যালিডেশন**
        if ($quantity < 0) {
            echo "❌ Error: Quantity cannot be a negative number.";
            $success = false;
            break; // Stop the loop if a negative value is found
        }

        // Assign values from the POST array
        $category_picture = $_POST['category_picture'][$key] ?? '';
        $product_name     = $_POST['product_name'][$key] ?? '';
        $item             = $_POST['item'][$key] ?? '';
        $person           = $_POST['person'][$key] ?? '';
        $gks              = $_POST['gks'][$key] ?? '';
        $seller           = $_POST['seller'][$key] ?? '';
        $price            = $_POST['price'][$key] ?? 0;
        $discount         = $_POST['discount'][$key] ?? 0;
        $current_price    = $_POST['current_price'][$key] ?? 0;
        $size             = $_POST['size'][$key] ?? '';
        $weight           = $_POST['weight'][$key] ?? '';
        $discount_code    = $_POST['discount_code'][$key] ?? '';
        $discount_special = $_POST['discount_special'][$key] ?? '';
        $mobile           = $_POST['mobile'] ?? '';
        $track_number     = $_POST['track_number'] ?? '';

        mysqli_stmt_bind_param(
            $stmt, 
            "ssssssssssssssss",
            $category_picture, 
            $product_name, 
            $item, 
            $person, 
            $gks, 
            $seller, 
            $price, 
            $discount, 
            $current_price, 
            $size, 
            $weight, 
            $quantity, 
            $discount_code, 
            $discount_special, 
            $mobile, 
            $track_number
        );
        
        if (!mysqli_stmt_execute($stmt)) {
            echo "❌ Error inserting product: " . mysqli_stmt_error($stmt);
            $success = false;
        }
    }

    mysqli_stmt_close($stmt);
    mysqli_close($conn);

    if ($success) {
        echo "✅ Product(s) inserted successfully!";
    }
}
?>