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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $conn->beginTransaction();

        $supplier_id      = $_POST['supplier_id'];
        $ref_no           = $_POST['ref_no'];
        $purchase_date    = $_POST['purchase_date'] . ' ' . date('H:i:s');
        $purchase_status  = 'purchase'; 
        $discount_type    = $_POST['discount_type'];
        $discount_amount  = $_POST['discount_amount'];
        $shipping_detail  = $_POST['shipping_detail'];
        $shipping_charges = $_POST['shipping_charges'];
        $note             = $_POST['note'];
        $amount           = $_POST['amount']; 
        $bank_id          = $_POST['bank_id'];
        $voucher_no       = $_POST['voucher_no'];

        $product_ids          = json_decode($_POST['product_id']);
        $quantities           = json_decode($_POST['quantity']);
        $pp_without_discounts = json_decode($_POST['pp_without_discount']);
        $discounts            = json_decode($_POST['discount_percent']);
        $purchase_prices      = json_decode($_POST['purchase_price']);
        $profit_margins       = json_decode($_POST['profit_margin']);
        $sell_prices          = json_decode($_POST['sell_price']);
        $fair_prices          = json_decode($_POST['fair_price']);
        $drums                = json_decode($_POST['drum']);
        $color_ids            = json_decode($_POST['color_id']);
        $size_ids             = json_decode($_POST['size_id']);
        $barcodes             = json_decode($_POST['barcode']);

        // 🟢 Default: empty string if no file uploaded
        $target_dir  = "purchase_upload/";
        $document_path = "";

        if (isset($_FILES["attach_document"]) && $_FILES["attach_document"]["size"] > 0) {
            $target_file = $target_dir . basename($_FILES["attach_document"]["name"]);
            $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

            if ($_FILES["attach_document"]["size"] > 500000) {
                throw new Exception("Sorry, your file is too large.");
            }

            if (!in_array($fileType, ["jpg","jpeg","png","gif","pdf"])) {
                throw new Exception("Sorry, only JPG, JPEG, PNG, GIF & PDF files are allowed.");
            }

            if (move_uploaded_file($_FILES["attach_document"]["tmp_name"], $target_file)) {
                $document_path = $target_file;
            }
        }

        $stmt = $conn->prepare("INSERT INTO purchase_lines (
            supplier_id, ref_no, purchase_date, purchase_status, discount_type, discount_amount,
            shipping_detail, shipping_charges, note, attach_document, product_id, quantity,
            pp_without_discount, discount_percent, purchase_price, profit_margin, sell_price, fair_price,
            drum, color_id, size_id, created_at, voucher_no
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

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

        foreach ($product_ids as $index => $product_id) {
            $size_id  = isset($size_ids[$index])  ? $size_ids[$index]  : '';
            $color_id = isset($color_ids[$index]) ? $color_ids[$index] : ''; 
            $barcode  = isset($barcodes[$index])  ? $barcodes[$index]  : '';

            $stmt->execute([
                $supplier_id,
                $ref_no,
                $purchase_date,
                $purchase_status,
                $discount_type,
                $discount_amount,
                $shipping_detail,
                $shipping_charges,
                $note,
                $document_path,
                $product_id,
                $quantities[$index],
                $pp_without_discounts[$index],
                $discounts[$index],
                $purchase_prices[$index],
                $profit_margins[$index],
                $sell_prices[$index],
                $fair_prices[$index],
                $drums[$index],
                $color_id,
                $size_id,
                $currentDate,
                $voucher_no
            ]);

            $stmt_update = $conn->prepare("UPDATE variations 
                SET default_purchase_price = ?, dpp_inc_tax = ?, profit_percent = ?, 
                    default_sell_price = ?, sell_price_inc_tax = ? 
                WHERE product_id = ?");

            $stmt_update->execute([
                $purchase_prices[$index],
                $purchase_prices[$index],
                $profit_margins[$index],
                $sell_prices[$index],
                $sell_prices[$index],
                $product_id
            ]);

            if (!empty($barcode)) {
                $stmt_barcode = $conn->prepare("UPDATE products SET barcode = ? WHERE id = ?");
                $stmt_barcode->execute([$barcode, $product_id]);
            }
        }

        if ($amount > 0) {
            $stmt_bank = $conn->prepare("INSERT INTO bank_debit_amount 
                (bank_id, supplier_id, ref_no, amount, note, date, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?)");

            $stmt_bank->execute([
                $bank_id,
                $supplier_id,
                $ref_no,
                $amount,
                $note,
                $purchase_date,
                'purchase'
            ]);
        }

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Data inserted and updated successfully']);

    } catch (Exception $e) {
        $conn->rollBack();
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
}
?>  
