<?php
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

include 'auth.php';
include "db.php";

/* FETCH SUPPLIERS */
$suppliers = [];
$supplierQuery = $conn->query("SELECT id, name FROM suppliers ORDER BY id DESC");
if($supplierQuery){
    $suppliers = $supplierQuery->fetch_all(MYSQLI_ASSOC);
}

/* FETCH PRODUCTS */
$products = [];
$productQuery = $conn->query("SELECT product_id, product_name, price_per_piece, stock_quantity FROM products ORDER BY product_id DESC");
if($productQuery){
    $products = $productQuery->fetch_all(MYSQLI_ASSOC);
}

/* SAVE PURCHASE INVOICE */
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['supplier_id'])){

    $date        = $_POST['date'];
    $supplier_id = intval($_POST['supplier_id']);

    $sub_total   = floatval($_POST['sub_total'] ?? 0);
    $grand_total = floatval($_POST['grand_total'] ?? 0);

    $discount    = floatval($_POST['discount_amount'] ?? 0);
    $tax         = floatval($_POST['tax_amount'] ?? 0);
    $other       = floatval($_POST['other_amount'] ?? 0);
    $round_off   = floatval($_POST['round_off'] ?? 0);

    // 🆕 NEW: Gate Pass / Builty / Dispatch Through fields receive karna
    $gate_pass_number = trim($_POST['gate_pass_number'] ?? '');
    $builty_number     = trim($_POST['builty_number'] ?? '');
    $dispatch_through  = trim($_POST['dispatch_through'] ?? '');
    // 🆕 NEW: Vehicle Size field receive karna
    $vehicle_size      = trim($_POST['vehicle_size'] ?? '');

    /* 1. INSERT MAIN PURCHASE INVOICE RECORD (🆕 gate_pass_number, bilty_number, dispatch_through, vehicle_size add kiye) */
    // NOTE: column ka sahi naam "bilty_number" hai (builty_number nahi)
    $stmt = $conn->prepare("
        INSERT INTO purchases
        (
            supplier_id,
            purchase_date,
            sub_total,
            discount_amount,
            tax_amount,
            other_charges,
            round_off,
            grand_total,
            gate_pass_number,
            bilty_number,
            dispatch_through,
            vehicle_size
        )
        VALUES(?,?,?,?,?,?,?,?,?,?,?,?)
    ");

    $stmt->bind_param(
        "isddddddssss",
        $supplier_id,
        $date,
        $sub_total,
        $discount,
        $tax,
        $other,
        $round_off,
        $grand_total,
        $gate_pass_number,
        $builty_number,
        $dispatch_through,
        $vehicle_size
    );

    $stmt->execute();
    $purchase_id = $stmt->insert_id;
    $stmt->close();

    /* FILE ATTACHMENT PROCESSING */
    $attachment_name = "";
    if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['attachment']['tmp_name'];
        $fileName = $_FILES['attachment']['name'];
        $fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        
        $allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf', 'docx', 'xlsx'];
        
        if (in_array($fileExtension, $allowedExtensions)) {
            $attachment_name = md5(time() . $fileName) . '.' . $fileExtension;
            $uploadFileDir = './uploads/';
            if (!is_dir($uploadFileDir)) {
                mkdir($uploadFileDir, 0755, true);
            }
            $dest_path = $uploadFileDir . $attachment_name;
            move_uploaded_file($fileTmpPath, $dest_path);
        }
    }

    /* 2. INSERT INDIVIDUAL PRODUCTS & UPDATE STOCK STATUS */
    if(isset($_POST['product_id']) && is_array($_POST['product_id'])){

        foreach($_POST['product_id'] as $key => $product_id){
            $product_id = intval($product_id);
            if($product_id <= 0) continue;

            $qty   = floatval($_POST['quantity'][$key]);
            $price = floatval($_POST['price'][$key]);
            $total = $qty * $price;

            $itemStmt = $conn->prepare("
                INSERT INTO purchase_items
                (
                    purchase_id,
                    product_id,
                    quantity,
                    price,
                    total
                )
                VALUES(?,?,?,?,?)
            ");
            $itemStmt->bind_param("iiidd", $purchase_id, $product_id, $qty, $price, $total);
            $itemStmt->execute();
            $itemStmt->close();

            $stockStmt = $conn->prepare("
                UPDATE products
                SET stock_quantity = stock_quantity + ?
                WHERE product_id = ?
            ");
            $stockStmt->bind_param("di", $qty, $product_id);
            $stockStmt->execute();
            $stockStmt->close();
        }
    }

    /* 3. DYNAMIC TRANSACTIONS RECORD SUMMARY MAPPER (FOR LEDGER) */
    $purchase_summary = json_encode([
        'sub_total' => $sub_total,
        'tax' => $tax,
        'discount' => $discount,
        'other' => $other,
        'round_off' => $round_off
    ]);

    $type = "Credit"; 
    $reference_type = "supplier";

    $ledgerStmt = $conn->prepare("
        INSERT INTO transactions (reference_id, voucher_id, reference_type, date, description, type, amount) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");

    $ledgerStmt->bind_param(
        "iissssd",
        $supplier_id,
        $purchase_id,
        $reference_type,
        $date,
        $purchase_summary,
        $type,
        $grand_total
    );

    if($ledgerStmt->execute()){
        $ledgerStmt->close();
        // APKA DIRECT REDIRECTION YAHAN HANDLE HORHA HY
        header("Location: purchase_view.php?id=" . $purchase_id);
        exit;
    } else {
        echo "<script>alert('Error updating ledger: " . $conn->error . "');</script>";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Purchase Invoice - Tameer Al Madina</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    background: #F4F6F9;
    font-family: 'Poppins', sans-serif;
    min-height: 100vh;
}

.main-layout {
    display: flex;
    width: 100%;
    min-height: 100vh;
    position: relative;
}

aside, .sidebar, [class*="sidebar"] {
    width: 260px;
    min-width: 260px;
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    transition: all 0.3s ease;
}

.content-wrapper {
    flex: 1;
    margin-left: 260px;
    display: flex;
    flex-direction: column;
    background: #F4F6F9;
    min-width: 0;
    width: calc(100% - 260px);
    transition: all 0.3s ease;
}

/* Navbar Config */
.top-navbar {
    height: 60px;
    background: #FFFFFF;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 30px;
    border-bottom: 1px solid #EAEAEA;
}

.navbar-left-flex {
    display: flex;
    align-items: center;
    gap: 15px;
}

.mobile-menu-toggle {
    display: none;
    font-size: 20px;
    color: #0A192F;
    cursor: pointer;
    background: #F4F6F9;
    width: 38px;
    height: 38px;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    border: 1px solid #E2E8F0;
}

.search-container {
    position: relative;
    width: 300px;
}

.search-container input {
    width: 100%;
    padding: 8px 15px 8px 40px;
    background: #F8F9FA;
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    font-size: 13px;
    outline: none;
}

.search-container i {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: #A0AEC0;
}

.user-profile {
    display: flex;
    align-items: center;
    gap: 20px;
}

.profile-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.profile-info i.profile-icon {
    font-size: 26px;
    color: #4A5568;
    background: #F4F6F9;
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    border: 1px solid #E2E8F0;
}

.profile-text h4 {
    font-size: 13px;
    color: #1A202C;
    font-weight: 600;
}

.profile-text p {
    font-size: 11px;
    color: #718096;
}

/* Master Form Sheet Wrapper */
.page-container {
    padding: 20px 30px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.form-card {
    background: #FFFFFF;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    width: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
}

form {
    display: flex;
    flex-direction: column;
    flex: 1;
}

.form-banner {
    background: linear-gradient(135deg, #0A192F 0%, #172A45 100%);
    padding: 15px 30px;
    color: #FFFFFF;
    border-bottom: 4px solid #0d6efd;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.banner-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.banner-icon {
    background: rgba(255, 255, 255, 0.1);
    width: 38px;
    height: 38px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 6px;
    font-size: 16px;
}

.banner-text h2 {
    font-size: 18px;
    font-weight: 600;
}

.banner-text p {
    font-size: 11px;
    color: #A0AEC0;
}

.banner-right-text {
    font-size: 18px;
    font-weight: 700;
    color: rgba(255, 255, 255, 0.15);
}

.section-header {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 18px 30px 10px 30px;
    font-size: 14px;
    font-weight: 600;
    color: #0A192F;
}

.section-header i {
    color: #0d6efd;
    font-size: 16px;
}

/* Fluid Form Input Blueprint */
.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr); 
    gap: 15px 25px;
    padding: 0 30px;
}

.form-group {
    display: flex;
    flex-direction: column;
}

.form-group label {
    font-size: 12px;
    font-weight: 500;
    color: #2D3748;
    margin-bottom: 6px;
}

.required {
    color: #E53E3E;
    margin-left: 3px;
}

.input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.input-wrapper i {
    position: absolute;
    left: 15px;
    color: #A0AEC0;
    font-size: 13px;
    z-index: 2;
}

.input-wrapper input,
.input-wrapper select {
    width: 100%;
    height: 38px;
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    padding: 5px 15px 5px 40px;
    font-size: 13px;
    color: #4A5568;
    background: #FFFFFF;
    outline: none;
}

.input-wrapper input:focus,
.input-wrapper select:focus {
    border-color: #0d6efd;
    box-shadow: 0 0 0 2px rgba(13, 110, 253, 0.1);
}

/* Line Item Row Layout */
.table-wrapper {
    margin: 15px 30px 5px 30px;
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    overflow: hidden;
}

table {
    width: 100%;
    border-collapse: collapse;
}

table thead {
    background: #F8F9FA;
    border-bottom: 2px solid #E2E8F0;
}

table th {
    padding: 10px 15px;
    font-size: 12px;
    font-weight: 600;
    color: #4A5568;
    text-align: left;
}

table td {
    padding: 8px 15px;
    border-bottom: 1px solid #E2E8F0;
    background: #FFFFFF;
}

table td input,
table td select {
    width: 100%;
    height: 34px;
    border: 1px solid #CBD5E1;
    border-radius: 6px;
    padding: 0 10px;
    font-size: 13px;
    outline: none;
}

.btn-delete-row {
    background: #FFF5F5;
    color: #E53E3E;
    border: 1px solid #FED7D7;
    width: 34px;
    height: 34px;
    border-radius: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.btn-delete-row:hover {
    background: #E53E3E;
    color: #FFFFFF;
}

.table-btn-container {
    padding: 0 30px;
    margin-top: 10px;
}

/* Modifier Valuation Modules */
.summary-row {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 15px;
    padding: 0 30px;
    margin-top: 15px;
}

.summary-box {
    background: #F8F9FA;
    border: 1px solid #E2E8F0;
    border-radius: 8px;
    padding: 10px 15px;
}

.summary-box label {
    display: block;
    font-size: 11px;
    font-weight: 600;
    color: #4A5568;
    margin-bottom: 4px;
}

.summary-box input {
    width: 100%;
    height: 32px;
    border: 1px solid #CBD5E1;
    border-radius: 6px;
    padding: 0 10px;
    font-size: 13px;
    background: #FFFFFF;
    outline: none;
}

.summary-box input[readonly] {
    background: #EDF2F7;
    border-color: #E2E8F0;
    cursor: pointer;
}

.grand-total-section {
    padding: 0 30px;
    margin-top: 15px;
}

.grand-box {
    background: #F0F7FF;
    border: 1px solid #D2E7FF;
    border-radius: 8px;
    padding: 12px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.grand-box label {
    font-size: 14px;
    font-weight: 600;
    color: #0A192F;
}

.grand-box input {
    width: 200px;
    height: 36px;
    border: 1px solid #A4CDFF;
    border-radius: 6px;
    padding: 0 15px;
    font-size: 16px;
    font-weight: 700;
    color: #0d6efd;
    background: #FFFFFF;
    text-align: right;
    outline: none;
}

/* Overlay Module Dialog */
.popup {
    position: fixed;
    inset: 0;
    background: rgba(0,0,0,0.4);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 1100;
}

.popup-content {
    width: 100%;
    max-width: 400px;
    background: #FFFFFF;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 10px 25px rgba(0,0,0,0.1);
}

.popup-title {
    font-size: 16px;
    font-weight: 600;
    color: #0A192F;
    margin-bottom: 15px;
    border-bottom: 1px solid #E2E8F0;
    padding-bottom: 8px;
}

.tabs {
    display: flex;
    background: #F1F5F9;
    padding: 4px;
    border-radius: 6px;
    margin-bottom: 15px;
}

.tab-btn {
    flex: 1;
    padding: 6px;
    border: none;
    border-radius: 4px;
    background: transparent;
    font-size: 12px;
    font-weight: 500;
    color: #64748B;
    cursor: pointer;
}

.active-tab {
    background: #FFFFFF;
    color: #0A192F;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.popup input {
    width: 100%;
    height: 36px;
    border: 1px solid #CBD5E1;
    border-radius: 6px;
    padding: 0 12px;
    font-size: 13px;
    outline: none;
}

.popup-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    margin-top: 15px;
}

/* Structural Operations Footer */
.form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 30px 25px 30px;
    margin-top: auto; 
    border-top: 1px solid #F0F2F5;
    flex-wrap: wrap;
    gap: 15px;
}

.action-left, .action-right {
    display: flex;
    gap: 12px;
}

.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 18px;
    border: none;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    cursor: pointer;
}

.btn-cancel { background: #EDF2F7; color: #4A5568; }
.btn-submit { background: #28a745; color: #FFFFFF; }
.btn-secondary { background: #0A192F; color: #FFFFFF; }
.btn-add { background: #F1F5F9; color: #4A5568; border: 1px dashed #CBD5E1; padding: 6px 14px; font-size: 12px; }

.sidebar-overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.4);
    z-index: 998;
}

@media (min-width: 992px) {
    body { overflow: hidden; }
    .page-container { height: calc(100vh - 60px); }
}

@media (max-width: 1024px) and (min-width: 769px) {
    aside, .sidebar, [class*="sidebar"] { width: 240px; min-width: 240px; }
    .content-wrapper { margin-left: 240px; width: calc(100% - 240px); }
    .form-grid { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 768px) {
    body { overflow-y: auto !important; }
    .mobile-menu-toggle { display: inline-flex; }
    aside, .sidebar, [class*="sidebar"] { left: -260px !important; }
    aside.active, .sidebar.active, [class*="sidebar"].active { left: 0 !important; }
    .content-wrapper { margin-left: 0 !important; width: 100% !important; }
    .top-navbar { padding: 0 15px; }
    .search-container { width: 140px; }
    .page-container { padding: 10px; }
    .form-banner { padding: 12px 15px; }
    .banner-right-text { display: none; }
    .section-header { padding: 15px 15px 8px 15px; }
    .form-grid { grid-template-columns: 1fr !important; padding: 0 15px; gap: 12px; }
    .table-wrapper { margin: 10px; }
    .table-btn-container { padding: 0 10px; }
    .summary-row { grid-template-columns: repeat(2, 1fr); padding: 0 10px; gap: 10px; }
    .grand-total-section { padding: 0 10px; }
    .grand-box { flex-direction: column; gap: 10px; align-items: flex-start; }
    .grand-box input { width: 100%; }
    .form-actions { padding: 15px; flex-direction: column; align-items: stretch; }
    .action-left, .action-right { flex-direction: column; width: 100%; }
    .btn { justify-content: center; width: 100%; }
}
</style>
</head>
<body>

<div class="sidebar-overlay" id="sidebarOverlay" onclick="toggleMobileSidebar()"></div>

<div class="main-layout">
    
    <?php 
    $sidebar_path = "/home/tameeralmadina/public_html/TAM/sidebar";
    if (file_exists($sidebar_path)) {
        include $sidebar_path;
    } elseif (file_exists($sidebar_path . ".php")) {
        include $sidebar_path . ".php";
    }
    ?>

    <div class="content-wrapper">
        
        <div class="top-navbar">
            <div class="navbar-left-flex">
                <div class="mobile-menu-toggle" onclick="toggleMobileSidebar()">
                    <i class="fa-solid fa-bars"></i>
                </div>
                <div class="search-container">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <input type="text" placeholder="Search here...">
                </div>
            </div>
            
            <div class="user-profile">
                <div class="profile-info">
                    <i class="fa-solid fa-circle-user profile-icon"></i>
                    <div class="profile-text">
                        <h4>Rubab Admin</h4>
                        <p>Administrator</p>
                    </div>
                </div>
            </div>
        </div>

        <div class="page-container">
            <div class="form-card">
                
                <div class="form-banner">
                    <div class="banner-left">
                        <div class="banner-icon">
                            <i class="fa-solid fa-truck-ramp-box"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Purchase Invoice</h2>
                            <p>Record stock entry collections and evaluate automatic supplier ledgers</p>
                        </div>
                    </div>
                    <div class="banner-right-text">Tameer Al Madina</div>
                </div>

                <form method="POST" enctype="multipart/form-data">
                    
                    <div style="overflow-y: auto; flex: 1; padding-bottom: 15px;">
                        <div class="section-header">
                            <i class="fa-solid fa-circle-info"></i> Purchase Parameters
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Date<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-regular fa-calendar"></i>
                                    <input type="date" name="date" value="<?= date('Y-m-d') ?>" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Supplier Origin Target<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-boxes-packing"></i>
                                    <select id="supplierSelect" name="supplier_id" required>
                                        <option value="">Select Supplier</option>
                                        <?php foreach($suppliers as $s){ ?>
                                            <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                                        <?php } ?>
                                        <option value="add_supplier">+ Add New Supplier</option>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group" style="grid-column: span 2;">
                                <label>Attachment / Document</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-paperclip"></i>
                                    <input type="file" name="attachment" style="padding-top: 6px;">
                                </div>
                            </div>
                        </div>

                        <!-- 🆕 NEW SECTION: Gate Pass / Builty / Dispatch Through / Vehicle Size -->
                        <div class="section-header">
                            <i class="fa-solid fa-truck"></i> Dispatch Details
                        </div>

                        <div class="form-grid">
                            <div class="form-group">
                                <label>Gate Pass Number</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-id-card"></i>
                                    <input type="text" name="gate_pass_number" placeholder="e.g. GP-1024">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Builty Number</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-file-lines"></i>
                                    <input type="text" name="builty_number" placeholder="e.g. BLT-5567">
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Dispatch Through</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-truck-fast"></i>
                                    <input type="text" name="dispatch_through" placeholder="e.g. Al-Madina Goods Transport">
                                </div>
                            </div>

                            <!-- 🆕 NEW: Vehicle Size field -->
                            <div class="form-group">
                                <label>Vehicle Size</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-truck-front"></i>
                                    <input type="text" name="vehicle_size" placeholder="e.g. 10 Ton / 20ft Container">
                                </div>
                            </div>
                        </div>
                        <!-- 🆕 END NEW SECTION -->

                        <div class="section-header">
                            <i class="fa-solid fa-layer-group"></i> Incoming Procurement Table
                        </div>

                        <div class="table-wrapper">
                            <table id="purchaseTable">
                                <thead>
                                    <tr>
                                        <th style="width: 40%;">Product</th>
                                        <th style="width: 20%;">Purchase Price (OMR)</th>
                                        <th style="width: 15%;">Quantity</th>
                                        <th style="width: 20%;">Total</th>
                                        <th style="width: 5%; text-align: center;">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <select name="product_id[]" class="product" onchange="loadProductPrice(this)" required>
                                                <option value="">Select Product</option>
                                                <?php foreach($products as $p){ ?>
                                                    <option value="<?= $p['product_id'] ?>" data-price="<?= $p['price_per_piece'] ?>">
                                                        <?= htmlspecialchars($p['product_name']) ?>
                                                    </option>
                                                <?php } ?>
                                                <option value="add_product">+ Add New Product</option>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="number" step="0.001" name="price[]" class="price" onkeyup="calculateRow(this)" onchange="calculateRow(this)" required placeholder="0.000">
                                        </td>
                                        <td>
                                            <input type="number" step="0.001" name="quantity[]" class="qty" onkeyup="calculateRow(this)" onchange="calculateRow(this)" required placeholder="0">
                                        </td>
                                        <td>
                                            <input type="text" class="total" readonly placeholder="0.000">
                                        </td>
                                        <td style="text-align: center;">
                                            <button type="button" class="btn-delete-row" onclick="deleteRow(this)">
                                                <i class="fa-solid fa-trash-can"></i>
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <div class="table-btn-container">
                            <button type="button" class="btn btn-add" onclick="addRow()">
                                <i class="fa-solid fa-plus"></i> Append Row
                            </button>
                        </div>

                        <div class="section-header">
                            <i class="fa-solid fa-calculator"></i> Matrix Aggregations
                        </div>

                        <div class="summary-row">
                            <div class="summary-box">
                                <label>Sub Total</label>
                                <input id="subTotal" value="0.000" readonly>
                            </div>
                            <div class="summary-box" onclick="openPopup('discount')">
                                <label>Discount (Click)</label>
                                <input id="discountDisplay" value="0.000" readonly>
                            </div>
                            <div class="summary-box" onclick="openPopup('tax')">
                                <label>VAT (Click)</label>
                                <input id="taxDisplay" value="0.000" readonly>
                            </div>
                            <div class="summary-box" onclick="openPopup('other')">
                                <label>Other Charges</label>
                                <input id="otherDisplay" value="0.000" readonly>
                            </div>
                            <div class="summary-box">
                                <label>Round Off</label>
                                <input type="number" id="roundOff" value="0" onkeyup="calculateGrand()">
                            </div>
                        </div>

                        <div class="grand-total-section">
                            <div class="grand-box">
                                <label><i class="fa-solid fa-sterling-sign"></i> Total Liability Accumulation (OMR)</label>
                                <input id="grandTotal" value="0.000" readonly>
                            </div>
                        </div>
                    </div>

                    <input type="hidden" name="sub_total" id="hiddenSubTotal">
                    <input type="hidden" name="grand_total" id="hiddenGrandTotal">
                    <input type="hidden" name="discount_amount" id="hiddenDiscount" value="0">
                    <input type="hidden" name="tax_amount" id="hiddenTax" value="0">
                    <input type="hidden" name="other_amount" id="hiddenOther" value="0">
                    <input type="hidden" name="round_off" id="hiddenRound" value="0">

                    <div class="form-actions">
                        <div class="action-left">
                            <button type="submit" class="btn btn-submit">
                                <i class="fa-regular fa-circle-check"></i> Save Purchase
                            </button>
                            <button type="reset" class="btn btn-cancel" onclick="setTimeout(calculateGrand, 50)">
                                <i class="fa-solid fa-arrow-rotate-left"></i> Reset Fields
                            </button>
                        </div>
                        
                        <div class="action-right">
                            <button type="button" class="btn btn-secondary" onclick="window.print()">
                                <i class="fa-solid fa-print"></i> Print
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="shareInvoice()">
                                <i class="fa-solid fa-share-nodes"></i> Share
                            </button>
                        </div>
                    </div>

                </form>

            </div>
        </div>
    </div>
</div>

<div class="popup" id="popupModal">
    <div class="popup-content">
        <div class="popup-title" id="popupTitle">Calculations</div>
        
        <div class="tabs">
            <button type="button" class="tab-btn active-tab" id="priceBtn" onclick="switchMode('price')">Fixed Price</button>
            <button type="button" class="tab-btn" id="percentBtn" onclick="switchMode('percent')">Percentage (%)</button>
        </div>
        
        <input type="number" id="popupValue" placeholder="Enter metric scale value">
        
        <div class="popup-actions">
            <button type="button" class="btn btn-cancel" style="padding: 6px 14px;" onclick="closePopup()">Close</button>
            <button type="button" class="btn btn-secondary" style="background:#0d6efd; padding: 6px 14px;" onclick="applyPopup()">Apply</button>
        </div>
    </div>
</div>

<script>
let currentType = "";
let currentMode = "price";
let values = { tax:0, discount:0, other:0 };

/* NAVIGATION OBSERVERS */
document.addEventListener("change", function(e){
    if(e.target.id === "supplierSelect" && e.target.value === "add_supplier") window.location.href = "suppliers_add.php";
    if(e.target.classList.contains("product") && e.target.value === "add_product") window.location.href = "add_product.php";
});

/* DYNAMIC PRODUCT PRICE LOADING */
function loadProductPrice(el) {
    let row = el.closest("tr");
    let selectedOption = el.options[el.selectedIndex];
    let defaultPrice = parseFloat(selectedOption.dataset.price) || 0;
    
    row.querySelector(".price").value = defaultPrice > 0 ? defaultPrice.toFixed(3) : "";
    calculateRow(el);
}

/* INLINE ENGINE ARITHMETIC */
function calculateRow(el){
    let row = el.closest("tr");
    let qty = parseFloat(row.querySelector(".qty").value) || 0;
    let price = parseFloat(row.querySelector(".price").value) || 0;
    
    row.querySelector(".total").value = (qty * price).toFixed(3);
    calculateGrand();
}

/* TOTAL MATRIX CONSOLIDATION */
function calculateGrand(){
    let sub = 0;
    document.querySelectorAll(".total").forEach(t => { sub += parseFloat(t.value) || 0; });
    document.getElementById("subTotal").value = sub.toFixed(3);

    let round = parseFloat(document.getElementById("roundOff").value) || 0;
    let total = sub - values.discount + values.tax + values.other + round;

    document.getElementById("grandTotal").value = total.toFixed(3);
    document.getElementById("hiddenSubTotal").value = sub.toFixed(3);
    document.getElementById("hiddenGrandTotal").value = total.toFixed(3);
    document.getElementById("hiddenRound").value = round.toFixed(3);
}

/* APPEND TARGET ROWS */
function addRow(){
    let table = document.querySelector("#purchaseTable tbody");
    let row = table.rows[0].cloneNode(true);
    row.querySelectorAll("input").forEach(i => i.value = "");
    row.querySelector("select").selectedIndex = 0;
    table.appendChild(row);
}

/* DELETE SELECTED ROW */
function deleteRow(btn){
    let table = document.querySelector("#purchaseTable tbody");
    if(table.rows.length > 1){
        btn.closest("tr").remove();
        calculateGrand();
    } else {
        alert("At least one product item is mandatory.");
    }
}

/* MODAL INTERFACES CONTROLS */
function openPopup(type){
    currentType = type;
    currentMode = "price";
    document.getElementById("popupModal").style.display = "flex";
    document.getElementById("popupTitle").innerText = "Configure " + type.toUpperCase();
    document.getElementById("popupValue").value = "";
    switchMode("price");
}

/* CLOSE POPUP CONTROLS */
function closePopup(){ document.getElementById("popupModal").style.display = "none"; }

function switchMode(mode){
    currentMode = mode;
    document.getElementById("priceBtn").classList.toggle("active-tab", mode === "price");
    document.getElementById("percentBtn").classList.toggle("active-tab", mode === "percent");
}

function applyPopup(){
    let val = parseFloat(document.getElementById("popupValue").value) || 0;
    let sub = parseFloat(document.getElementById("subTotal").value) || 0;

    if(currentMode === "percent") val = sub * (val / 100);

    values[currentType] = val;
    document.getElementById(currentType + "Display").value = val.toFixed(3);
    document.getElementById("hidden" + currentType.charAt(0).toUpperCase() + currentType.slice(1)).value = val.toFixed(3);
    
    closePopup();
    calculateGrand();
}

function toggleMobileSidebar() {
    let sidebar = document.querySelector('aside, .sidebar, [class*="sidebar"]');
    let overlay = document.getElementById('sidebarOverlay');
    if(sidebar) sidebar.classList.toggle('active');
    if(overlay) overlay.style.display = overlay.style.display === 'block' ? 'none' : 'block';
}

function shareInvoice() {
    alert("Share feature triggered.");
}
</script>
</body>
</html>