<?php
require_once '../includes/auth.php';
require_once '../db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { die("Invalid Request"); }

$vendor_id           = (int)$_POST['vendor_id'];
$purchase_date       = $_POST['purchase_date'];
$supplier_invoice_no = trim($_POST['supplier_invoice_no'] ?? '');
$action              = $_POST['action'] ?? 'save'; // save | final
$round_off           = (float)($_POST['round_off'] ?? 0);

$product_ids        = $_POST['product_id']     ?? [];
$descriptions       = $_POST['description']    ?? [];
$batch_nos          = $_POST['batch_no']       ?? [];
$mrps               = $_POST['mrp']            ?? [];
$purchase_prices    = $_POST['purchase_price'] ?? [];
$quantities         = $_POST['quantity']       ?? [];
$gst_percents       = $_POST['gst_percent']    ?? [];
$disc_types         = $_POST['disc_type']      ?? [];
$disc_values        = $_POST['disc_value']     ?? [];
$overall_disc_type  = $_POST['overall_discount_type']  ?? '';
$overall_disc_value = (float)($_POST['overall_discount_value'] ?? 0);

if (!$vendor_id || !$purchase_date) die('Missing required fields');

$conn->begin_transaction();
try {
    // Generate PO No
    $datePart = date('Ymd', strtotime($purchase_date));
    $seq = str_pad(
        $conn->query("SELECT COUNT(*) FROM purchase_orders WHERE purchase_date='$purchase_date'")->fetch_row()[0] + 1,
        3, '0', STR_PAD_LEFT
    );
    $po_no  = "PO-$datePart-$seq";
    $status = ($action === 'final') ? 'final' : 'draft';

    // Insert PO header (totals updated below)
    $stmt = $conn->prepare("
        INSERT INTO purchase_orders (po_no, vendor_id, supplier_invoice_no, purchase_date, status, company_id)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->bind_param("sisssi", $po_no, $vendor_id, $supplier_invoice_no, $purchase_date, $status, $cid);
    $stmt->execute();
    $purchase_id = $stmt->insert_id;

    // Insert items
    $ins = $conn->prepare("
        INSERT INTO purchase_items
        (purchase_order_id, product_id, description, batch_no, mrp, purchase_price, selling_price,
         quantity, available_qty, gst_percent, disc_type, disc_value)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $total_taxable = 0;
    $total_gst     = 0;

    for ($i = 0; $i < count($product_ids); $i++) {
        if (empty($product_ids[$i]) ||
            ($quantities[$i] ?? 0) <= 0 || ($purchase_prices[$i] ?? 0) <= 0) continue;

        $pid      = (int)$product_ids[$i];
        $desc     = $descriptions[$i] ?? '';
        $batch    = !empty($batch_nos[$i]) ? $batch_nos[$i] : date('Ymd');
        $mrp      = (float)$mrps[$i];
        $pp       = (float)$purchase_prices[$i];
        $gst      = (float)$gst_percents[$i];
        $qty      = (float)$quantities[$i];
        $dt       = $disc_types[$i]  ?? '';
        $dv       = (float)($disc_values[$i] ?? 0);

        // Effective purchase price after per-line discount
        $eff_pp = $pp;
        if ($dt === 'percent') $eff_pp = $pp * (1 - $dv / 100);
        elseif ($dt === 'amount') $eff_pp = $pp - $dv;
        $eff_pp = max(0, $eff_pp);

        $selling_price = 0.0;
        $ins->bind_param("iissddddddsd",
            $purchase_id, $pid, $desc, $batch, $mrp, $pp, $selling_price, $qty, $qty, $gst, $dt, $dv);
        $ins->execute();

        $total_taxable += $eff_pp * $qty;
        $total_gst     += $eff_pp * $qty * $gst / 100;
    }

    $sub = $total_taxable + $total_gst;
    // Apply overall discount
    if ($overall_disc_type === 'percent') $sub = $sub * (1 - $overall_disc_value / 100);
    elseif ($overall_disc_type === 'amount') $sub = $sub - $overall_disc_value;
    $sub = max(0, $sub);

    $net = round($sub + $round_off, 2);
    $total_taxable = round($total_taxable, 2);
    $total_gst     = round($total_gst, 2);

    $conn->query("
        UPDATE purchase_orders
        SET total_amount=$total_taxable, gst_amount=$total_gst, net_amount=$net,
            round_off=$round_off, discount_type='$overall_disc_type', discount_value=$overall_disc_value
        WHERE id=$purchase_id
    ");

    // Stock movements on finalize
    if ($action === 'final') {
        $res = $conn->query("SELECT id, product_id, quantity FROM purchase_items WHERE purchase_order_id = $purchase_id");
        $smStmt = $conn->prepare("
            INSERT INTO stock_movements (product_id, purchase_item_id, type, quantity, reference_id, reference_type)
            VALUES (?, ?, 'IN', ?, ?, 'purchase')
        ");
        while ($m = $res->fetch_assoc()) {
            $piid = (int)$m['id']; $ppid = (int)$m['product_id']; $pqty = (int)$m['quantity'];
            $smStmt->bind_param("iiii", $ppid, $piid, $pqty, $purchase_id);
            $smStmt->execute();
        }
    }

    $conn->commit();

    header("Location: " . ($action === 'final' ? "view.php?id=$purchase_id" : "edit.php?id=$purchase_id&saved=1"));
    exit;

} catch (Exception $e) {
    $conn->rollback();
    die("Save failed: " . $e->getMessage());
}
