<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

/* 👥 1. SUPPLIERS NIKALNA FOR DROPDOWN */
$suppliers_query = "SELECT id, name FROM suppliers ORDER BY name ASC";
$suppliers_result = $conn->query($suppliers_query);

/* 📦 2. PRODUCTS NIKALNA FOR DYNAMIC SELECT FIELDS */
$products_query = "SELECT product_id, product_name, price_per_piece FROM products ORDER BY product_name ASC";
$products_result = $conn->query($products_query);
$products_array = [];
while ($p_row = $products_result->fetch_assoc()) {
    $products_array[] = $p_row;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Create Purchase Quotation Request</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
body { background:#eef2f7; font-family:'Poppins',sans-serif; margin:0; padding:20px; color:#333; }
.wrapper { max-width:1100px; margin:20px auto; background:#fff; border-radius:14px; box-shadow:0 8px 25px rgba(0,0,0,0.05); padding:25px; }
.header { display:flex; align-items:center; gap:10px; color:#0d6efd; border-bottom:2px solid #f4f5f7; padding-bottom:15px; margin-bottom:20px; }
.header h2 { margin:0; font-size:22px; font-weight:700; }

.meta-grid { display:grid; grid-template-columns: repeat(3, 1fr); gap:15px; background:#f8f9fa; padding:15px; border-radius:10px; margin-bottom:20px; }
.meta-item h4 { margin:0 0 5px 0; font-size:12px; color:#888; text-transform:uppercase; }
.input-field { width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; font-family:inherit; font-size:14px; box-sizing:border-box; background:#fff; }

table { width:100%; border-collapse:collapse; margin-bottom:15px; }
th { background:#0d6efd; color:#fff; padding:12px; font-size:13px; text-align:left; }
td { padding:10px 5px; border-bottom:1px solid #eee; }

.btn { padding:9px 18px; border-radius:6px; border:none; font-weight:600; font-size:13px; cursor:pointer; text-decoration:none; transition:0.2s; display:inline-block; }
.btn-cancel { background:#e5e7eb; color:#4b5563; }
.btn-add-row { background:#198754; color:#fff; margin-bottom:20px; }
.btn-add-row:hover { background:#157347; }
.btn-remove { background:#dc3545; color:#fff; padding:5px 10px; font-size:12px; border-radius:4px; }
.btn-save { background:#0d6efd; color:#fff; }
.btn-save:hover { background:#0b58ca; }

.summary-container { display:flex; justify-content:flex-end; margin-top:20px; }
.summary-box { width:350px; background:#f8f9fa; padding:15px; border-radius:10px; display:flex; flex-direction:column; gap:10px; }
.summary-row { display:flex; justify-content:between; align-items:center; font-size:14px; }
.summary-row span:first-child { flex:1; color:#555; }
.summary-row .summary-input { width:120px; text-align:right; }
.grand-total-row { border-top:2px dashed #ddd; padding-top:10px; font-size:17px; font-weight:700; color:#0d6efd; }
</style>
</head>
<body>

<div class="wrapper">
    <form action="purchase_quota_process.php" method="POST">
        
        <div class="header">
            <span style="font-size:24px;">📝</span>
            <h2>Create Purchase Quotation Request</h2>
        </div>

        <div class="meta-grid">
            <div class="meta-item">
                <h4>Select Supplier *</h4>
                <select name="supplier_id" class="input-field" required>
                    <option value="">-- Choose Vendor / Supplier --</option>
                    <?php while($sup = $suppliers_result->fetch_assoc()): ?>
                        <option value="<?= $sup['id'] ?>"><?= htmlspecialchars($sup['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="meta-item">
                <h4>Date Issued *</h4>
                <input type="date" name="date_issued" class="input-field" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="meta-item">
                <h4>Valid Till / Expiry *</h4>
                <input type="date" name="valid_till" class="input-field" value="<?= date('Y-m-d', strtotime('+1 month')) ?>" required>
            </div>
        </div>

        <table id="quota_table">
            <thead>
                <tr>
                    <th style="width: 45%;">Product Name</th>
                    <th style="width: 15%; text-align: center;">Estimated Price (OMR)</th>
                    <th style="width: 15%; text-align: center;">Required Qty</th>
                    <th style="width: 15%; text-align: right; padding-right:15px;">Total Amount</th>
                    <th style="width: 10%; text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                </tbody>
        </table>

        <button type="button" class="btn btn-add-row" onclick="addNewRow()">+ Add Product Item</button>

        <div class="summary-container">
            <div class="summary-box">
                <div class="summary-row">
                    <span>Sub Total:</span>
                    <strong id="sub_total_display">0.000 OMR</strong>
                    <input type="hidden" name="sub_total" id="sub_total_input" value="0">
                </div>
                
                <div class="summary-row">
                    <span>(+) Tax Amount:</span>
                    <input type="number" step="0.001" name="tax_amount" id="tax_amount" class="input-field summary-input" value="0.000" oninput="calculateGrandTotals()">
                </div>
                
                <div class="summary-row">
                    <span>(-) Discount Setup:</span>
                    <input type="number" step="0.001" name="discount_amount" id="discount_amount" class="input-field summary-input" value="0.000" oninput="calculateGrandTotals()">
                </div>

                <div class="summary-row grand-total-row">
                    <span>Grand Total:</span>
                    <span id="grand_total_display">0.000 OMR</span>
                    <input type="hidden" name="grand_total" id="grand_total_input" value="0">
                </div>
            </div>
        </div>

        <div style="display:flex; justify-content:space-between; margin-top:30px; border-top:1px solid #eee; padding-top:20px;">
            <a href="purchase_quota_list.php" class="btn btn-cancel">Cancel & Back</a>
            <button type="submit" class="btn btn-save">Save Quotation Request</button>
        </div>
    </form>
</div>

<script>
// PHP products array backend se JavaScript global namespace array object mein encode ho raha hai
const productsData = <?= json_encode($products_array); ?>;
let rowIndex = 0;

// Auto row add initialization on window render lifecycle
window.onload = function() {
    addNewRow();
};

function addNewRow() {
    let tbody = document.querySelector("#quota_table tbody");
    let tr = document.createElement("tr");
    tr.setAttribute("id", "row_" + rowIndex);

    // Products option dropdown components creation loops
    let options = '<option value="">-- Choose Product --</option>';
    productsData.forEach(function(prod) {
        options += `<option value="${prod.product_id}" data-price="${prod.price_per_piece}">${prod.product_name}</option>`;
    });

    tr.innerHTML = `
        <td>
            <select name="items[${rowIndex}][product_id]" class="input-field product-select" onchange="assignProductPrice(this)" required>
                ${options}
            </select>
        </td>
        <td>
            <input type="number" step="0.001" name="items[${rowIndex}][price]" class="input-field row-price" value="0.000" style="text-align:center;" oninput="calculateRowTotal(this)" required>
        </td>
        <td>
            <input type="number" name="items[${rowIndex}][qty]" class="input-field row-qty" value="1" min="1" style="text-align:center;" oninput="calculateRowTotal(this)" required>
        </td>
        <td style="text-align:right; font-weight:600; padding-right:15px;" class="row-total-text">
            0.000 OMR
        </td>
        <td style="text-align:center;">
            <button type="button" class="btn btn-remove" onclick="removeRow(this)">Remove</button>
        </td>
    `;
    
    tbody.appendChild(tr);
    rowIndex++;
}

function removeRow(button) {
    let tbody = document.querySelector("#quota_table tbody");
    if(tbody.rows.length > 1) {
        button.closest("tr").remove();
        calculateGrandTotals();
    } else {
        alert("At least one quotation item row is strictly required inside invoices.");
    }
}

function assignProductPrice(selectElement) {
    let tr = selectElement.closest("tr");
    let selectedOption = selectElement.options[selectElement.selectedIndex];
    let basePrice = parseFloat(selectedOption.getAttribute("data-price")) || 0;
    
    tr.querySelector(".row-price").value = basePrice.toFixed(3);
    calculateRowTotal(selectElement);
}

function calculateRowTotal(element) {
    let tr = element.closest("tr");
    let price = parseFloat(tr.querySelector(".row-price").value) || 0;
    let qty = parseInt(tr.querySelector(".row-qty").value) || 0;
    
    let total = price * qty;
    tr.querySelector(".row-total-text").innerText = total.toFixed(3) + " OMR";
    
    calculateGrandTotals();
}

function calculateGrandTotals() {
    let subTotal = 0;
    document.querySelectorAll(".row-total-text").forEach(function(el) {
        subTotal += parseFloat(el.innerText) || 0;
    });

    let tax = parseFloat(document.getElementById("tax_amount").value) || 0;
    let discount = parseFloat(document.getElementById("discount_amount").value) || 0;
    
    let grandTotal = (subTotal + tax) - discount;
    if(grandTotal < 0) grandTotal = 0;

    // UI elements sync updates logs mapping
    document.getElementById("sub_total_display").innerText = subTotal.toFixed(3) + " OMR";
    document.getElementById("sub_total_input").value = subTotal.toFixed(3);
    
    document.getElementById("grand_total_display").innerText = grandTotal.toFixed(3) + " OMR";
    document.getElementById("grand_total_input").value = grandTotal.toFixed(3);
}
</script>

</body>
</html>