<?php
session_start();
require_once 'config/config.php';
require_once 'auth/check_auth.php';

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

$pageTitle = 'Advanced Receipts & Invoices';
$currentPage = 'receipts-invoices';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo $pageTitle; ?> | KSO Chandigarh</title>
    
    <!-- AdminLTE CSS -->
    <link rel="stylesheet" href="dist/css/adminlte.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <!-- Summernote -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css">
    
    <style>
        .receipts-header {
            background: linear-gradient(135deg, #a8e6cf 0%, #7fcdcd 100%);
            color: white;
            border-radius: 15px;
            padding: 25px;
            margin-bottom: 25px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .receipt-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #28a745;
            transition: all 0.3s ease;
        }
        
        .receipt-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .invoice-builder {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
            margin-bottom: 20px;
            border: 2px dashed #dee2e6;
            transition: all 0.3s ease;
        }
        
        .invoice-builder:hover {
            border-color: #007bff;
            background: #e3f2fd;
        }
        
        .template-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }
        
        .template-card {
            background: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            border: 2px solid #dee2e6;
            transition: all 0.3s ease;
        }
        
        .template-card:hover {
            border-color: #007bff;
            transform: translateY(-2px);
        }
        
        .template-card.active {
            border-color: #28a745;
            background: #e8f5e8;
        }
        
        .invoice-preview {
            background: white;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            min-height: 500px;
        }
        
        .line-item {
            border-bottom: 1px solid #eee;
            padding: 10px 0;
        }
        
        .line-item:last-child {
            border-bottom: none;
        }
        
        .payment-status {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .payment-status.paid {
            background: #d4edda;
            color: #155724;
        }
        
        .payment-status.pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .payment-status.overdue {
            background: #f8d7da;
            color: #721c24;
        }
        
        .auto-calculation {
            background: #e8f5e8;
            border: 1px solid #c3e6cb;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .qr-code-container {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            margin-top: 20px;
        }
        
        .digital-signature {
            border: 2px dashed #007bff;
            border-radius: 8px;
            padding: 20px;
            text-align: center;
            margin-top: 20px;
        }
        
        .audit-trail {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-top: 15px;
        }
        
        .batch-actions {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 80px;
            color: rgba(0,0,0,0.1);
            font-weight: bold;
            z-index: 1;
        }
        
        .analytics-widget {
            background: white;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
    </style>
</head>

<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">
    <!-- Include header -->
    <?php include 'templates/header.php'; ?>
    
    <!-- Include sidebar -->
    <?php include 'templates/sidebar.php'; ?>
    
    <!-- Content Wrapper -->
    <div class="content-wrapper">
        <!-- Content Header -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0">
                            <i class="fas fa-file-invoice-dollar text-primary"></i> Advanced Receipts & Invoices
                        </h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item active">Receipts & Invoices</li>
                        </ol>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">
                
                <!-- Receipts Header -->
                <div class="receipts-header">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalReceipts">0</h3>
                                <p class="mb-0">Total Receipts</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="totalInvoices">0</h3>
                                <p class="mb-0">Total Invoices</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="pendingAmount">₹0</h3>
                                <p class="mb-0">Pending Amount</p>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="text-center">
                                <h3 class="mb-1" id="monthlyRevenue">₹0</h3>
                                <p class="mb-0">Monthly Revenue</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Invoice Builder -->
                <div class="row">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-plus"></i> Create New Invoice/Receipt
                                </h3>
                                <div class="card-tools">
                                    <div class="btn-group">
                                        <button class="btn btn-primary btn-sm" onclick="createInvoice()">
                                            <i class="fas fa-file-invoice"></i> New Invoice
                                        </button>
                                        <button class="btn btn-success btn-sm" onclick="createReceipt()">
                                            <i class="fas fa-receipt"></i> New Receipt
                                        </button>
                                    </div>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="invoice-builder">
                                    <h6>Template Selection</h6>
                                    <div class="template-selector">
                                        <div class="template-card active" data-template="standard">
                                            <i class="fas fa-file-alt fa-2x mb-2"></i>
                                            <h6>Standard</h6>
                                        </div>
                                        <div class="template-card" data-template="professional">
                                            <i class="fas fa-briefcase fa-2x mb-2"></i>
                                            <h6>Professional</h6>
                                        </div>
                                        <div class="template-card" data-template="modern">
                                            <i class="fas fa-desktop fa-2x mb-2"></i>
                                            <h6>Modern</h6>
                                        </div>
                                        <div class="template-card" data-template="minimal">
                                            <i class="fas fa-minimize fa-2x mb-2"></i>
                                            <h6>Minimal</h6>
                                        </div>
                                    </div>
                                    
                                    <form id="invoiceForm">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Invoice/Receipt Type</label>
                                                    <select class="form-control" id="documentType">
                                                        <option value="invoice">Invoice</option>
                                                        <option value="receipt">Receipt</option>
                                                        <option value="quotation">Quotation</option>
                                                        <option value="credit_note">Credit Note</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Client/Member</label>
                                                    <select class="form-control" id="clientSelect">
                                                        <option value="">Select Client</option>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Invoice Date</label>
                                                    <input type="date" class="form-control" id="invoiceDate">
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label>Due Date</label>
                                                    <input type="date" class="form-control" id="dueDate">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label>Description</label>
                                            <textarea class="form-control" id="invoiceDescription" rows="3"></textarea>
                                        </div>
                                        
                                        <h6>Line Items</h6>
                                        <div id="lineItems">
                                            <div class="line-item">
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <input type="text" class="form-control" placeholder="Description">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <input type="number" class="form-control" placeholder="Qty">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <input type="number" class="form-control" placeholder="Rate">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <input type="number" class="form-control" placeholder="Tax %">
                                                    </div>
                                                    <div class="col-md-2">
                                                        <input type="number" class="form-control" placeholder="Amount" readonly>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="addLineItem()">
                                            <i class="fas fa-plus"></i> Add Line Item
                                        </button>
                                        
                                        <div class="auto-calculation">
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <strong>Subtotal: <span id="subtotal">₹0.00</span></strong>
                                                </div>
                                                <div class="col-md-4">
                                                    <strong>Tax: <span id="totalTax">₹0.00</span></strong>
                                                </div>
                                                <div class="col-md-4">
                                                    <strong>Total: <span id="grandTotal">₹0.00</span></strong>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label>Payment Terms</label>
                                            <select class="form-control" id="paymentTerms">
                                                <option value="net_30">Net 30</option>
                                                <option value="net_15">Net 15</option>
                                                <option value="due_on_receipt">Due on Receipt</option>
                                                <option value="advance">Advance Payment</option>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label>Notes</label>
                                            <textarea class="form-control" id="invoiceNotes" rows="2"></textarea>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" class="custom-control-input" id="includeQR">
                                                        <label class="custom-control-label" for="includeQR">Include QR Code</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <div class="custom-control custom-checkbox">
                                                        <input type="checkbox" class="custom-control-input" id="digitalSignature">
                                                        <label class="custom-control-label" for="digitalSignature">Digital Signature</label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="text-center">
                                            <button type="button" class="btn btn-primary" onclick="generateInvoice()">
                                                <i class="fas fa-magic"></i> Generate Invoice
                                            </button>
                                            <button type="button" class="btn btn-success" onclick="saveAsDraft()">
                                                <i class="fas fa-save"></i> Save as Draft
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-eye"></i> Live Preview
                                </h3>
                            </div>
                            <div class="card-body">
                                <div class="invoice-preview" id="invoicePreview">
                                    <div class="text-center text-muted">
                                        <i class="fas fa-file-invoice fa-3x mb-3"></i>
                                        <p>Invoice preview will appear here</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Recent Invoices/Receipts -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history"></i> Recent Invoices & Receipts
                        </h3>
                        <div class="card-tools">
                            <div class="batch-actions">
                                <div class="btn-group">
                                    <button class="btn btn-sm btn-outline-primary" onclick="bulkDownload()">
                                        <i class="fas fa-download"></i> Bulk Download
                                    </button>
                                    <button class="btn btn-sm btn-outline-success" onclick="bulkEmail()">
                                        <i class="fas fa-envelope"></i> Bulk Email
                                    </button>
                                    <button class="btn btn-sm btn-outline-warning" onclick="bulkMarkPaid()">
                                        <i class="fas fa-check"></i> Mark as Paid
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped" id="receiptsTable">
                                <thead>
                                    <tr>
                                        <th><input type="checkbox" id="selectAll"></th>
                                        <th>Invoice #</th>
                                        <th>Client</th>
                                        <th>Date</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody id="receiptsTableBody">
                                    <!-- Receipts will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Analytics Dashboard -->
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-line"></i> Revenue Analytics
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="revenueChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header">
                                <h3 class="card-title">
                                    <i class="fas fa-chart-pie"></i> Payment Status Distribution
                                </h3>
                            </div>
                            <div class="card-body">
                                <canvas id="paymentChart" width="400" height="300"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

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

<!-- Include footer -->
<?php include 'templates/footer.php'; ?>

<!-- Scripts -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/qrcode@1.5.3/build/qrcode.min.js"></script>

<script>
// Advanced Receipts & Invoices System
let currentTemplate = 'standard';
let lineItemCount = 1;

$(document).ready(function() {
    loadStats();
    loadRecentReceipts();
    loadClients();
    loadRevenueChart();
    loadPaymentChart();
    setupEventListeners();
    
    // Set default dates
    $('#invoiceDate').val(new Date().toISOString().split('T')[0]);
    const dueDate = new Date();
    dueDate.setDate(dueDate.getDate() + 30);
    $('#dueDate').val(dueDate.toISOString().split('T')[0]);
});

function setupEventListeners() {
    // Template selection
    $('.template-card').click(function() {
        $('.template-card').removeClass('active');
        $(this).addClass('active');
        currentTemplate = $(this).data('template');
        updatePreview();
    });
    
    // Form change events
    $('#invoiceForm input, #invoiceForm select, #invoiceForm textarea').change(function() {
        updatePreview();
        calculateTotals();
    });
    
    // Line item calculations
    $(document).on('input', '.line-item input', function() {
        calculateLineItem($(this).closest('.line-item'));
        calculateTotals();
    });
    
    // Select all checkbox
    $('#selectAll').change(function() {
        $('.receipt-checkbox').prop('checked', this.checked);
    });
}

function loadStats() {
    $.ajax({
        url: 'api/receipts/stats.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                $('#totalReceipts').text(response.stats.total_receipts);
                $('#totalInvoices').text(response.stats.total_invoices);
                $('#pendingAmount').text('₹' + response.stats.pending_amount.toLocaleString());
                $('#monthlyRevenue').text('₹' + response.stats.monthly_revenue.toLocaleString());
            }
        }
    });
}

function loadRecentReceipts() {
    $.ajax({
        url: 'api/receipts/recent.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const tbody = $('#receiptsTableBody');
                tbody.empty();
                
                response.receipts.forEach(function(receipt) {
                    tbody.append(createReceiptRow(receipt));
                });
            }
        }
    });
}

function createReceiptRow(receipt) {
    const statusClass = receipt.status === 'paid' ? 'paid' : (receipt.status === 'overdue' ? 'overdue' : 'pending');
    
    return `
        <tr>
            <td><input type="checkbox" class="receipt-checkbox" value="${receipt.id}"></td>
            <td>${receipt.invoice_number}</td>
            <td>${receipt.client_name}</td>
            <td>${formatDate(receipt.invoice_date)}</td>
            <td>₹${receipt.amount.toLocaleString()}</td>
            <td><span class="payment-status ${statusClass}">${receipt.status}</span></td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-primary" onclick="viewReceipt(${receipt.id})">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button class="btn btn-outline-success" onclick="downloadReceipt(${receipt.id})">
                        <i class="fas fa-download"></i>
                    </button>
                    <button class="btn btn-outline-info" onclick="emailReceipt(${receipt.id})">
                        <i class="fas fa-envelope"></i>
                    </button>
                    <button class="btn btn-outline-warning" onclick="duplicateReceipt(${receipt.id})">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </td>
        </tr>
    `;
}

function loadClients() {
    $.ajax({
        url: 'api/receipts/clients.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const select = $('#clientSelect');
                select.empty();
                select.append('<option value="">Select Client</option>');
                
                response.clients.forEach(function(client) {
                    select.append(`<option value="${client.id}">${client.name} (${client.kso_id})</option>`);
                });
            }
        }
    });
}

function addLineItem() {
    lineItemCount++;
    const lineItem = `
        <div class="line-item">
            <div class="row">
                <div class="col-md-4">
                    <input type="text" class="form-control item-description" placeholder="Description">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-quantity" placeholder="Qty" min="1" value="1">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-rate" placeholder="Rate" min="0" step="0.01">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-tax" placeholder="Tax %" min="0" max="100" step="0.01">
                </div>
                <div class="col-md-1">
                    <input type="number" class="form-control item-amount" placeholder="Amount" readonly>
                </div>
                <div class="col-md-1">
                    <button type="button" class="btn btn-danger btn-sm" onclick="removeLineItem(this)">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
    
    $('#lineItems').append(lineItem);
}

function removeLineItem(button) {
    $(button).closest('.line-item').remove();
    calculateTotals();
}

function calculateLineItem(lineItem) {
    const quantity = parseFloat(lineItem.find('.item-quantity').val()) || 0;
    const rate = parseFloat(lineItem.find('.item-rate').val()) || 0;
    const taxPercent = parseFloat(lineItem.find('.item-tax').val()) || 0;
    
    const subtotal = quantity * rate;
    const tax = subtotal * (taxPercent / 100);
    const total = subtotal + tax;
    
    lineItem.find('.item-amount').val(total.toFixed(2));
}

function calculateTotals() {
    let subtotal = 0;
    let totalTax = 0;
    
    $('.line-item').each(function() {
        const quantity = parseFloat($(this).find('.item-quantity').val()) || 0;
        const rate = parseFloat($(this).find('.item-rate').val()) || 0;
        const taxPercent = parseFloat($(this).find('.item-tax').val()) || 0;
        
        const lineSubtotal = quantity * rate;
        const lineTax = lineSubtotal * (taxPercent / 100);
        
        subtotal += lineSubtotal;
        totalTax += lineTax;
    });
    
    const grandTotal = subtotal + totalTax;
    
    $('#subtotal').text('₹' + subtotal.toFixed(2));
    $('#totalTax').text('₹' + totalTax.toFixed(2));
    $('#grandTotal').text('₹' + grandTotal.toFixed(2));
}

function updatePreview() {
    const clientId = $('#clientSelect').val();
    const invoiceDate = $('#invoiceDate').val();
    const dueDate = $('#dueDate').val();
    const description = $('#invoiceDescription').val();
    
    if (!clientId || !invoiceDate) {
        $('#invoicePreview').html(`
            <div class="text-center text-muted">
                <i class="fas fa-file-invoice fa-3x mb-3"></i>
                <p>Please select client and date to see preview</p>
            </div>
        `);
        return;
    }
    
    const preview = generatePreviewHTML();
    $('#invoicePreview').html(preview);
}

function generatePreviewHTML() {
    const clientName = $('#clientSelect option:selected').text();
    const invoiceDate = $('#invoiceDate').val();
    const dueDate = $('#dueDate').val();
    const description = $('#invoiceDescription').val();
    
    return `
        <div class="invoice-header">
            <div class="row">
                <div class="col-md-6">
                    <h4>KSO Chandigarh</h4>
                    <p class="text-muted">Invoice</p>
                </div>
                <div class="col-md-6 text-right">
                    <p>Invoice #: INV-${Date.now()}</p>
                    <p>Date: ${formatDate(invoiceDate)}</p>
                    <p>Due: ${formatDate(dueDate)}</p>
                </div>
            </div>
        </div>
        <hr>
        <div class="billing-info">
            <div class="row">
                <div class="col-md-6">
                    <h6>Bill To:</h6>
                    <p>${clientName}</p>
                </div>
                <div class="col-md-6">
                    <h6>Description:</h6>
                    <p>${description || 'No description'}</p>
                </div>
            </div>
        </div>
        <hr>
        <div class="line-items">
            <table class="table table-sm">
                <thead>
                    <tr>
                        <th>Description</th>
                        <th>Qty</th>
                        <th>Rate</th>
                        <th>Tax</th>
                        <th>Amount</th>
                    </tr>
                </thead>
                <tbody>
                    ${generateLineItemsHTML()}
                </tbody>
            </table>
        </div>
        <div class="totals text-right">
            <p>Subtotal: <span id="previewSubtotal">₹0.00</span></p>
            <p>Tax: <span id="previewTax">₹0.00</span></p>
            <h5>Total: <span id="previewTotal">₹0.00</span></h5>
        </div>
    `;
}

function generateLineItemsHTML() {
    let html = '';
    $('.line-item').each(function() {
        const description = $(this).find('.item-description').val();
        const quantity = $(this).find('.item-quantity').val();
        const rate = $(this).find('.item-rate').val();
        const tax = $(this).find('.item-tax').val();
        const amount = $(this).find('.item-amount').val();
        
        if (description) {
            html += `
                <tr>
                    <td>${description}</td>
                    <td>${quantity}</td>
                    <td>₹${rate}</td>
                    <td>${tax}%</td>
                    <td>₹${amount}</td>
                </tr>
            `;
        }
    });
    
    return html || '<tr><td colspan="5" class="text-center text-muted">No items added</td></tr>';
}

function generateInvoice() {
    const formData = collectFormData();
    
    $.ajax({
        url: 'api/receipts/generate.php',
        method: 'POST',
        data: formData,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Invoice generated successfully!');
                }
                
                // Open invoice in new window
                window.open('api/receipts/view.php?id=' + response.invoice_id, '_blank');
                
                // Reset form
                resetForm();
                loadRecentReceipts();
                loadStats();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function saveAsDraft() {
    const formData = collectFormData();
    formData.status = 'draft';
    
    $.ajax({
        url: 'api/receipts/save-draft.php',
        method: 'POST',
        data: formData,
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Draft saved successfully!');
                }
                resetForm();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function collectFormData() {
    const lineItems = [];
    $('.line-item').each(function() {
        const description = $(this).find('.item-description').val();
        if (description) {
            lineItems.push({
                description: description,
                quantity: $(this).find('.item-quantity').val(),
                rate: $(this).find('.item-rate').val(),
                tax: $(this).find('.item-tax').val(),
                amount: $(this).find('.item-amount').val()
            });
        }
    });
    
    return {
        template: currentTemplate,
        document_type: $('#documentType').val(),
        client_id: $('#clientSelect').val(),
        invoice_date: $('#invoiceDate').val(),
        due_date: $('#dueDate').val(),
        description: $('#invoiceDescription').val(),
        line_items: JSON.stringify(lineItems),
        payment_terms: $('#paymentTerms').val(),
        notes: $('#invoiceNotes').val(),
        include_qr: $('#includeQR').is(':checked'),
        digital_signature: $('#digitalSignature').is(':checked')
    };
}

function resetForm() {
    $('#invoiceForm')[0].reset();
    $('#lineItems').html(`
        <div class="line-item">
            <div class="row">
                <div class="col-md-4">
                    <input type="text" class="form-control item-description" placeholder="Description">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-quantity" placeholder="Qty" min="1" value="1">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-rate" placeholder="Rate" min="0" step="0.01">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-tax" placeholder="Tax %" min="0" max="100" step="0.01">
                </div>
                <div class="col-md-2">
                    <input type="number" class="form-control item-amount" placeholder="Amount" readonly>
                </div>
            </div>
        </div>
    `);
    
    calculateTotals();
    updatePreview();
}

function loadRevenueChart() {
    $.ajax({
        url: 'api/receipts/revenue-chart.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('revenueChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            label: 'Revenue',
                            data: response.data,
                            borderColor: 'rgb(75, 192, 192)',
                            backgroundColor: 'rgba(75, 192, 192, 0.2)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
    });
}

function loadPaymentChart() {
    $.ajax({
        url: 'api/receipts/payment-chart.php',
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const ctx = document.getElementById('paymentChart').getContext('2d');
                new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: response.labels,
                        datasets: [{
                            data: response.data,
                            backgroundColor: [
                                '#28a745',
                                '#ffc107',
                                '#dc3545'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false
                    }
                });
            }
        }
    });
}

function viewReceipt(id) {
    window.open('api/receipts/view.php?id=' + id, '_blank');
}

function downloadReceipt(id) {
    window.open('api/receipts/download.php?id=' + id, '_blank');
}

function emailReceipt(id) {
    if (typeof Swal !== 'undefined') {
        Swal.fire({
            title: 'Email Receipt',
            text: 'Send receipt via email?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, send!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: 'api/receipts/email.php',
                    method: 'POST',
                    data: { id: id },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Sent!', 'Receipt has been emailed.', 'success');
                        } else {
                            Swal.fire('Error!', response.message, 'error');
                        }
                    }
                });
            }
        });
    }
}

function duplicateReceipt(id) {
    $.ajax({
        url: 'api/receipts/duplicate.php',
        method: 'POST',
        data: { id: id },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Receipt duplicated successfully!');
                }
                loadRecentReceipts();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function bulkDownload() {
    const selected = $('.receipt-checkbox:checked').map(function() {
        return this.value;
    }).get();
    
    if (selected.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select receipts to download');
        }
        return;
    }
    
    window.open('api/receipts/bulk-download.php?ids=' + selected.join(','), '_blank');
}

function bulkEmail() {
    const selected = $('.receipt-checkbox:checked').map(function() {
        return this.value;
    }).get();
    
    if (selected.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select receipts to email');
        }
        return;
    }
    
    $.ajax({
        url: 'api/receipts/bulk-email.php',
        method: 'POST',
        data: { ids: selected },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Bulk email sent successfully!');
                }
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function bulkMarkPaid() {
    const selected = $('.receipt-checkbox:checked').map(function() {
        return this.value;
    }).get();
    
    if (selected.length === 0) {
        if (window.ksoToast) {
            window.ksoToast.error('Please select receipts to mark as paid');
        }
        return;
    }
    
    $.ajax({
        url: 'api/receipts/bulk-mark-paid.php',
        method: 'POST',
        data: { ids: selected },
        success: function(response) {
            if (response.success) {
                if (window.ksoToast) {
                    window.ksoToast.success('Receipts marked as paid successfully!');
                }
                loadRecentReceipts();
                loadStats();
            } else {
                if (window.ksoToast) {
                    window.ksoToast.error('Error: ' + response.message);
                }
            }
        }
    });
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('en-US', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

function createInvoice() {
    $('#documentType').val('invoice');
    updatePreview();
}

function createReceipt() {
    $('#documentType').val('receipt');
    updatePreview();
}
</script>

</body>
</html>
