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

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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['customer_id'])) {
    $customer_id = intval($_POST['customer_id']);
    $date = $_POST['date'];
    $valid_until = $_POST['valid_until'];
    $payment_terms = $_POST['payment_terms'];
    $round_off = floatval($_POST['round_off'] ?? 0);
    
    $tax_amount = floatval($_POST['tax_amount'] ?? 0);
    $discount_amount = floatval($_POST['discount_amount'] ?? 0);
    $other_amount = floatval($_POST['other_amount'] ?? 0);
    
    // Manually typed terms collect karna array se
    $c_terms = isset($_POST['custom_terms']) ? array_filter($_POST['custom_terms']) : [];
    $custom_terms_json = json_encode($c_terms);

    $sub_total = 0;
    $items_to_insert = [];

    if (isset($_POST['product_id']) && is_array($_POST['product_id'])) {
        foreach ($_POST['product_id'] as $key => $p_id) {
            $qty = intval($_POST['quantity'][$key] ?? 0);
            if($qty <= 0 || empty($p_id)) continue;
            
            $stmt_p = $conn->prepare("SELECT price_per_piece FROM products WHERE product_id = ?");
            $stmt_p->bind_param("i", $p_id);
            $stmt_p->execute();
            $stmt_p->bind_result($price);
            $stmt_p->fetch();
            $stmt_p->close();
            
            $item_total = $price * $qty;
            $sub_total += $item_total;

            $items_to_insert[] = [
                'product_id' => $p_id,
                'price' => $price,
                'quantity' => $qty,
                'total' => $item_total
            ];
        }
    }

    $grand_total = $sub_total + $tax_amount + $other_amount - $discount_amount + $round_off; 
    
    if ($grand_total > 0 && $customer_id > 0 && count($items_to_insert) > 0) {
        $summary_data = json_encode([
            'sub_total' => $sub_total,
            'tax' => $tax_amount,
            'discount' => $discount_amount,
            'other' => $other_amount,
            'round_off' => $round_off
        ]);
        
        // quotations table mein save karna (No Ledger Impact)
        $stmt_q = $conn->prepare("INSERT INTO quotations (customer_id, date, valid_until, payment_terms, custom_terms, summary_data, amount, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'Pending')");
        $stmt_q->bind_param("isssssd", $customer_id, $date, $valid_until, $payment_terms, $custom_terms_json, $summary_data, $grand_total);
        
        if ($stmt_q->execute()) {
            $quotation_id = $stmt_q->insert_id;

            $stmt_item = $conn->prepare("INSERT INTO quotation_items (quotation_id, product_id, quantity, price, total) VALUES (?, ?, ?, ?, ?)");
            foreach ($items_to_insert as $item) {
                $stmt_item->bind_param("iiidd", $quotation_id, $item['product_id'], $item['quantity'], $item['price'], $item['total']);
                $stmt_item->execute();
            }
            $stmt_item->close();

            header("Location: quote_list.php"); 
            exit();
        } else {
            echo "<script>alert('Error: " . $conn->error . "');</script>";
        }
        $stmt_q->close();
    }
}

$customers = $conn->query("SELECT id, name FROM customers ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);
$products  = $conn->query("SELECT product_id, product_name, price_per_piece FROM products ORDER BY product_id DESC")->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Sales Quotation - 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 Frame Layout */
.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;
}

/* Base Master Container Sheet */
.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: 13px;
    font-weight: 600;
    background: rgba(13, 110, 253, 0.2);
    border: 1px solid rgba(13, 110, 253, 0.4);
    padding: 4px 14px;
    border-radius: 20px;
    color: #63B3ED;
}

.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;
}

/* Dynamic Inputs Blueprint Layout Grid */
.form-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr); 
    gap: 15px;
    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: 12px;
    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 12px 5px 35px;
    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);
}

/* Quotation Dynamic Lines Item Table */
.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;
}

table td input[readonly] {
    background: #F1F5F9;
    border-color: #E2E8F0;
    color: #64748B;
}

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

/* Custom Terms Dashboard Panel */
.terms-panel {
    margin: 15px 30px;
    padding: 15px 20px;
    background: #F8FAFC;
    border: 1px dashed #A4CDFF;
    border-radius: 8px;
}

.terms-panel h4 {
    font-size: 13px;
    font-weight: 600;
    color: #0A192F;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 6px;
}

.terms-inputs-stack {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.terms-inputs-stack input {
    height: 34px;
    border: 1px solid #E2E8F0;
    border-radius: 6px;
    padding: 0 12px;
    font-size: 13px;
    outline: none;
}

/* Matrix Numerical Analysis Blocks */
.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;
}

/* Modifier Modal Layers Overlay */
.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;
}

/* Interactive Base Functional Controls */
.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; text-decoration: none; }
.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; }
    .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; }
    .terms-panel { margin: 10px; padding: 12px; }
    .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">
        
        <!-- Top Navigation Row Layer -->
        <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>

        <!-- Master Operations Sheet Workspace -->
        <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-file-invoice"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Create Sales Quotation / Estimate</h2>
                            <p>Draft structural procurement projections and print customer offers</p>
                        </div>
                    </div>
                    <div class="banner-right-text"><i class="fa-solid fa-shield-halved"></i> Quotation Mode (No Ledger Effect)</div>
                </div>

                <form method="POST">
                    
                    <div style="overflow-y: auto; flex: 1; padding-bottom: 15px;">
                        <div class="section-header">
                            <i class="fa-solid fa-sliders"></i> Quotation 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>Valid Until (Date)<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-calendar-check"></i>
                                    <input type="date" name="valid_until" required>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Target Customer<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-user-tie"></i>
                                    <select name="customer_id" required>
                                        <option value="">Select Customer</option>
                                        <?php foreach($customers as $c){ echo "<option value='{$c['id']}'>{$c['name']}</option>"; } ?>
                                    </select>
                                </div>
                            </div>

                            <div class="form-group">
                                <label>Payment Milestone Terms<span class="required">*</span></label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-handshake-angle"></i>
                                    <select name="payment_terms" required>
                                        <option value="Cash on Delivery">Cash on Delivery</option>
                                        <option value="15 Days Credit">15 Days Credit</option>
                                        <option value="30 Days Credit">30 Days Credit</option>
                                        <option value="50% Advance / 50% Delivery">50% Advance / 50% Delivery</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="section-header">
                            <i class="fa-solid fa-boxes-stacked"></i> Estimations Allocation Table
                        </div>

                        <div class="table-wrapper">
                            <table id="salesTable">
                                <thead>
                                    <tr>
                                        <th style="width: 45%;">Product</th>
                                        <th style="width: 15%;">Price (OMR)</th>
                                        <th style="width: 15%;">Quantity</th>
                                        <th style="width: 25%;">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <select name="product_id[]" class="product" onchange="calculateRow(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 } ?>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" class="price" readonly placeholder="0.000">
                                        </td>
                                        <td>
                                            <input type="number" name="quantity[]" class="qty" onkeyup="calculateRow(this)" required placeholder="0">
                                        </td>
                                        <td>
                                            <input type="text" class="total" readonly placeholder="0.000">
                                        </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 Product Line
                            </button>
                        </div>

                        <div class="terms-panel">
                            <h4><i class="fa-solid fa-pen-to-square"></i> Manual Custom Terms &amp; Conditions</h4>
                            <div class="terms-inputs-stack">
                                <input type="text" name="custom_terms[]" placeholder="Condition 1: e.g. Price includes transport/unloading charges.">
                                <input type="text" name="custom_terms[]" placeholder="Condition 2: e.g. Delivery will be done within 3 days.">
                                <input type="text" name="custom_terms[]" placeholder="Condition 3: e.g. Submitted rates are final.">
                            </div>
                        </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>Tax (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" name="round_off" value="0" onkeyup="calculateGrand()">
                            </div>
                        </div>

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

                    <!-- Valuation hidden registers -->
                    <input type="hidden" name="tax_amount" id="hiddenTax" value="0">
                    <input type="hidden" name="discount_amount" id="hiddenDiscount" value="0">
                    <input type="hidden" name="other_amount" id="hiddenOther" value="0">

                    <!-- Actions Panel Operational Matrix Footer -->
                    <div class="form-actions">
                        <div class="action-left">
                            <button type="submit" class="btn btn-submit">
                                <i class="fa-regular fa-circle-check"></i> Save Quotation
                            </button>
                            <a href="quote_list.php" class="btn btn-cancel">
                                <i class="fa-solid fa-xmark"></i> Abort / Cancel
                            </a>
                        </div>
                        
                        <div class="action-right">
                            <button type="button" class="btn btn-secondary" onclick="window.print()">
                                <i class="fa-solid fa-print"></i> Print Blueprint
                            </button>
                        </div>
                    </div>

                </form>

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

<!-- Config Dialog Modals Container -->
<div class="popup" id="popup">
    <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 scale metric 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 = "", currentMode = "price";
let values = { tax:0, discount:0, other:0 };

/* ROW MULTIPLICATION ENGINE */
function calculateRow(el){
    let row = el.closest("tr");
    let product = row.querySelector(".product");
    let qty = parseFloat(row.querySelector(".qty").value) || 0;
    let price = parseFloat(product.options[product.selectedIndex].dataset.price) || 0;
    row.querySelector(".price").value = price.toFixed(3);
    row.querySelector(".total").value = (qty * price).toFixed(3);
    calculateGrand();
}

/* TOTAL NET AGGREGATIONS CONSOLIDATOR */
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 + Number(values.tax) + Number(values.other) - Number(values.discount) + round;
    document.getElementById("grandTotal").value = total.toFixed(3);
}

/* TABLE CLONE EXTENSION INTERFACE */
function addRow(){
    let table = document.querySelector("#salesTable tbody");
    let row = table.rows[0].cloneNode(true);
    row.querySelectorAll("input").forEach(i => i.value = "");
    row.querySelector("select").selectedIndex = 0;
    table.appendChild(row);
}

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

function closePopup(){ document.getElementById("popup").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 value = parseFloat(document.getElementById("popupValue").value) || 0;
    let sub = parseFloat(document.getElementById("subTotal").value) || 0;
    
    if(currentMode === "percent") value = sub * (value / 100);
    
    values[currentType] = value;
    document.getElementById(currentType + "Display").value = value.toFixed(3);
    document.getElementById("hidden" + currentType.charAt(0).toUpperCase() + currentType.slice(1)).value = value.toFixed(3);
    
    calculateGrand();
    closePopup();
}

/* RESPONSIVE TOGGLE VIEW OVERLAY */
function toggleMobileSidebar() {
    const sidebarElements = document.querySelectorAll('aside, .sidebar, [class*="sidebar"]');
    const overlay = document.getElementById('sidebarOverlay');
    
    sidebarElements.forEach(sidebar => {
        sidebar.classList.toggle('active');
    });
    
    if(sidebarElements[0] && sidebarElements[0].classList.contains('active')) {
        overlay.style.display = 'block';
    } else {
        overlay.style.display = 'none';
    }
}
</script>
</body>
</html>