<?php 
include 'includes/config.php';
ini_set('display_errors', 1); 
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $customer_ids = $_POST['customer_id'] ?? [];
    $product_ids = $_POST['product_id'] ?? [];
    $product_codes = $_POST['product_code'] ?? [];
    $product_names = $_POST['product_name'] ?? [];
    $sale_taxs = $_POST['sale_tax'] ?? [];
    $categorys = $_POST['category'] ?? [];
    $date_sales = $_POST['date_sale'] ?? [];
    $units = $_POST['unit'] ?? [];
    $prices = $_POST['price'] ?? [];
    $sale_qtys = $_POST['sale_qty'] ?? [];
    $total_amounts = $_POST['total_amount'] ?? [];
    $net_cashs = $_POST['net_cash'] ?? [];
    $discounts = $_POST['discount'] ?? [];
    $order_taxs = $_POST['order_tax'] ?? [];
    $bank_id = intval($_POST['bank_id'] ?? 0);
    $advance_payment = $_POST['advance_payment'] ?? 0;
    $installment_amounts = $_POST['installment_amount'] ?? [];
    $installment_due_dates = $_POST['installment_due_date'] ?? [];
    $user_ids = $_POST['user_id'] ?? [];

    $guarantor1 = [
        'name' => $_POST['guarantor1_name'] ?? '',
        'father' => $_POST['guarantor1_father'] ?? '',
        'email' => $_POST['guarantor1_email'] ?? '',
        'phone1' => $_POST['guarantor1_phone1'] ?? '',
        'phone2' => $_POST['guarantor1_phone2'] ?? '',
        'address' => $_POST['guarantor1_address'] ?? '',
        'cnic' => $_POST['guarantor1_cnic'] ?? '',
        'note' => $_POST['guarantor1_note'] ?? '',
        'granted' => $_POST['guarantor1_granted'] ?? 0,
        'cnic_front' => $_FILES['guarantor1_cnic_front'] ?? null,
        'cnic_back' => $_FILES['guarantor1_cnic_back'] ?? null
    ];
    $guarantor2 = [
        'name' => $_POST['guarantor2_name'] ?? '',
        'father' => $_POST['guarantor2_father'] ?? '',
        'email' => $_POST['guarantor2_email'] ?? '',
        'phone1' => $_POST['guarantor2_phone1'] ?? '',
        'phone2' => $_POST['guarantor2_phone2'] ?? '',
        'address' => $_POST['guarantor2_address'] ?? '',
        'cnic' => $_POST['guarantor2_cnic'] ?? '',
        'note' => $_POST['guarantor2_note'] ?? '',
        'granted' => $_POST['guarantor2_granted'] ?? 0,
        'cnic_front' => $_FILES['guarantor2_cnic_front'] ?? null,
        'cnic_back' => $_FILES['guarantor2_cnic_back'] ?? null
    ];

    $create_on = date('Y-m-d H:i:s');

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $conn->prepare("SELECT MAX(invoice) AS max_invoice FROM stock_sale"); 
        $stmt->execute();
        $max_invoice = $stmt->fetch(PDO::FETCH_ASSOC)['max_invoice'] ?? null;
        $next_invoice = empty($max_invoice) ? "0000000001" : str_pad($max_invoice + 1, 10, "0", STR_PAD_LEFT);

        $invoice_total = array_sum(array_map('floatval', $total_amounts));
        $net_cash_input = floatval($net_cashs[0] ?? 0);
        $discount_input = floatval($discounts[0] ?? 0);
        $order_tax = floatval($order_taxs[0] ?? 0);
        $advance_payment = floatval($advance_payment ?? 0);
        $bank_id = intval($bank_id ?? 0);
        $is_installment = !empty($installment_amounts) && !empty($installment_due_dates);

        $total_after_discount = $invoice_total - $discount_input;

        if ($is_installment) {
            $net_cash_input = ($advance_payment > 0) ? $advance_payment : 0;
            $change_value = 0;
        } else {
            if ($net_cash_input > $total_after_discount) {
                $change_value = $net_cash_input - $total_after_discount;
                $net_cash_input = $total_after_discount;
            } else {
                $change_value = 0;
            }
        }

        $stmt_stock = $conn->prepare("
            INSERT INTO stock_sale 
            (invoice, customer_id, user_id, product_code, product_id, product_name, sale_tax, category, date_sale, unit, price, sale_qty, total_amount, net_cash, discount, order_tax, change_value, create_on)
            VALUES 
            (:invoice, :customer_id, :user_id, :product_code, :product_id, :product_name, :sale_tax, :category, :date_sale, :unit, :price, :sale_qty, :total_amount, :net_cash, :discount, :order_tax, :change_value, :create_on)
        ");

        foreach ($product_ids as $i => $pid) {
            $stmt_stock->execute([
                ':invoice' => $next_invoice, 
                ':customer_id' => $customer_ids[0] ?? 0, 
                ':user_id' => $user_ids[0] ?? 0,
                ':product_code' => $product_codes[$i] ?? '', 
                ':product_id' => $pid, 
                ':product_name' => $product_names[$i] ?? '',
                ':sale_tax' => floatval($sale_taxs[$i] ?? 0), 
                ':category' => $categorys[$i] ?? 0, 
                ':date_sale' => $date_sales[0] ?? date('Y-m-d'),
                ':unit' => $units[$i] ?? '', 
                ':price' => floatval($prices[$i] ?? 0), 
                ':sale_qty' => floatval($sale_qtys[$i] ?? 0), 
                ':total_amount' => floatval($total_amounts[$i] ?? 0),
                ':net_cash' => ($i === 0 ? $net_cash_input : 0), 
                ':discount' => ($i === 0 ? $discount_input : 0),
                ':order_tax' => $order_tax, 
                ':change_value' => ($i === 0 ? $change_value : 0), 
                ':create_on' => $create_on
            ]);
        }

        $deposit = $is_installment ? (($advance_payment > 0) ? $advance_payment : 0) : $net_cash_input;
        if ($deposit > 0) {
            $stmt = $conn->prepare("
                INSERT INTO cash_deposit 
                (invoice, user_id, amount, status, date_deposit, bank_id, create_on) 
                VALUES 
                (:invoice, :user_id, :amount, 'customer', :date_deposit, :bank_id, :create_on)
            ");
            $stmt->execute([
                ':invoice' => $next_invoice,
                ':user_id' => $customer_ids[0] ?? 0,
                ':amount' => $deposit,
                ':date_deposit' => $date_sales[0] ?? date('Y-m-d'),
                ':bank_id' => $bank_id,
                ':create_on' => $create_on
            ]);
        }

        if ($is_installment) {
            $stmt_inst = $conn->prepare("
                INSERT INTO customer_installments 
                (invoice, customer_id, installment_no, amount, due_date, status, paid_date, create_on)
                VALUES 
                (:invoice, :customer_id, :installment_no, :amount, :due_date, 'pending', NULL, :create_on)
            ");
            foreach ($installment_amounts as $idx => $amt) {
                $amt = floatval($amt);
                if ($amt <= 0) continue;
                $stmt_inst->execute([
                    ':invoice' => $next_invoice,
                    ':customer_id' => $customer_ids[0] ?? 0,
                    ':installment_no' => $idx + 1,
                    ':amount' => $amt,
                    ':due_date' => $installment_due_dates[$idx] ?? date('Y-m-d'),
                    ':create_on' => $create_on
                ]);
            }
        }

        $uploadDir = 'uploads/guarantors/' . $next_invoice . '/';
        if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

        $stmt_guar = $conn->prepare("
            INSERT INTO sale_guarantors 
            (invoice, customer_id, type, name, father_name, email, phone1, phone2, address, cnic, note, granted, cnic_front, cnic_back, create_on)
            VALUES 
            (:invoice, :customer_id, :type, :name, :father_name, :email, :phone1, :phone2, :address, :cnic, :note, :granted, :cnic_front, :cnic_back, :create_on)
        ");

        foreach (['guarantor1' => $guarantor1, 'guarantor2' => $guarantor2] as $type => $g) {
            if (empty($g['name'])) continue;

            $cnicFrontPath = $g['cnic_front'] ? $uploadDir . basename($g['cnic_front']['name']) : null;
            $cnicBackPath  = $g['cnic_back'] ? $uploadDir . basename($g['cnic_back']['name']) : null;

            if ($g['cnic_front'] && move_uploaded_file($g['cnic_front']['tmp_name'], $cnicFrontPath)) {}
            if ($g['cnic_back'] && move_uploaded_file($g['cnic_back']['tmp_name'], $cnicBackPath)) {}

            $stmt_guar->execute([
                ':invoice' => $next_invoice, 
                ':customer_id' => $customer_ids[0] ?? 0, 
                ':type' => $type, 
                ':name' => $g['name'],
                ':father_name' => $g['father'], 
                ':email' => $g['email'], 
                ':phone1' => $g['phone1'], 
                ':phone2' => $g['phone2'],
                ':address' => $g['address'], 
                ':cnic' => $g['cnic'], 
                ':note' => $g['note'], 
                ':granted' => $g['granted'],
                ':cnic_front' => $cnicFrontPath, 
                ':cnic_back' => $cnicBackPath, 
                ':create_on' => $create_on
            ]);
        }

        echo "success"; 
        exit;

    } catch (PDOException $e) { 
        echo "error: " . $e->getMessage(); 
        exit; 
    }

    $conn = null;
}
?>
