<?php
include 'includes/config.php';

function getNewInvoiceNumber($conn) {
    // Query to get the last invoice number
    $query = $conn->prepare("SELECT invoice FROM manual_stock_sale ORDER BY invoice DESC LIMIT 1");
    $query->execute();
    $lastInvoice = $query->fetchColumn();

    if ($lastInvoice) {
        // Extract the numeric part and increment it
        $newInvoiceNumber = str_pad((int)$lastInvoice + 1, 10, '0', STR_PAD_LEFT);
    } else {
        // If no invoice exists, start with 0000000001
        $newInvoiceNumber = '0000000001';
    }

    return $newInvoiceNumber;
}

if (isset($_POST['customer_id'])) {
    $customer_id = $_POST['customer_id'];
    $pay_term = $_POST['pay_term'];
    $pay_term_status = $_POST['pay_term_status'];
    $date_sale = $_POST['date_sale'];
    $saleman = $_POST['saleman'];
    $sale_status = $_POST['sale_status'];
    $discount_type = $_POST['discount_type'];
    $discount = $_POST['discount'];
    $shipping_detail = $_POST['shipping_detail'];
    $shipping_address = $_POST['shipping_address'];
    $shipping_charges = $_POST['shipping_charges'];
    $shipping_status = $_POST['shipping_status'];
    $delivered_to = $_POST['delivered_to'];
    $receive_amount = $_POST['receive_amount'];
    $payment_method = $_POST['payment_method'];

    $products = $_POST['products'];

    $invoice_number = getNewInvoiceNumber($conn);

    try {
        $conn->beginTransaction();

        foreach ($products as $product) {
            $product_id = ''; 
            $product_name = $product['product_name'];
            $unit = '';
            $quantity = $product['quantity'];
            $price = $product['price'];
            $total_amount = $quantity * $price;

            // Insert into manual_stock_sale table
            $query = $conn->prepare("
                INSERT INTO manual_stock_sale (
                    product_id, 
                    invoice, 
                    customer_id, 
                    date_sale,
                    saleman,
                    product_code, 
                    product_name, 
                    unit, 
                    price, 
                    sale_qty, 
                    total_amount, 
                    discount, 
                    discount_type,
                    shipping_charges, 
                    shipping_detail, 
                    shipping_address, 
                    shipping_status, 
                    delivered_to, 
                    sale_status, 
                    pay_term, 
                    pay_term_status,
                    receive_amount
                ) VALUES (
                    ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
                )
            ");
            $query->execute([
                $product_id, 
                $invoice_number, 
                $customer_id, 
                $date_sale,
                $saleman,
                $product_id, 
                $product_name, 
                $unit, 
                $price, 
                $quantity, 
                $total_amount, 
                $discount, 
                $discount_type,
                $shipping_charges, 
                $shipping_detail, 
                $shipping_address, 
                $shipping_status, 
                $delivered_to, 
                $sale_status, 
                $pay_term, 
                $pay_term_status,
                $receive_amount
            ]);
        }

        // If receive_amount is greater than 0, insert into cash_deposit table
        if ($receive_amount > 0) {
            $query = $conn->prepare("INSERT INTO cash_deposit_manually (
                    user_id, 
                    amount, 
                    status, 
                    payment_status, 
                    date_deposit,
                    invoice
                ) VALUES (
                    ?, ?, 'customer', ?, NOW(), ?
                )
            ");
            $query->execute([
                $customer_id, 
                $receive_amount, 
                $payment_method,
                $invoice_number
            ]);
        }

        // Commit the transaction
        $conn->commit();

        // Return 'success' if all inserts are successful
        echo 'success';

    } catch (Exception $e) {
        // Rollback the transaction if any insert fails
        $conn->rollBack();
        echo 'Error: ' . $e->getMessage();
    }
} else {
    echo 'No data received.';
}
?>
