<?php
require_once 'config.php';
requireLogin();

$company_id = $_SESSION['company_id'] ?? null;

// Get items with HSN codes and tax rates
$items_sql = "SELECT 
    i.*,
    ic.category_name,
    h.hsn_code,
    h.gst_rate as hsn_gst_rate,
    COALESCE(h.gst_rate, i.gst_rate) as effective_gst_rate
    FROM items i 
    LEFT JOIN item_categories ic ON i.item_category_id = ic.id 
    LEFT JOIN hsn_codes h ON i.hsn_code_id = h.id 
    WHERE i.company_id = ?";
$stmt = $conn->prepare($items_sql);
$stmt->bind_param('i', $company_id);
$stmt->execute();
$items = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get invoice type from URL (sales/purchase)
$invoice_type = isset($_GET['type']) ? $_GET['type'] : 'sales';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($page - 1) * $per_page;

// Get customers/suppliers based on invoice type
if ($invoice_type === 'sales') {
    $party_sql = "SELECT id, customer_name as name, gstin FROM customers WHERE company_id = ?";
} else {
    $party_sql = "SELECT id, supplier_name as name, gstin FROM suppliers WHERE company_id = ?";
}
$stmt = $conn->prepare($party_sql);
$stmt->bind_param('i', $company_id);
$stmt->execute();
$parties = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get invoices list
$invoices_sql = "SELECT i.*, 
                 CASE 
                    WHEN i.invoice_type = 'sales' THEN c.customer_name 
                    ELSE s.supplier_name 
                 END as party_name,
                 CASE 
                    WHEN i.invoice_type = 'sales' THEN c.gstin 
                    ELSE s.gstin 
                 END as party_gstin
                 FROM invoices i 
                 LEFT JOIN customers c ON i.customer_id = c.id 
                 LEFT JOIN suppliers s ON i.supplier_id = s.id 
                 WHERE i.company_id = ? AND i.invoice_type = ?
                 ORDER BY i.invoice_date DESC, i.id DESC
                 LIMIT ? OFFSET ?";
$stmt = $conn->prepare($invoices_sql);
$stmt->bind_param('isii', $company_id, $invoice_type, $per_page, $offset);
$stmt->execute();
$invoices = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get total count for pagination
$count_sql = "SELECT COUNT(*) as total FROM invoices WHERE company_id = ? AND invoice_type = ?";
$stmt = $conn->prepare($count_sql);
$stmt->bind_param('is', $company_id, $invoice_type);
$stmt->execute();
$total_invoices = $stmt->get_result()->fetch_assoc()['total'];
$total_pages = ceil($total_invoices / $per_page);

require_once 'header.php';
require_once 'sub_header.php';
?>

<div class="container-fluid px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><?php echo ucfirst($invoice_type); ?> Invoices</h2>
        <div class="d-flex gap-2">
            <div class="btn-group">
                <a href="?type=sales" class="btn btn-outline-primary <?php echo $invoice_type === 'sales' ? 'active' : ''; ?>">
                    Sales Invoices
                </a>
                <a href="?type=purchase" class="btn btn-outline-primary <?php echo $invoice_type === 'purchase' ? 'active' : ''; ?>">
                    Purchase Invoices
                </a>
            </div>
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#invoiceModal">
                <i class="fas fa-plus"></i> New Invoice
            </button>
        </div>
    </div>

    <!-- Invoices List -->
    <div class="card mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>Invoice #</th>
                            <th>Date</th>
                            <th><?php echo $invoice_type === 'sales' ? 'Customer' : 'Supplier'; ?></th>
                            <th>GSTIN</th>
                            <th>Amount</th>
                            <th>Tax</th>
                            <th>Total</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($invoices as $invoice): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                            <td><?php echo date('d-m-Y', strtotime($invoice['invoice_date'])); ?></td>
                            <td><?php echo htmlspecialchars($invoice['party_name']); ?></td>
                            <td><?php echo htmlspecialchars($invoice['party_gstin']); ?></td>
                            <td class="text-end">₹<?php echo number_format($invoice['total_amount'], 2); ?></td>
                            <td class="text-end">₹<?php echo number_format($invoice['tax_amount'], 2); ?></td>
                            <td class="text-end">₹<?php echo number_format($invoice['grand_total'], 2); ?></td>
                            <td>
                                <span class="badge bg-<?php 
                                    echo match($invoice['status']) {
                                        'paid' => 'success',
                                        'overdue' => 'danger',
                                        'sent' => 'info',
                                        default => 'secondary'
                                    };
                                ?>">
                                    <?php echo ucfirst($invoice['status']); ?>
                                </span>
                            </td>
                            <td>
                                <div class="btn-group btn-group-sm">
                                    <a href="view_invoice.php?id=<?php echo $invoice['id']; ?>" 
                                       class="btn btn-info" title="View">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="edit_invoice.php?id=<?php echo $invoice['id']; ?>" 
                                       class="btn btn-warning" title="Edit">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button type="button" class="btn btn-danger" title="Delete"
                                            onclick="deleteInvoice(<?php echo $invoice['id']; ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <button type="button" class="btn btn-success" title="Print"
                                            onclick="printInvoice(<?php echo $invoice['id']; ?>)">
                                        <i class="fas fa-print"></i>
                                    </button>
                                    <a href="update_invoice_status.php?id=<?php echo $invoice['id']; ?>&type=<?php echo $invoice_type; ?>" 
                                       class="btn btn-secondary" title="Change Status">
                                        <i class="fas fa-exchange-alt"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
            <nav aria-label="Page navigation" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?type=<?php echo $invoice_type; ?>&page=<?php echo $page-1; ?>">Previous</a>
                    </li>
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                        <li class="page-item <?php echo $page == $i ? 'active' : ''; ?>">
                            <a class="page-link" href="?type=<?php echo $invoice_type; ?>&page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                        <a class="page-link" href="?type=<?php echo $invoice_type; ?>&page=<?php echo $page+1; ?>">Next</a>
                    </li>
                </ul>
            </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Invoice Modal -->
<div class="modal fade" id="invoiceModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">New <?php echo ucfirst($invoice_type); ?> Invoice</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="invoiceForm" method="post" action="save_invoice.php">
                    <input type="hidden" name="invoice_type" value="<?php echo $invoice_type; ?>">
                    
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label class="form-label">Invoice Date</label>
                            <input type="date" class="form-control" name="invoice_date" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">
                                <?php echo $invoice_type === 'sales' ? 'Customer' : 'Supplier'; ?>
                            </label>
                            <select class="form-select" name="party_id" id="partySelect" required>
                                <option value="">Select</option>
                                <?php foreach ($parties as $party): ?>
                                    <option value="<?php echo $party['id']; ?>" 
                                            data-gstin="<?php echo $party['gstin']; ?>">
                                        <?php echo htmlspecialchars($party['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Due Date</label>
                            <input type="date" class="form-control" name="due_date">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Supply Place</label>
                            <input type="text" class="form-control" name="supply_place">
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label">Billing Address (Default)</label>
                            <textarea class="form-control" name="billing_address" id="billingAddress" rows="2" readonly></textarea>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Shipping Address</label>
                            <textarea class="form-control" name="shipping_address" id="shippingAddress" rows="2"></textarea>
                            <div class="form-check mt-2">
                                <input class="form-check-input" type="checkbox" id="sameAsBilling">
                                <label class="form-check-label" for="sameAsBilling">
                                    Same as billing address
                                </label>
                            </div>
                        </div>
                    </div>

                    <!-- Items Table -->
                    <div class="table-responsive mb-3">
                        <table class="table table-bordered" id="itemsTable">
                            <thead>
                                <tr>
                                    <th>Item</th>
                                    <th>HSN/SAC</th>
                                    <th>Quantity</th>
                                    <th>Rate</th>
                                    <th>Discount (%)</th>
                                    <th>Tax Rate (%)</th>
                                    <th>Amount</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        <select class="form-select item-select" name="items[0][item_id]" required>
                                            <option value="">Select Item</option>
                                            <?php foreach ($items as $item): ?>
                                                <option value="<?php echo $item['id']; ?>"
                                                        data-rate="<?php echo $invoice_type === 'sales' ? $item['sales_price'] : $item['purchase_price']; ?>"
                                                        data-gst="<?php echo $item['effective_gst_rate']; ?>"
                                                        data-hsn="<?php echo $item['hsn_code']; ?>">
                                                    <?php echo htmlspecialchars($item['item_name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </td>
                                    <td><input type="text" class="form-control hsn-code" readonly></td>
                                    <td><input type="number" class="form-control quantity" name="items[0][quantity]" value="1" min="1" required></td>
                                    <td><input type="number" class="form-control rate" name="items[0][rate]" step="0.01" required></td>
                                    <td><input type="number" class="form-control discount" name="items[0][discount]" value="0" min="0" max="100" step="0.01"></td>
                                    <td><input type="number" class="form-control tax-rate" name="items[0][tax_rate]" readonly></td>
                                    <td><input type="number" class="form-control amount" name="items[0][amount]" readonly></td>
                                    <td>
                                        <button type="button" class="btn btn-danger btn-sm remove-item">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>

                    <button type="button" class="btn btn-success mb-3" id="addItem">
                        <i class="fas fa-plus"></i> Add Item
                    </button>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Notes</label>
                                <textarea class="form-control" name="notes" rows="3"></textarea>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Payment Terms</label>
                                <input type="text" class="form-control" name="payment_terms" value="Due on receipt">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-bordered">
                                <tr>
                                    <td>Sub Total:</td>
                                    <td class="text-end">₹<span id="subtotal">0.00</span></td>
                                </tr>
                                <tr>
                                    <td>Total Discount:</td>
                                    <td class="text-end">₹<span id="totalDiscount">0.00</span></td>
                                </tr>
                                <tr>
                                    <td>Total Tax:</td>
                                    <td class="text-end">₹<span id="totalTax">0.00</span></td>
                                </tr>
                                <tr class="table-active">
                                    <td><strong>Grand Total:</strong></td>
                                    <td class="text-end"><strong>₹<span id="grandTotal">0.00</span></strong></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="submit" form="invoiceForm" class="btn btn-primary">Save Invoice</button>
            </div>
        </div>
    </div>
</div>

<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include Bootstrap JS and Popper.js for modal functionality -->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize items table functionality
    let rowCount = 1;

    // Add new item row
    $('#addItem').click(function() {
        console.log('Add Item Clicked');
        const newRow = $('#itemsTable tbody tr:first').clone();
        newRow.find('input').val('');
        newRow.find('select').val('');
        newRow.find('[name]').each(function() {
            const name = $(this).attr('name');
            $(this).attr('name', name.replace('[0]', `[${rowCount}]`));
        });
        $('#itemsTable tbody').append(newRow);
        rowCount++;
        updateCalculations();
    });

    // Remove item row
    $(document).on('click', '.remove-item', function() {
        console.log('Remove Item Clicked');
        if ($('#itemsTable tbody tr').length > 1) {
            $(this).closest('tr').remove();
            updateCalculations();
        }
    });

    // Update HSN code, rate, and tax rate when item is selected
    $(document).on('change', '.item-select', function() {
        console.log('Item Selected');
        const row = $(this).closest('tr');
        const selected = $(this).find('option:selected');
        row.find('.hsn-code').val(selected.data('hsn'));
        row.find('.rate').val(selected.data('rate'));
        row.find('.tax-rate').val(selected.data('gst'));
        updateRowCalculation(row);
    });

    // Handle quantity/rate/discount changes
    $(document).on('input', '.quantity, .rate, .discount', function() {
        console.log('Input Changed');
        updateRowCalculation($(this).closest('tr'));
    });

    function updateRowCalculation(row) {
        const quantity = parseFloat(row.find('.quantity').val()) || 0;
        const rate = parseFloat(row.find('.rate').val()) || 0;
        const discount = parseFloat(row.find('.discount').val()) || 0;
        const taxRate = parseFloat(row.find('.tax-rate').val()) || 0;

        const amountBeforeDiscount = quantity * rate;
        const discountAmount = (amountBeforeDiscount * discount) / 100;
        const taxableAmount = amountBeforeDiscount - discountAmount;
        const taxAmount = (taxableAmount * taxRate) / 100;
        const finalAmount = taxableAmount + taxAmount;

        row.find('.amount').val(finalAmount.toFixed(2));
        updateCalculations();
    }

    function updateCalculations() {
        let subtotal = 0;
        let totalDiscount = 0;
        let totalTax = 0;

        $('#itemsTable tbody tr').each(function() {
            const quantity = parseFloat($(this).find('.quantity').val()) || 0;
            const rate = parseFloat($(this).find('.rate').val()) || 0;
            const discount = parseFloat($(this).find('.discount').val()) || 0;
            const taxRate = parseFloat($(this).find('.tax-rate').val()) || 0;

            const amountBeforeDiscount = quantity * rate;
            const discountAmount = (amountBeforeDiscount * discount) / 100;
            const taxableAmount = amountBeforeDiscount - discountAmount;
            const taxAmount = (taxableAmount * taxRate) / 100;
            const finalAmount = taxableAmount + taxAmount;

            subtotal += amountBeforeDiscount;
            totalDiscount += discountAmount;
            totalTax += taxAmount;
        });

        const grandTotal = subtotal - totalDiscount + totalTax;

        $('#subtotal').text(subtotal.toFixed(2));
        $('#totalDiscount').text(totalDiscount.toFixed(2));
        $('#totalTax').text(totalTax.toFixed(2));
        $('#grandTotal').text(grandTotal.toFixed(2));
    }
});

function deleteInvoice(id) {
    if (confirm('Are you sure you want to delete this invoice?')) {
        window.location.href = `delete_invoice.php?id=${id}`;
    }
}

// Fetch party address when selected - Updated to handle both customers and suppliers
$('#partySelect').change(function() {
    const partyId = $(this).val();
    const billingAddress = $('#billingAddress');
    const shippingAddress = $('#shippingAddress');
    const invoiceType = $('input[name="invoice_type"]').val();
    
    if (!partyId) {
        billingAddress.val('');
        shippingAddress.val('');
        return;
    }

    const endpoint = invoiceType === 'sales' ? 'get_customer.php' : 'get_supplier.php';
    
    $.ajax({
        url: endpoint,
        method: 'GET',
        data: { id: partyId },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                let party;
                if (invoiceType === 'sales') {
                    party = response.customer;
                } else {
                    party = response.supplier;
                }
                
                if (party) {
                    const addressParts = [
                        party.address,
                        party.city,
                        party.state,
                        party.pincode ? `- ${party.pincode}` : ''
                    ].filter(Boolean);
                    
                    const fullAddress = addressParts.join(', ');
                    billingAddress.val(fullAddress);
                    
                    // Update shipping address if "same as billing" is checked
                    if ($('#sameAsBilling').is(':checked')) {
                        shippingAddress.val(fullAddress);
                    }
                } else {
                    billingAddress.val('Party data not found');
                    console.error('Party lookup failed: No party data in response');
                }
            } else {
                billingAddress.val('Error: ' + (response.message || 'Failed to load party data'));
                console.error('Party lookup failed:', response.message || 'Unknown error');
            }
        },
        error: function(xhr, status, error) {
            billingAddress.val('Error loading party data');
            console.error('AJAX Error:', status, error);
        }
    });
});

// Handle "Same as billing" checkbox
$('#sameAsBilling').change(function() {
    if ($(this).is(':checked')) {
        $('#shippingAddress').val($('#billingAddress').val()).prop('readonly', true);
    } else {
        $('#shippingAddress').prop('readonly', false);
    }
});

function printInvoice(id) {
    window.open(`print_invoice.php?id=${id}`, '_blank');
}
</script>

<?php require_once 'footer.php'; ?>
<?php require_once 'calculator.php'; ?> in above page in Supply Place i need all indian state selection dropdownlist required