<?php
include 'auth_check.php';

if (!isAdmin()) {
    header("Location: sale.php");
    exit();
}

$message = '';
$messageClass = 'success-box';
$date = date('Y-m-d');
$time = date('H:i:s');
$user = $_SESSION['name'];

function insertCreditPurchasing($conn, $stockId, $product_name, $supplier, $invoice_number, $qty, $unit, $total, $date, $time, $user) {
    $status = 'Pending';
    $paid = 0;
    $pending = $total;

    $stmt = $conn->prepare("INSERT INTO credit_puraching (stock_id, product_name, supplier, invoice_number, purchased_qty, unit, total_amount, paid_amount, pending_amount, payment_status, purchase_date, purchase_time, entered_date, entered_time, entered_user) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    $stmt->bind_param("isssdsdddssssss", $stockId, $product_name, $supplier, $invoice_number, $qty, $unit, $total, $paid, $pending, $status, $date, $time, $date, $time, $user);
    $stmt->execute();
}

function updateLatestCreditPurchasingRecord($conn, $stockId, $oldInvoiceNumber, $product_name, $supplier, $invoice_number, $qty, $unit, $total, $date, $time, $user) {
    $selectSql = "SELECT id, paid_amount FROM credit_puraching WHERE stock_id = ?";
    if ($oldInvoiceNumber !== '') {
        $selectSql .= " AND invoice_number = ?";
    }
    $selectSql .= " ORDER BY id DESC LIMIT 1";

    $stmt = $conn->prepare($selectSql);
    if ($oldInvoiceNumber !== '') {
        $stmt->bind_param("is", $stockId, $oldInvoiceNumber);
    } else {
        $stmt->bind_param("i", $stockId);
    }
    $stmt->execute();
    $res = $stmt->get_result();

    if ($res && $res->num_rows > 0) {
        $row = $res->fetch_assoc();
        $existingPaid = (float)$row['paid_amount'];
        $newPending = $total - $existingPaid;
        if ($newPending < 0) {
            $newPending = 0;
        }
        $paymentStatus = $newPending <= 0 ? 'Paid' : 'Pending';

        $up = $conn->prepare("UPDATE credit_puraching SET stock_id=?, product_name=?, supplier=?, invoice_number=?, purchased_qty=?, unit=?, total_amount=?, pending_amount=?, payment_status=?, purchase_date=?, purchase_time=?, entered_date=?, entered_time=?, entered_user=? WHERE id=?");
        $up->bind_param(
            "isssdsddssssssi",
            $stockId,
            $product_name,
            $supplier,
            $invoice_number,
            $qty,
            $unit,
            $total,
            $newPending,
            $paymentStatus,
            $date,
            $time,
            $date,
            $time,
            $user,
            $row['id']
        );
        $up->execute();
        return true;
    }

    return false;
}

function updateLatestAllPurchasingRecord($conn, $oldProductName, $oldInvoiceNumber, $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $supplier, $invoice_number, $expiry_date, $total_purchasing_price, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost) {
    $sql = "UPDATE all_purchasing_product_data 
            SET product_name=?, purchasing_price=?, selling_price=?, purchased_qty=?, unit=?, supplier=?, invoice_number=?, expiry_date=?, total_purchasing_price=?, entered_date=?, entered_time=?, entered_user=?, is_dual_mode=?, dual_mode_name_1=?, dual_mode_qty_1=?, dual_mode_price_1=?, dual_mode_name_2=?, dual_mode_qty_2=?, dual_mode_price_2=?, purchase_percentage=?, base_unit_cost=?
            WHERE product_name=?";
    if ($oldInvoiceNumber !== '') {
        $sql .= " AND invoice_number=?";
    }
    $sql .= " ORDER BY id DESC LIMIT 1";

    $stmt = $conn->prepare($sql);

    if ($oldInvoiceNumber !== '') {
        $stmt->bind_param(
            "sdddssssdsssisddsddddss",
            $product_name,
            $purchasing_price,
            $selling_price,
            $purchased_qty,
            $unit,
            $supplier,
            $invoice_number,
            $expiry_date,
            $total_purchasing_price,
            $date,
            $time,
            $user,
            $is_dual_mode,
            $dual_mode_name_1,
            $dual_mode_qty_1,
            $dual_mode_price_1,
            $dual_mode_name_2,
            $dual_mode_qty_2,
            $dual_mode_price_2,
            $purchase_percentage,
            $baseUnit_cost,
            $oldProductName,
            $oldInvoiceNumber
        );
    } else {
        $stmt->bind_param(
            "sdddssssdsssisddsdddds",
            $product_name,
            $purchasing_price,
            $selling_price,
            $purchased_qty,
            $unit,
            $supplier,
            $invoice_number,
            $expiry_date,
            $total_purchasing_price,
            $date,
            $time,
            $user,
            $is_dual_mode,
            $dual_mode_name_1,
            $dual_mode_qty_1,
            $dual_mode_price_1,
            $dual_mode_name_2,
            $dual_mode_qty_2,
            $dual_mode_price_2,
            $purchase_percentage,
            $base_unit_cost,
            $oldProductName
        );
    }

    $stmt->execute();
}

function getDualPackQtyFromProductName($productName, $fallbackQty = 0) {
    $packQty = 0;

    if (preg_match('/(\d+(?:\.\d+)?)\s*kg/i', $productName, $matches)) {
        $packQty = (float)$matches[1];
    }

    if ($packQty <= 0) {
        $packQty = (float)$fallbackQty;
    }

    return $packQty > 0 ? $packQty : 0;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $action = $_POST['action'] ?? 'item_add';
        $edit_id = (int)($_POST['id'] ?? 0);

        if ($action === 'delete_purchase' && $edit_id > 0) {
            $fetchRow = $conn->prepare("SELECT * FROM stock WHERE id = ? LIMIT 1");
            $fetchRow->bind_param("i", $edit_id);
            $fetchRow->execute();
            $stockRowResult = $fetchRow->get_result();

            if ($stockRowResult && $stockRowResult->num_rows > 0) {
                $stockRow = $stockRowResult->fetch_assoc();

                $product_name = trim((string)$stockRow['product_name']);
                $invoice_number = trim((string)($stockRow['invoice_number'] ?? ''));

                $conn->begin_transaction();

                try {
                    $creditIds = [];

                    $creditFetch = $conn->prepare("SELECT id FROM credit_puraching WHERE stock_id = ?");
                    $creditFetch->bind_param("i", $edit_id);
                    $creditFetch->execute();
                    $creditRes = $creditFetch->get_result();

                    while ($creditRow = $creditRes->fetch_assoc()) {
                        $creditIds[] = (int)$creditRow['id'];
                    }

                    if (!empty($creditIds)) {
                        $placeholders = implode(',', array_fill(0, count($creditIds), '?'));
                        $types = str_repeat('i', count($creditIds));

                        $deleteUpdates = $conn->prepare("DELETE FROM credit_purchaing_update WHERE credit_purchase_id IN ($placeholders)");
                        $deleteUpdates->bind_param($types, ...$creditIds);
                        $deleteUpdates->execute();
                    }

                    $deleteCredit = $conn->prepare("DELETE FROM credit_puraching WHERE stock_id = ?");
                    $deleteCredit->bind_param("i", $edit_id);
                    $deleteCredit->execute();

                    if ($invoice_number !== '') {
                        $deleteAllPurchasing = $conn->prepare("DELETE FROM all_purchasing_product_data WHERE product_name = ? AND invoice_number = ?");
                        $deleteAllPurchasing->bind_param("ss", $product_name, $invoice_number);
                        $deleteAllPurchasing->execute();
                    } else {
                        $deleteAllPurchasing = $conn->prepare("DELETE FROM all_purchasing_product_data WHERE product_name = ?");
                        $deleteAllPurchasing->bind_param("s", $product_name);
                        $deleteAllPurchasing->execute();
                    }

                    $deleteStock = $conn->prepare("DELETE FROM stock WHERE id = ?");
                    $deleteStock->bind_param("i", $edit_id);
                    $deleteStock->execute();

                    $conn->commit();
                    $message = 'Selected daily purchasing record deleted successfully.';
                } catch (Throwable $e) {
                    $conn->rollback();
                    throw $e;
                }
            } else {
                $message = 'Selected record not found.';
                $messageClass = 'error-box';
            }
        } else {
            $product_name = trim($_POST['product_name'] ?? '');
            $selling_price = (float)($_POST['selling_price'] ?? 0);
            $purchase_percentage = (float)($_POST['purchase_percentage'] ?? 0);
            $purchasing_price = (float)($_POST['purchasing_price'] ?? 0);
            $entered_qty = (float)($_POST['purchased_qty'] ?? 0);
            $unit = trim($_POST['unit'] ?? '');
            $supplier = trim($_POST['supplier'] ?? '');
            $invoice_number = trim($_POST['invoice_number'] ?? '');
            $expiry_date = trim($_POST['expiry_date'] ?? '');
            $total_purchasing_price = (float)($_POST['total_purchasing_price'] ?? 0);

            $is_dual_mode = (int)($_POST['is_dual_mode'] ?? 0);
            $dual_mode_name_1 = trim($_POST['dual_mode_name_1'] ?? '');
            $dual_mode_qty_1 = (float)($_POST['dual_mode_qty_1'] ?? 0);
            $dual_mode_price_1 = (float)($_POST['dual_mode_price_1'] ?? 0);
            $dual_mode_name_2 = trim($_POST['dual_mode_name_2'] ?? '');
            $dual_mode_qty_2 = (float)($_POST['dual_mode_qty_2'] ?? 0);
            $dual_mode_price_2 = (float)($_POST['dual_mode_price_2'] ?? 0);
            $base_unit_cost = (float)($_POST['base_unit_cost'] ?? 0);

            if ($is_dual_mode === 1) {
                if ($dual_mode_price_1 > 0) {
                    $selling_price = $dual_mode_price_1;
                }
                if ($dual_mode_name_1 === '') {
                    $dual_mode_name_1 = '50Kg Bag';
                }
                if ($dual_mode_name_2 === '') {
                    $dual_mode_name_2 = 'Loose Kg';
                }
                if ($dual_mode_qty_2 <= 0) {
                    $dual_mode_qty_2 = 1;
                }

                $derivedPackQty = getDualPackQtyFromProductName($product_name, $dual_mode_qty_1);
                if ($derivedPackQty > 0) {
                    $dual_mode_qty_1 = $derivedPackQty;
                } elseif ($dual_mode_qty_1 <= 0) {
                    $dual_mode_qty_1 = 50;
                }
            } else {
                $dual_mode_name_1 = '';
                $dual_mode_qty_1 = 0;
                $dual_mode_price_1 = 0;
                $dual_mode_name_2 = '';
                $dual_mode_qty_2 = 0;
                $dual_mode_price_2 = 0;
            }

            if ($selling_price > 0) {
                $purchasing_price = $selling_price - (($selling_price * $purchase_percentage) / 100);
                if ($purchasing_price < 0) {
                    $purchasing_price = 0;
                }
            }

            $purchased_qty = $entered_qty;

            if ($is_dual_mode === 1) {
                $packQty = getDualPackQtyFromProductName($product_name, $dual_mode_qty_1);

                if ($packQty > 0) {
                    $purchased_qty = $entered_qty * $packQty;
                    $base_unit_cost = $purchasing_price / $packQty;
                } else {
                    $base_unit_cost = 0;
                }

                $total_purchasing_price = $purchasing_price * $entered_qty;
            } else {
                $base_unit_cost = $purchasing_price;
                $total_purchasing_price = $purchasing_price * $purchased_qty;
            }

            if ($product_name && $selling_price > 0 && $purchasing_price > 0 && $purchased_qty > 0 && $unit !== '' && $supplier !== '') {

                if ($action === 'edit_purchase') {
                    if ($edit_id <= 0) {
                        $message = 'Please select an existing product row before editing.';
                        $messageClass = 'error-box';
                    } else {
                        $fetchCurrent = $conn->prepare("SELECT product_name, invoice_number FROM stock WHERE id = ? LIMIT 1");
                        $fetchCurrent->bind_param("i", $edit_id);
                        $fetchCurrent->execute();
                        $currentRes = $fetchCurrent->get_result();

                        if ($currentRes && $currentRes->num_rows > 0) {
                            $currentRow = $currentRes->fetch_assoc();
                            $oldProductName = $currentRow['product_name'];
                            $oldInvoiceNumber = trim((string)($currentRow['invoice_number'] ?? ''));

                            $conn->begin_transaction();

                            try {
                                $stockUpdate = $conn->prepare("UPDATE stock SET product_name=?, purchasing_price=?, selling_price=?, purchased_qty=?, unit=?, supplier=?, invoice_number=?, expiry_date=?, total_purchasing_price=?, entered_date=?, entered_time=?, entered_user=?, is_dual_mode=?, dual_mode_name_1=?, dual_mode_qty_1=?, dual_mode_price_1=?, dual_mode_name_2=?, dual_mode_qty_2=?, dual_mode_price_2=?, purchase_percentage=?, base_unit_cost=? WHERE id=?");
                                $stockUpdate->bind_param("sdddssssdsssisddsddddi", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $supplier, $invoice_number, $expiry_date, $total_purchasing_price, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost, $edit_id);
                                $stockUpdate->execute();

                                updateLatestAllPurchasingRecord(
                                    $conn,
                                    $oldProductName,
                                    $oldInvoiceNumber,
                                    $product_name,
                                    $purchasing_price,
                                    $selling_price,
                                    $purchased_qty,
                                    $unit,
                                    $supplier,
                                    $invoice_number,
                                    $expiry_date,
                                    $total_purchasing_price,
                                    $date,
                                    $time,
                                    $user,
                                    $is_dual_mode,
                                    $dual_mode_name_1,
                                    $dual_mode_qty_1,
                                    $dual_mode_price_1,
                                    $dual_mode_name_2,
                                    $dual_mode_qty_2,
                                    $dual_mode_price_2,
                                    $purchase_percentage,
                                    $base_unit_cost
                                );

                                $updated = updateLatestCreditPurchasingRecord(
                                    $conn,
                                    $edit_id,
                                    $oldInvoiceNumber,
                                    $product_name,
                                    $supplier,
                                    $invoice_number,
                                    $purchased_qty,
                                    $unit,
                                    $total_purchasing_price,
                                    $date,
                                    $time,
                                    $user
                                );

                                if (!$updated) {
                                    insertCreditPurchasing($conn, $edit_id, $product_name, $supplier, $invoice_number, $purchased_qty, $unit, $total_purchasing_price, $date, $time, $user);
                                }

                                $conn->commit();
                                $message = 'Selected product edited successfully.';
                            } catch (Throwable $e) {
                                $conn->rollback();
                                throw $e;
                            }
                        } else {
                            $message = 'Selected row not found for edit.';
                            $messageClass = 'error-box';
                        }
                    }
                } elseif ($action === 'qty_update') {
                    if ($edit_id <= 0) {
                        $message = 'Please select an existing product row before QTY-Update.';
                        $messageClass = 'error-box';
                    } else {
                        $fetchExisting = $conn->prepare("SELECT id, purchased_qty, total_purchasing_price FROM stock WHERE id = ? LIMIT 1");
                        $fetchExisting->bind_param("i", $edit_id);
                        $fetchExisting->execute();
                        $res = $fetchExisting->get_result();

                        if ($res && $res->num_rows > 0) {
                            $row = $res->fetch_assoc();

                            $conn->begin_transaction();

                            try {
                                $newQty = (float)$row['purchased_qty'] + (float)$purchased_qty;
                                $newTotal = (float)$row['total_purchasing_price'] + (float)$total_purchasing_price;

                                $up = $conn->prepare("UPDATE stock SET product_name=?, purchasing_price=?, selling_price=?, purchased_qty=?, unit=?, supplier=?, invoice_number=?, expiry_date=?, total_purchasing_price=?, entered_date=?, entered_time=?, entered_user=?, is_dual_mode=?, dual_mode_name_1=?, dual_mode_qty_1=?, dual_mode_price_1=?, dual_mode_name_2=?, dual_mode_qty_2=?, dual_mode_price_2=?, purchase_percentage=?, base_unit_cost=? WHERE id=?");
                                $up->bind_param("sdddssssdsssisddsddddi", $product_name, $purchasing_price, $selling_price, $newQty, $unit, $supplier, $invoice_number, $expiry_date, $newTotal, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost, $edit_id);
                                $up->execute();

                                $stmt1 = $conn->prepare("INSERT INTO all_purchasing_product_data (product_name,purchasing_price,selling_price,purchased_qty,unit,supplier,invoice_number,expiry_date,total_purchasing_price,entered_date,entered_time,entered_user,is_dual_mode,dual_mode_name_1,dual_mode_qty_1,dual_mode_price_1,dual_mode_name_2,dual_mode_qty_2,dual_mode_price_2,purchase_percentage,base_unit_cost) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                                $stmt1->bind_param("sdddssssdsssisddsdddd", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $supplier, $invoice_number, $expiry_date, $total_purchasing_price, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost);
                                $stmt1->execute();

                                insertCreditPurchasing($conn, $edit_id, $product_name, $supplier, $invoice_number, $purchased_qty, $unit, $total_purchasing_price, $date, $time, $user);

                                $conn->commit();
                                $message = 'Product quantity updated successfully.';
                            } catch (Throwable $e) {
                                $conn->rollback();
                                throw $e;
                            }
                        } else {
                            $message = 'Selected row not found for QTY-Update.';
                            $messageClass = 'error-box';
                        }
                    }
                } else {
                    $checkNew = $conn->prepare("SELECT id FROM stock WHERE product_name = ? LIMIT 1");
                    $checkNew->bind_param("s", $product_name);
                    $checkNew->execute();
                    $newRes = $checkNew->get_result();

                    if ($newRes && $newRes->num_rows > 0) {
                        $message = 'Product already exists in stock. Please use QTY-Update or Edit.';
                        $messageClass = 'error-box';
                    } else {
                        $conn->begin_transaction();

                        try {
                            $stmt2 = $conn->prepare("INSERT INTO stock (product_name,purchasing_price,selling_price,purchased_qty,unit,supplier,invoice_number,expiry_date,total_purchasing_price,entered_date,entered_time,entered_user,is_dual_mode,dual_mode_name_1,dual_mode_qty_1,dual_mode_price_1,dual_mode_name_2,dual_mode_qty_2,dual_mode_price_2,purchase_percentage,base_unit_cost) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                            $stmt2->bind_param("sdddssssdsssisddsdddd", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $supplier, $invoice_number, $expiry_date, $total_purchasing_price, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost);
                            $stmt2->execute();
                            $stockId = $conn->insert_id;

                            $stmt1 = $conn->prepare("INSERT INTO all_purchasing_product_data (product_name,purchasing_price,selling_price,purchased_qty,unit,supplier,invoice_number,expiry_date,total_purchasing_price,entered_date,entered_time,entered_user,is_dual_mode,dual_mode_name_1,dual_mode_qty_1,dual_mode_price_1,dual_mode_name_2,dual_mode_qty_2,dual_mode_price_2,purchase_percentage,base_unit_cost) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                            $stmt1->bind_param("sdddssssdsssisddsdddd", $product_name, $purchasing_price, $selling_price, $purchased_qty, $unit, $supplier, $invoice_number, $expiry_date, $total_purchasing_price, $date, $time, $user, $is_dual_mode, $dual_mode_name_1, $dual_mode_qty_1, $dual_mode_price_1, $dual_mode_name_2, $dual_mode_qty_2, $dual_mode_price_2, $purchase_percentage, $base_unit_cost);
                            $stmt1->execute();

                            insertCreditPurchasing($conn, $stockId, $product_name, $supplier, $invoice_number, $purchased_qty, $unit, $total_purchasing_price, $date, $time, $user);

                            $conn->commit();
                            $message = 'New product added successfully.';
                        } catch (Throwable $e) {
                            $conn->rollback();
                            throw $e;
                        }
                    }
                }
            } else {
                $message = 'Please fill required fields.';
                $messageClass = 'error-box';
            }
        }
    } catch (Throwable $e) {
        app_log_error('daily_purchasing.php error: ' . $e->getMessage());
        $message = 'Connection or server issue detected. Please try again.';
        $messageClass = 'error-box';
    }
}

try {
    $stock = $conn->query("SELECT * FROM stock ORDER BY product_name ASC");
    $suppliers = $conn->query("SELECT company_name FROM suppliers ORDER BY company_name ASC");
} catch (Throwable $e) {
    app_log_error('daily_purchasing.php load error: ' . $e->getMessage());
    $message = 'Data loading is temporarily unavailable. Please refresh and try again.';
    $messageClass = 'error-box';
    $stock = false;
    $suppliers = false;
}

$supplierOptions = [];
if ($suppliers) {
    while ($sup = $suppliers->fetch_assoc()) {
        $supplierOptions[] = $sup['company_name'];
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Krushi Sewa Piyasa-Inventory</title>
    <link rel="stylesheet" href="assets/style.css">
</head>
<body>
<div class="layout">
    <?php renderSidebar('daily_purchasing'); ?>
    <main class="main-content">
        <div class="topbar"><span class="topbar-left-status"></span>Logged User: <?php echo $_SESSION['name']; ?> | <?php echo $_SESSION['user_category']; ?></div>

        <?php if ($message !== '') { ?>
            <div class="message-box <?php echo $messageClass; ?>"><?php echo htmlspecialchars($message); ?></div>
        <?php } ?>

        <div class="form-card">
            <h2>Inventory</h2>
            <form method="POST" class="daily-purchase-form" onsubmit="return confirmDeleteAction(event);">
                <input type="hidden" name="id" id="edit_id">

                <div class="daily-purchase-grid">
                    <div class="field-group field-span-2">
                        <label for="search_product">Product Name</label>
                        <input type="text" name="product_name" id="search_product" placeholder="Search Product Name" onkeyup="filterTable(); updateDualQtyPreview();" oninput="updateDualQtyPreview();" required>
                    </div>

                    <div class="field-group">
                        <label for="is_dual_mode">Product Type</label>
                        <select name="is_dual_mode" id="is_dual_mode" onchange="toggleDualModeFields(); syncPrimarySellingPrice(); calcDailyPurchaseTotal();">
                            <option value="0">Standard Product</option>
                            <option value="1">Dual Selling Mode Product</option>
                        </select>
                    </div>

                    <div class="field-group">
                        <label for="edit_selling_price">Primary Selling Price</label>
                        <input type="number" step="0.01" name="selling_price" id="edit_selling_price" placeholder="Primary Selling Price" oninput="syncPrimarySellingPrice(); calcDailyPurchaseTotal();" required>
                    </div>

                    <div class="field-group">
                        <label for="edit_purchase_percentage">Purchase Percentage</label>
                        <input type="number" step="0.01" name="purchase_percentage" id="edit_purchase_percentage" placeholder="Purchase Percentage" oninput="calcDailyPurchaseTotal()" required>
                    </div>

                    <div class="field-group">
                        <label for="edit_purchasing_price">Purchasing Value</label>
                        <input type="number" step="0.01" name="purchasing_price" id="edit_purchasing_price" placeholder="Purchasing Value" readonly required>
                    </div>

                    <div class="field-group">
                        <label for="edit_purchased_qty" id="edit_purchased_qty_label">Purchased Qty</label>
                        <input type="number" step="0.01" name="purchased_qty" id="edit_purchased_qty" placeholder="Purchased QTY" oninput="calcDailyPurchaseTotal()" required>
                        <small id="dual_qty_preview" style="display:block;margin-top:6px;color:#1f7a3f;font-weight:600;"></small>
                    </div>

                    <div class="field-group">
                        <label for="edit_unit">Unit</label>
                        <select name="unit" id="edit_unit" required>
                            <option value="">Select Unit</option>
                            <option value="Kg">Kg</option>
                            <option value="g">g</option>
                            <option value="L">L</option>
                            <option value="ml">ml</option>
                            <option value="Pcs">Pcs</option>
                            <option value="Pack">Pack</option>
                            <option value="Bottle">Bottle</option>
                            <option value="Bag">Bag</option>
                            <option value="Box">Box</option>
                            <option value="Tin">Tin</option>
                            <option value="Can">Can</option>
                            <option value="Dozen">Dozen</option>
                            <option value="Meter">Meter</option>
                            <option value="Feet">Feet</option>
                        </select>
                    </div>

                    <div class="field-group field-span-2">
                        <label for="edit_supplier">Supplier</label>
                        <select name="supplier" id="edit_supplier" required>
                            <option value="">Select Supplier</option>
                            <?php foreach ($supplierOptions as $company) { ?>
                                <option value="<?php echo htmlspecialchars($company); ?>"><?php echo htmlspecialchars($company); ?></option>
                            <?php } ?>
                        </select>
                    </div>

                    <div class="field-group field-span-2">
                        <label for="edit_invoice_number">Invoice Number</label>
                        <input type="text" name="invoice_number" id="edit_invoice_number" placeholder="Invoice Number">
                    </div>

                    <div class="field-group">
                        <label for="edit_expiry_date">Expiry Date</label>
                        <input type="date" name="expiry_date" id="edit_expiry_date">
                    </div>

                    <div class="field-group field-highlight">
                        <label for="edit_total_purchasing_price">Total Purchasing Price</label>
                        <input type="number" step="0.01" name="total_purchasing_price" id="edit_total_purchasing_price" readonly required>
                    </div>
                </div>

                <input type="hidden" name="base_unit_cost" id="edit_base_unit_cost" value="0">

                <div class="dual-mode-card" id="dual_mode_wrap" style="display:none;">
                    <div class="dual-mode-title">Dual Selling Mode Setup</div>
                    <div class="dual-mode-grid">
                        <div class="field-group">
                            <label for="edit_dual_mode_name_1">Mode 1 Name</label>
                            <input type="text" name="dual_mode_name_1" id="edit_dual_mode_name_1" placeholder="50Kg Bag">
                        </div>
                        <div class="field-group">
                            <label for="edit_dual_mode_qty_1">Mode 1 Qty Reduction</label>
                            <input type="number" step="0.01" name="dual_mode_qty_1" id="edit_dual_mode_qty_1" placeholder="50" oninput="calcDailyPurchaseTotal()">
                        </div>
                        <div class="field-group">
                            <label for="edit_dual_mode_price_1">Mode 1 Selling Price</label>
                            <input type="number" step="0.01" name="dual_mode_price_1" id="edit_dual_mode_price_1" placeholder="Mode 1 Selling Price" oninput="syncPrimarySellingPrice(); calcDailyPurchaseTotal()">
                        </div>
                        <div class="field-group">
                            <label for="edit_dual_mode_name_2">Mode 2 Name</label>
                            <input type="text" name="dual_mode_name_2" id="edit_dual_mode_name_2" placeholder="Loose Kg">
                        </div>
                        <div class="field-group">
                            <label for="edit_dual_mode_qty_2">Mode 2 Qty Reduction</label>
                            <input type="number" step="0.01" name="dual_mode_qty_2" id="edit_dual_mode_qty_2" placeholder="1">
                        </div>
                        <div class="field-group">
                            <label for="edit_dual_mode_price_2">Mode 2 Selling Price</label>
                            <input type="number" step="0.01" name="dual_mode_price_2" id="edit_dual_mode_price_2" placeholder="Mode 2 Selling Price">
                        </div>
                    </div>
                </div>

                <div class="daily-action-row">
                    <button type="submit" name="action" value="item_add">Item-Add</button>
                    <button type="submit" name="action" value="qty_update">QTY-Update</button>
                    <button type="submit" name="action" value="edit_purchase">Edit</button>
                    <button type="submit" name="action" value="delete_purchase" style="background:#c9302c;">Delete</button>
                </div>
            </form>
        </div>

        <div class="table-card">
            <div class="table-scroll">
                <table id="productTable">
                    <tr>
                        <th>ID</th>
                        <th>Product</th>
                        <th>Purchase Value</th>
                        <th>Primary Price</th>
                        <th>Qty</th>
                        <th>Unit</th>
                        <th>Supplier</th>
                        <th>Invoice No</th>
                        <th>Expiry Date</th>
                        <th>Mode 1</th>
                        <th>Mode 2</th>
                        <th>Total</th>
                    </tr>
                    <?php if ($stock) { while ($row = $stock->fetch_assoc()) { ?>
                    <tr onclick="fillEditForm(
                        '<?php echo $row['id']; ?>',
                        '<?php echo htmlspecialchars($row['product_name'], ENT_QUOTES); ?>',
                        '<?php echo $row['purchasing_price']; ?>',
                        '<?php echo $row['selling_price']; ?>',
                        '<?php echo $row['purchased_qty']; ?>',
                        '<?php echo htmlspecialchars($row['unit'], ENT_QUOTES); ?>',
                        '<?php echo $row['total_purchasing_price']; ?>',
                        '<?php echo htmlspecialchars($row['invoice_number'] ?? '', ENT_QUOTES); ?>',
                        '<?php echo htmlspecialchars($row['expiry_date'] ?? '', ENT_QUOTES); ?>',
                        '<?php echo htmlspecialchars($row['supplier'] ?? '', ENT_QUOTES); ?>',
                        '<?php echo (int)($row['is_dual_mode'] ?? 0); ?>',
                        '<?php echo htmlspecialchars($row['dual_mode_name_1'] ?? '', ENT_QUOTES); ?>',
                        '<?php echo $row['dual_mode_qty_1'] ?? 0; ?>',
                        '<?php echo $row['dual_mode_price_1'] ?? 0; ?>',
                        '<?php echo htmlspecialchars($row['dual_mode_name_2'] ?? '', ENT_QUOTES); ?>',
                        '<?php echo $row['dual_mode_qty_2'] ?? 0; ?>',
                        '<?php echo $row['dual_mode_price_2'] ?? 0; ?>',
                        '<?php echo $row['purchase_percentage'] ?? 0; ?>',
                        '<?php echo $row['base_unit_cost'] ?? 0; ?>'
                    )">
                        <td><?php echo $row['id']; ?></td>
                        <td><?php echo htmlspecialchars($row['product_name']); ?></td>
                        <td><?php echo number_format((float)$row['purchasing_price'],2); ?></td>
                        <td><?php echo number_format((float)$row['selling_price'],2); ?></td>
                        <td><?php echo number_format((float)$row['purchased_qty'],2); ?></td>
                        <td><?php echo htmlspecialchars($row['unit']); ?></td>
                        <td><?php echo htmlspecialchars($row['supplier'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($row['invoice_number'] ?? ''); ?></td>
                        <td><?php echo htmlspecialchars($row['expiry_date'] ?? ''); ?></td>
                        <td>
                            <?php
                            if ((int)($row['is_dual_mode'] ?? 0) === 1) {
                                echo htmlspecialchars($row['dual_mode_name_1']) . ' - Rs.' . number_format((float)$row['dual_mode_price_1'], 2);
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td>
                            <?php
                            if ((int)($row['is_dual_mode'] ?? 0) === 1) {
                                echo htmlspecialchars($row['dual_mode_name_2']) . ' - Rs.' . number_format((float)$row['dual_mode_price_2'], 2);
                            } else {
                                echo '-';
                            }
                            ?>
                        </td>
                        <td><?php echo number_format((float)$row['total_purchasing_price'],2); ?></td>
                    </tr>
                    <?php } } ?>
                </table>
            </div>
        </div>
    </main>
</div>

<script src="assets/app.js"></script>
<script>
function confirmDeleteAction(event) {
    const activeButton = document.activeElement;
    if (activeButton && activeButton.name === 'action' && activeButton.value === 'delete_purchase') {
        const editId = document.getElementById('edit_id').value;
        if (!editId) {
            alert('Please select a row before deleting.');
            event.preventDefault();
            return false;
        }
        const ok = confirm('Are you sure you want to delete the selected purchasing record?');
        if (!ok) {
            event.preventDefault();
            return false;
        }
    }
    return true;
}
</script>
</body>
</html>