<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Fetch banks for dropdown
$sql_banks = "SELECT bank_code, bank_name FROM banks WHERE active = 1 ORDER BY bank_name";
$result_banks = $conn->query($sql_banks);
$banks = $result_banks->fetch_all(MYSQLI_ASSOC);

// Fetch corporates
$sql_corps = "SELECT corp_id, corporate FROM corporate WHERE cancelled = 0 ORDER BY corporate";
$result_corps = $conn->query($sql_corps);
$corporates = $result_corps->fetch_all(MYSQLI_ASSOC);

// Generate receipt number
function generateReceiptNumber($conn) {
    $sql = "SELECT MAX(CAST(SUBSTRING(receipt_no, 4) AS UNSIGNED)) as max_num 
            FROM premium_receipt WHERE receipt_no LIKE 'RCP%'";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    $next_num = ($row['max_num'] ?? 0) + 1;
    return 'RCP' . str_pad($next_num, 7, '0', STR_PAD_LEFT);
}

$receipt_no = generateReceiptNumber($conn);

$conn->close();
?>

<?php include 'layouts/main.php'; ?>
<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Add Receipt')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.19/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        .debit-row.allocated {
            background-color: #e8f5e9;
        }
        .allocation-error {
            border-color: #dc3545;
        }
        #remainingAmount {
            font-size: 1.2em;
            font-weight: bold;
        }
        .payment-info {
            display: none;
        }
        .table th {
            background-color: #f8f9fa;
        }
        #debitsSection {
            display: none;
        }
        #paymentDiffSection {
            display: none;
        }
        .payment-diff-badge {
            font-size: 1.2em;
            padding: 10px 15px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Finance', 'title' => 'Add Receipt')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <form id="receiptForm">
                                <!-- Corporate Selection -->
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title mb-0">Select Corporate</h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-6">
                                                <label class="form-label">Corporate</label>
                                                <select class="form-select" id="corporateSelect" name="corp_id" required>
                                                    <option value="">Select Corporate</option>
                                                    <?php foreach ($corporates as $corp): ?>
                                                        <option value="<?php echo $corp['corp_id']; ?>">
                                                            <?php echo htmlspecialchars($corp['corporate']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Receipt Details -->
                                <div class="card">
                                    <div class="card-header">
                                        <h4 class="card-title mb-0">Receipt Details</h4>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <label class="form-label">Receipt Number</label>
                                                <input type="text" class="form-control" name="receipt_no" 
                                                       value="<?php echo $receipt_no; ?>" readonly>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <label class="form-label">Receipt Date</label>
                                                <input type="date" class="form-control" name="receipt_date" 
                                                       value="<?php echo date('Y-m-d'); ?>" required>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <label class="form-label">Total Amount</label>
                                                <input type="number" class="form-control" name="receipt_amount" 
                                                       id="receiptAmount" step="0.01" min="0" required>
                                            </div>
                                            
                                            <div class="col-md-3">
                                                <label class="form-label">Payment Mode</label>
                                                <select class="form-select" name="payment_mode" id="paymentMode" required>
                                                    <option value="">Select Mode</option>
                                                    <option value="1">Cash</option>
                                                    <option value="2">Cheque</option>
                                                    <option value="3">Bank Transfer</option>
                                                    <option value="4">Mobile Money</option>
                                                </select>
                                            </div>
                                        </div>

                                        <!-- Payment Type and Difference Section -->
                                        <div class="row mt-3">
                                            <div class="col-md-4">
                                                <label class="form-label">Payment Type</label>
                                                <select class="form-select" id="paymentType" name="payment_type" required>
                                                    <option value="exact">Exact Payment</option>
                                                    <option value="over">Over Payment</option>
                                                    <option value="under">Under Payment</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-8">
                                                <div id="paymentDiffSection">
                                                    <div class="alert alert-info mb-0">
                                                        <div class="d-flex justify-content-between align-items-center">
                                                            <div>
                                                                <h5 class="alert-heading mb-1">Payment Difference</h5>
                                                                <p class="mb-0" id="paymentDiffMessage"></p>
                                                            </div>
                                                            <div>
                                                                <span class="badge payment-diff-badge" id="paymentDiffAmount">0.00</span>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Bank Details -->
                                        <div class="row mt-3 payment-info" id="bankDetails">
                                            <div class="col-md-6">
                                                <label class="form-label">Bank</label>
                                                <select class="form-select" name="bank_id" id="bankId">
                                                    <option value="">Select Bank</option>
                                                    <?php foreach($banks as $bank): ?>
                                                        <option value="<?php echo $bank['bank_code']; ?>">
                                                            <?php echo htmlspecialchars($bank['bank_name']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <label class="form-label">Reference Number</label>
                                                <input type="text" class="form-control" name="reference_no" 
                                                       id="referenceNo" placeholder="Cheque/Transfer Reference">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Debit Notes Section -->
                                <div class="card" id="debitsSection">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h4 class="card-title mb-0">Unallocated Debit Notes</h4>
                                            <div>
                                                <span class="me-2">Remaining Amount:</span>
                                                <span id="remainingAmount" class="badge bg-primary">0.00</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-bordered" id="debitsTable">
                                                <thead>
                                                    <tr>
                                                        <th>Debit No</th>
                                                        <th>Date</th>
                                                        <th>Period</th>
                                                        <th class="text-end">Amount</th>
                                                        <th>Status</th>
                                                        <th width="200">Allocate</th>
                                                        <th width="100">Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td colspan="7" class="text-center">
                                                            Select a corporate to view debits
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>

                                <!-- Form Buttons -->
                                <div class="row mt-3">
                                    <div class="col-12">
                                        <div class="d-flex justify-content-end gap-2">
                                            <button type="button" class="btn btn-light" onclick="window.history.back();">
                                                Cancel
                                            </button>
                                            <button type="submit" class="btn btn-primary" id="saveButton" disabled>
                                                Save Receipt
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
document.addEventListener('DOMContentLoaded', function() {
    // Initialize elements
    const receiptForm = document.getElementById('receiptForm');
    const corporateSelect = document.getElementById('corporateSelect');
    const paymentMode = document.getElementById('paymentMode');
    const bankDetails = document.getElementById('bankDetails');
    const bankId = document.getElementById('bankId');
    const referenceNo = document.getElementById('referenceNo');
    const receiptAmount = document.getElementById('receiptAmount');
    const paymentType = document.getElementById('paymentType');
    const debitsSection = document.getElementById('debitsSection');
    const debitsTable = document.getElementById('debitsTable');
    const remainingAmount = document.getElementById('remainingAmount');
    const saveButton = document.getElementById('saveButton');
    const paymentDiffSection = document.getElementById('paymentDiffSection');
    const paymentDiffMessage = document.getElementById('paymentDiffMessage');
    const paymentDiffAmount = document.getElementById('paymentDiffAmount');

    // Handle corporate selection
    corporateSelect.addEventListener('change', function() {
        const corpId = this.value;
        if (corpId) {
            loadDebits(corpId);
        } else {
            debitsSection.style.display = 'none';
        }
    });

    // Handle payment mode change
    paymentMode.addEventListener('change', function() {
        const isCash = this.value === '1';
        bankDetails.style.display = isCash ? 'none' : 'block';
        
        bankId.required = !isCash;
        referenceNo.required = !isCash;

        if (isCash) {
            bankId.value = '';
            referenceNo.value = '';
        }

        // Update reference placeholder based on mode
        switch(this.value) {
            case '2':
                referenceNo.placeholder = 'Enter Cheque Number';
                break;
            case '3':
                referenceNo.placeholder = 'Enter Bank Transfer Reference';
                break;
            case '4':
                referenceNo.placeholder = 'Enter Mobile Money Reference';
                break;
            default:
                referenceNo.placeholder = 'Reference Number';
        }
    });

    // Handle receipt amount change
    receiptAmount.addEventListener('input', updateTotalAllocation);
    
    // Handle payment type change
    paymentType.addEventListener('change', updateTotalAllocation);

    function loadDebits(corpId) {
        debitsSection.style.display = 'block';
        const tbody = debitsTable.querySelector('tbody');
        tbody.innerHTML = '<tr><td colspan="7" class="text-center">Loading...</td></tr>';

        const formData = new FormData();
        formData.append('corp_id', corpId);

        fetch('get_corporate_debits.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error);
            }
            displayDebits(data.debits);
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message
            });
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center text-danger">
                        Error loading debits: ${error.message}
                    </td>
                </tr>
            `;
        });
    }

    function displayDebits(debits) {
        const tbody = debitsTable.querySelector('tbody');
        
        if (!debits.length) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center">
                        No unallocated debits found for this corporate
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = debits.map(debit => `
            <tr data-debit-id="${debit.debit_no}" class="debit-row">
                <td>${debit.debit_no}</td>
                <td>${new Date(debit.debit_date).toLocaleDateString()}</td>
                <td>
                    ${new Date(debit.period_from).toLocaleDateString()} - 
                    ${new Date(debit.period_to).toLocaleDateString()}
                </td>
                <td class="text-end">${parseFloat(debit.amount).toLocaleString(undefined, {
                    minimumFractionDigits: 2,
                    maximumFractionDigits: 2
                })}</td>
                <td>
                    <span class="badge bg-warning">
                        ${debit.status}
                    </span>
                </td>
                <td>
                    <input type="number" 
                           class="form-control allocation-amount" 
                           name="allocations[${debit.debit_no}]"
                           step="0.01" 
                           min="0" 
                           max="${debit.amount}"
                           data-max="${debit.amount}">
                </td>
                <td class="text-center">
                    <button type="button" 
                            class="btn btn-sm btn-outline-primary allocate-full"
                            title="Allocate Full Amount">
                        <i class="ri-funds-line"></i>
                    </button>
                    <button type="button" 
                            class="btn btn-sm btn-outline-danger clear-allocation"
                            title="Clear Allocation">
                        <i class="ri-delete-bin-line"></i>
                    </button>
                </td>
            </tr>
        `).join('');

        initializeAllocationInputs();
    }

    function initializeAllocationInputs() {
        document.querySelectorAll('.allocation-amount').forEach(input => {
            input.addEventListener('input', function() {
                validateAllocation(this);
                updateTotalAllocation();
            });
        });

        document.querySelectorAll('.allocate-full').forEach(btn => {
            btn.addEventListener('click', function() {
                const input = this.closest('tr').querySelector('.allocation-amount');
                input.value = input.dataset.max;
                validateAllocation(input);
                updateTotalAllocation();
            });
        });

        document.querySelectorAll('.clear-allocation').forEach(btn => {
            btn.addEventListener('click', function() {
                const input = this.closest('tr').querySelector('.allocation-amount');
                input.value = '';
                validateAllocation(input);
                updateTotalAllocation();
            });
        });
    }

    function validateAllocation(input) {
        const amount = parseFloat(input.value) || 0;
        const maxAmount = parseFloat(input.dataset.max);
        const row = input.closest('tr');

        // Clear previous states
        input.classList.remove('allocation-error');
        row.classList.remove('allocated');

        // Validate amount
        if (amount > 0) {
            row.classList.add('allocated');
            if (amount > maxAmount) {
                input.classList.add('allocation-error');
                input.value = maxAmount;
                Swal.fire({
                    icon: 'warning',
                    title: 'Invalid Amount',
                    text: `Maximum allocation amount is ${maxAmount.toLocaleString()}`
                });
            }
        }
    }

    function updateTotalAllocation() {
        const totalReceipt = parseFloat(receiptAmount.value) || 0;
        let totalAllocated = 0;

        document.querySelectorAll('.allocation-amount').forEach(input => {
            totalAllocated += parseFloat(input.value) || 0;
        });

        const difference = totalReceipt - totalAllocated;
        const currentPaymentType = paymentType.value;

        // Update payment difference section
        paymentDiffSection.style.display = difference !== 0 ? 'block' : 'none';
        paymentDiffAmount.textContent = Math.abs(difference).toFixed(2);

        if (difference > 0) {
            paymentDiffMessage.textContent = 'Over Payment - Amount will be available as credit';
            paymentDiffAmount.className = 'badge payment-diff-badge bg-success';
            saveButton.disabled = currentPaymentType !== 'over';
        } else if (difference < 0) {
            paymentDiffMessage.textContent = 'Under Payment - Partial allocation will be recorded';
            paymentDiffAmount.className = 'badge payment-diff-badge bg-warning';
            saveButton.disabled = currentPaymentType !== 'under';
        } else {
            paymentDiffSection.style.display = 'none';
            saveButton.disabled = currentPaymentType !== 'exact';
        }

        // Update remaining amount display
        remainingAmount.textContent = difference.toFixed(2);
        remainingAmount.className = `badge ${
            difference === 0 ? 'bg-success' : 
            difference > 0 ? 'bg-primary' : 'bg-danger'
        }`;
    }

    function validateForm() {
        if (!receiptForm.checkValidity()) {
            receiptForm.reportValidity();
            return false;
        }

        const totalReceipt = parseFloat(receiptAmount.value);
        if (!totalReceipt || totalReceipt <= 0) {
            Swal.fire({
                icon: 'error',
                title: 'Invalid Amount',
                text: 'Please enter a valid receipt amount'
            });
            return false;
        }

        const mode = paymentMode.value;
        if (!mode) {
            Swal.fire({
                icon: 'error',
                title: 'Missing Information',
                text: 'Please select a payment mode'
            });
            return false;
        }

        if (mode !== '1') {
            if (!bankId.value) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Information',
                    text: 'Please select a bank'
                });
                return false;
            }
            if (!referenceNo.value) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Information',
                    text: 'Please enter a reference number'
                });
                return false;
            }
        }

        // Validate allocations
        let totalAllocated = 0;
        let hasAllocations = false;

        document.querySelectorAll('.allocation-amount').forEach(input => {
            const amount = parseFloat(input.value) || 0;
            if (amount > 0) {
                hasAllocations = true;
                totalAllocated += amount;
            }
        });

        if (!hasAllocations) {
            Swal.fire({
                icon: 'error',
                title: 'No Allocations',
                text: 'Please allocate the receipt amount to at least one debit note'
            });
            return false;
        }

        const difference = totalReceipt - totalAllocated;
        const currentPaymentType = paymentType.value;

        // Validate based on payment type
        switch(currentPaymentType) {
            case 'exact':
                if (Math.abs(difference) > 0.01) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Allocation Mismatch',
                        text: 'Total allocations must equal receipt amount for exact payment'
                    });
                    return false;
                }
                break;
            case 'over':
                if (difference <= 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Over Payment',
                        text: 'Receipt amount must be greater than total allocations for over payment'
                    });
                    return false;
                }
                break;
            case 'under':
                if (difference >= 0) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid Under Payment',
                        text: 'Total allocations must be greater than receipt amount for under payment'
                    });
                    return false;
                }
                break;
        }

        return true;
    }

    // Form submission
    receiptForm.addEventListener('submit', function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        Swal.fire({
            title: 'Confirm Receipt',
            text: 'Are you sure you want to save this receipt and its allocations?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Save Receipt',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                saveReceipt();
            }
        });
    });

    function saveReceipt() {
        const formData = new FormData(receiptForm);

        // Show processing state
        Swal.fire({
            title: 'Saving Receipt',
            text: 'Please wait while we process your request...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch('save_receipt.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (!data.success) {
                throw new Error(data.error || 'Failed to save receipt');
            }

            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Receipt saved successfully',
                showCancelButton: true,
                confirmButtonText: 'View Receipt',
                cancelButtonText: 'Back to Receipts'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = `view_receipt.php?id=${data.receipt_no}`;
                } else {
                    window.location.href = 'view_receipts.php';
                }
            });
        })
        .catch(error => {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: error.message
            });
        });
    }
});
</script>
</body>
</html>