<?php
ob_start();

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

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

/* 🛠️ COMPLETE INVOICE SUBMISSION HANDLER WITH ITEMS, TAX/DISCOUNT & ATTACHMENT */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['customer_id'])) {
    
    $customer_id = intval($_POST['customer_id']);
    $date = $_POST['date'];
    $round_off = floatval($_POST['round_off'] ?? 0);
    
    // Form se real-time Javascript calculated dynamic numeric values ko receive karna
    $tax_amount = floatval($_POST['tax_amount'] ?? 0);
    $discount_amount = floatval($_POST['discount_amount'] ?? 0);
    $other_amount = floatval($_POST['other_amount'] ?? 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'] ?? '');
    
    $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;
            
            // User ki manually enter ki hui price post method se receive hogi
            $price = floatval($_POST['price'][$key] ?? 0); 
            
            $item_total = $price * $qty;
            $sub_total += $item_total;

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

    // Final Grand Total Arithmetic
    $grand_total = $sub_total + $tax_amount + $other_amount - $discount_amount + $round_off; 
    
    if ($grand_total > 0 && $customer_id > 0 && count($items_to_insert) > 0) {
        
        // 📸 FILE ATTACHMENT PROCESSING ENGINE (Camera & Gallery Input)
        $file_path = "";
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = 'uploads/';
            // Agar directory majood nahi hai to auto-create ho jaye
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
            // Security ke liye unique filename generate karna
            $new_filename = 'inv_' . time() . '_' . uniqid() . '.' . $file_extension;
            $target_file = $upload_dir . $new_filename;
            
            // Files types verification (Images aur Documents)
            $allowed_types = ['jpg', 'jpeg', 'png', 'gif', 'pdf', 'doc', 'docx', 'xls', 'xlsx'];
            if (in_array($file_extension, $allowed_types)) {
                if (move_uploaded_file($_FILES['attachment']['tmp_name'], $target_file)) {
                    $file_path = $target_file;
                }
            }
        }
        
        // Exact active breakdowns format ko description column me save karna JSON state me (With Attachment File Link)
        $invoice_summary = json_encode([
            'sub_total' => $sub_total,
            'tax' => $tax_amount,
            'discount' => $discount_amount,
            'other' => $other_amount,
            'round_off' => $round_off,
            'attachment' => $file_path // Encoded file state string inside standard log reference
        ]);
        
        $type = "Debit"; 
        $reference_type = "customer";

        // 1. Core ledger insert statement (🆕 gate_pass_number, bilty_number, dispatch_through add kiye)
        // NOTE: vehicle_size ka column "transactions" table mein maujood nahi hai, isliye is insert mein shamil nahi kiya
        $stmt_trans = $conn->prepare("INSERT INTO transactions (reference_id, reference_type, date, description, type, amount, gate_pass_number, bilty_number, dispatch_through) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt_trans->bind_param("issssdsss", $customer_id, $reference_type, $date, $invoice_summary, $type, $grand_total, $gate_pass_number, $builty_number, $dispatch_through);
        
        if ($stmt_trans->execute()) {
            $transaction_id = $stmt_trans->insert_id; // Current system reference code

            // 2. Renamed relational structure loop mapping
            $stmt_item = $conn->prepare("INSERT INTO sale_items (transaction_id, product_id, quantity, price, total) VALUES (?, ?, ?, ?, ?)");
            foreach ($items_to_insert as $item) {
                $stmt_item->bind_param("iiidd", $transaction_id, $item['product_id'], $item['quantity'], $item['price'], $item['total']);
                $stmt_item->execute();
            }
            $stmt_item->close();

            // Direct route shifting to invoice print layout
            header("Location: invoice_view.php?id=" . $transaction_id); 
            exit();
        } else {
            echo "<script>alert('Error updating ledger: " . $conn->error . "');</script>";
        }
        $stmt_trans->close();
    }
}

/* ALWAYS FRESH DATA */
$customers = $conn->query("SELECT id, name FROM customers ORDER BY id DESC")->fetch_all(MYSQLI_ASSOC);
$products  = $conn->query("SELECT product_id, product_name FROM products ORDER BY product_id DESC")->fetch_all(MYSQLI_ASSOC); // Removed price from select query since we don't want it
?>

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

/* Page Setup */
.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 #FF6B00;
    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: #FF6B00;
    font-size: 16px;
}

/* Fluid Form Grid Config */
.form-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr); /* Laptop mesh changed from 2 to 3 to adjust attachment input seamlessly */
    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: #FF6B00;
    box-shadow: 0 0 0 2px rgba(255, 107, 0, 0.1);
}

/* File specific padding for upload styling */
.input-wrapper input[type="file"] {
    padding-top: 8px;
    cursor: pointer;
}

/* Item Table Presentation Layer */
.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;
}

/* Calculation Bottom 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: #FFF5ED;
    border: 1px solid #FFE3D1;
    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 #FFD0B3;
    border-radius: 6px;
    padding: 0 15px;
    font-size: 16px;
    font-weight: 700;
    color: #FF6B00;
    background: #FFFFFF;
    text-align: right;
    outline: none;
}

/* Interactive Overlay Dialog System */
.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 textarea {
    width: 100%;
    height: 80px;
    border: 1px solid #CBD5E1;
    border-radius: 6px;
    padding: 8px 12px;
    font-size: 13px;
    resize: none;
    outline: none;
    margin-top: 10px;
}

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

/* Custom Action Buttons */
.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: #FF6B00; 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 th:nth-child(1) { width: 35% !important; }
    table th:nth-child(2) { width: 25% !important; }
    table th:nth-child(3) { width: 20% !important; }
    table th:nth-child(4) { width: 20% !important; }
    
    .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-file-invoice"></i>
                        </div>
                        <div class="banner-text">
                            <h2>Sales Invoice</h2>
                            <p>Generate fresh professional customer billing records and transactions</p>
                        </div>
                    </div>
                    <div class="banner-right-text">Tameer Al Madina</div>
                </div>

                <!-- 🔄 CHANGED: added enctype attribute to support attachments natively -->
                <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> Invoice Directives
                        </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" required value="<?php echo date('Y-m-d'); ?>">
                                </div>
                            </div>

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

                            <!-- 📸 NEW: Document/Image Attachment Element with capture functionality for Mobile Camera -->
                            <div class="form-group">
                                <label>Document Attachment</label>
                                <div class="input-wrapper">
                                    <i class="fa-solid fa-camera"></i>
                                    <input type="file" name="attachment" id="invoiceAttachment" accept="image/*,application/pdf,application/msword,application/vnd.ms-excel">
                                </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-cubes"></i> Line Items Structure
                        </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'] ?>">
                                                        <?= $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)" value="0.000" placeholder="0.000" required>
                                        </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> Add More Rows
                            </button>
                        </div>

                        <div class="section-header">
                            <i class="fa-solid fa-calculator"></i> Valuations & Dynamic Modifiers
                        </div>

                        <div class="summary-row">
                            <div class="summary-box">
                                <label>Sub Total</label>
                                <input type="text" id="subTotal" readonly value="0.000">
                            </div>
                            <div class="summary-box">
                                <label>VAT(Click to Config)</label>
                                <input type="text" id="taxDisplay" readonly value="0.000" onclick="openPopup('tax')">
                            </div>
                            <div class="summary-box">
                                <label>Discount (Click to Config)</label>
                                <input type="text" id="discountDisplay" readonly value="0.000" onclick="openPopup('discount')">
                            </div>
                            <div class="summary-box">
                                <label>Other Charges</label>
                                <input type="text" id="otherDisplay" readonly value="0.000" onclick="openPopup('other')">
                            </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-receipt"></i> Document Grand Valuation (OMR)</label>
                                <input type="text" id="grandTotal" readonly value="0.000">
                            </div>
                        </div>
                    </div>

                    <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">

                    <div class="form-actions">
                        <div class="action-left">
                            <button type="submit" class="btn btn-submit">
                                <i class="fa-regular fa-floppy-disk"></i> Save Invoice
                            </button>
                            <button type="reset" class="btn btn-cancel" onclick="setTimeout(calculateGrand, 50)">
                                <i class="fa-solid fa-arrow-rotate-left"></i> Reset
                            </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="popup">
    <div class="popup-content">
        <div class="popup-title" id="popupTitle">Modifier Config</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 numeric scale value">
        <textarea id="popupDescription" placeholder="Provide adjustment details/notes..."></textarea>

        <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-submit" style="padding: 6px 14px;" onclick="applyPopup()">Apply</button>
        </div>
    </div>
</div>

<script>
let currentType = "";
let currentMode = "price";

let values = { tax: 0, discount: 0, other: 0 };
let descriptions = { tax: "", discount: "", other: "" };

/* NAVIGATION WATCHERS */
document.addEventListener("change", function(e){
    if(e.target.id === "customerSelect" && e.target.value === "add_customer"){
        window.location.href = "customers_add.php";
    }
    if(e.target.classList.contains("product" ) && e.target.value === "add_product"){
        window.location.href = "add_product.php";
    }
});

/* ROW ARITHMETIC ENGINE */
function calculateRow(el){
    let row = el.parentElement.parentElement;
    let qty = row.querySelector(".qty").value;
    let priceInput = row.querySelector(".price");
    
    let price = priceInput.value || 0;
    row.querySelector(".total").value = (qty * price).toFixed(3);

    calculateGrand();
}

/* TOTAL CONSOLIDATION ENGINE */
function calculateGrand(){
    let sub = 0;
    document.querySelectorAll(".total").forEach(t=>{
        sub += Number(t.value || 0);
    });

    document.getElementById("subTotal").value = sub.toFixed(3);
    let round = Number(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);
}

/* CLONE NEW MESH ROWS */
function addRow(){
    let table = document.querySelector("#salesTable tbody");
    let row = table.rows[0].cloneNode(true);

    row.querySelectorAll("input").forEach(i=>{
        if(i.classList.contains("price")) {
            i.value = "0.000"; 
        } else {
            i.value = "";
        }
    });
    row.querySelector("select").selectedIndex = 0;

    table.appendChild(row);
}

/* INTERACTIVE DIALOG CONTROLS */
function openPopup(type){
    currentType = type;
    document.getElementById("popup").style.display = "flex";
    document.getElementById("popupTitle").innerText = "Configure " + type.charAt(0).toUpperCase() + type.slice(1);
    document.getElementById("popupValue").value = values[type];
    document.getElementById("popupDescription").value = descriptions[type];
    switchMode("price");
}

/* SMART DEVICE FEATURE TRIGGER */
// Auto-detect mobile environment to switch direct camera shutter stream trigger seamlessly
document.addEventListener("DOMContentLoaded", function() {
    const attachInput = document.getElementById("invoiceAttachment");
    if(/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
        // Safe check for smartphone environment to facilitate quick image logging
        attachInput.setAttribute("placeholder", "Tap to take a picture or open gallery");
    }
});

function closePopup(){
    document.getElementById("popup").style.display = "none";
}

function switchMode(mode){
    currentMode = mode;
    document.getElementById("priceBtn").classList.remove("active-tab");
    document.getElementById("percentBtn").classList.remove("active-tab");

    if(mode === "price"){
        document.getElementById("priceBtn").classList.add("active-tab");
    } else {
        document.getElementById("percentBtn").classList.add("active-tab");
    }
}

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

    if(currentMode === "percent"){
        value = sub * (value / 100);
    }

    values[currentType] = value;
    descriptions[currentType] = document.getElementById("popupDescription").value;

    if(currentType === "tax"){
        document.getElementById("taxDisplay").value = value.toFixed(3);
        document.getElementById("hiddenTax").value = value.toFixed(3);
    }
    if(currentType === "discount"){
        document.getElementById("discountDisplay").value = value.toFixed(3);
        document.getElementById("hiddenDiscount").value = value.toFixed(3);
    }
    if(currentType === "other"){
        document.getElementById("otherDisplay").value = value.toFixed(3);
        document.getElementById("hiddenOther").value = value.toFixed(3);
    }

    calculateGrand();
    closePopup();
}

/* SYSTEM WEBSHARE COMPONENT */
function shareInvoice(){
    let text = "🧾 Invoice Total: " + document.getElementById("grandTotal").value + " OMR";
    if(navigator.share){
        navigator.share({ title: 'Sales Invoice Outflow', text: text });
    } else {
        alert("Native web sharing architecture is not supported on this device ecosystem.");
    }
}

/* SIDEBAR LAYOUT INTERACTION OVERLAY Toggle */
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>