<?php 
include 'db.php'; 
include 'auth.php';
include 'includes/tax_helpers.php'; // For getSetting function
require_right('Add Expense'); 
?>

<!DOCTYPE html>
<html>
<head>
    <title>Add Expense</title>
    <link rel="stylesheet" href="assets/css/bootstrap.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <style>
        .select2-container { width: 100% !important; }
        .mapping-info {
            background-color: #e8f5e8;
            border: 1px solid #28a745;
            border-radius: 4px;
            padding: 8px 12px;
            margin-top: 5px;
            font-size: 0.9em;
        }
        .no-mapping-info {
            background-color: #fff3cd;
            border: 1px solid #ffc107;
            border-radius: 4px;
            padding: 8px 12px;
            margin-top: 5px;
            font-size: 0.9em;
        }
    </style>
</head>
<body class="p-4">

<h4 class="mb-3">Add New Expense</h4>
<form method="POST" id="expenseForm">
    <div class="row g-3">
        <div class="col-md-6">
            <label class="form-label">Expense Account</label>
            <select name="account_id" id="account_id" class="form-select select2" required>
                <option value="">Select Expense Account</option>
                <?php
                // Check if mapping columns exist
                $columns_exist = false;
                $result = mysqli_query($conn, "SHOW COLUMNS FROM expense_accounts LIKE 'chart_of_account_id'");
                if ($result && mysqli_num_rows($result) > 0) {
                    $columns_exist = true;
                }
                
                if ($columns_exist) {
                    // Show expense accounts with mapping info
                    $res = mysqli_query($conn, "
                        SELECT ea.id, ea.name, coa.account_code, coa.account_name, coa.account_category
                        FROM expense_accounts ea
                        LEFT JOIN chart_of_accounts coa ON ea.chart_of_account_id = coa.id
                        ORDER BY ea.name
                    ");
                } else {
                    // Fallback without mapping
                    $res = mysqli_query($conn, "SELECT id, name FROM expense_accounts ORDER BY name");
                }
                
                while ($row = mysqli_fetch_assoc($res)) {
                    if ($columns_exist && $row['account_code']) {
                        $category = ucwords(str_replace('_', ' ', $row['account_category']));
                        echo "<option value='{$row['id']}' data-mapped='true' data-code='{$row['account_code']}' data-name='{$row['account_name']}' data-category='{$category}'>
                            {$row['name']} → {$row['account_code']} - {$row['account_name']}
                        </option>";
                    } else {
                        echo "<option value='{$row['id']}' data-mapped='false'>{$row['name']}</option>";
                    }
                }
                ?>
            </select>
            <div id="mappingInfo" class="mapping-info mt-2" style="display: none;">
                <i class="fa fa-check-circle text-success"></i> 
                <strong>Mapped to Chart of Account:</strong> <span id="mappedAccountInfo"></span>
            </div>
            <div id="noMappingInfo" class="no-mapping-info mt-2" style="display: none;">
                <i class="fa fa-exclamation-triangle text-warning"></i> 
                <strong>Not Mapped:</strong> This expense account is not mapped to a chart of account. 
                The expense will be recorded but won't affect the financial statements.
            </div>
        </div>

        <div class="col-md-6">
            <label class="form-label">Payment Method</label>
            <select id="payment_method" name="payment_method" class="form-select" required>
                <option value="cash">Cash</option>
                <option value="bank">Bank</option>
                <option value="card">Card</option>
                <option value="upi">UPI</option>
            </select>
        </div>

        <div class="col-12 d-none" id="bank-account-wrapper">
            <label class="form-label">Select Bank Account</label>
            <select name="bank_account_id" id="bank_account_id" class="form-select">
                <option value="">-- Select Bank --</option>
                <?php
                $banks = mysqli_query($conn, "SELECT id, account_title FROM bank_accounts WHERE is_active = 1");
                while ($b = mysqli_fetch_assoc($banks)) {
                    echo "<option value='{$b['id']}'>" . htmlspecialchars($b['account_title']) . "</option>";
                }
                ?>
            </select>
        </div>

        <div class="col-md-6">
            <label class="form-label">Amount</label>
            <input type="number" step="0.01" name="amount" class="form-control" required placeholder="Amount">
        </div>

        <div class="col-md-6">
            <label class="form-label">Remarks</label>
            <textarea name="remarks" class="form-control" rows="1" placeholder="Remarks"></textarea>
        </div>

        <div class="col-12">
            <button type="submit" name="save_expense" class="btn btn-primary">Save Expense</button>
        </div>
    </div>
</form>

<?php
if (isset($_POST['save_expense'])) {
    $account_id = intval($_POST['account_id']);
    $amount = floatval($_POST['amount']);
    $remarks = mysqli_real_escape_string($conn, $_POST['remarks']);
    $payment_method = $_POST['payment_method'];
    $bank_account_id = !empty($_POST['bank_account_id']) ? intval($_POST['bank_account_id']) : null;

    // Check if expense approval is enabled
    $approval_enabled = getSetting($conn, 'expense_approval_enabled', '0') === '1';
    $expense_status = $approval_enabled ? 'pending' : 'approved';
    $approved_by = $approval_enabled ? null : $_SESSION['user_id'];
    $approved_at = $approval_enabled ? null : date('Y-m-d H:i:s');

    // Insert the expense
    $insert_sql = "
        INSERT INTO expenses (account_id, amount, remarks, payment_method, bank_account_id, status, approved_by, approved_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ";
    $stmt = mysqli_prepare($conn, $insert_sql);
    mysqli_stmt_bind_param($stmt, "idssisss", $account_id, $amount, $remarks, $payment_method, $bank_account_id, $expense_status, $approved_by, $approved_at);
    
    if (mysqli_stmt_execute($stmt)) {
        $expense_id = mysqli_insert_id($conn);
        
        // Try to create journal entry if mapping exists and expense is approved
        $journal_entry_id = null;
        $financial_message = "";
        
        if ($expense_status === 'approved') {
            // Check if mapping columns exist
            $columns_exist = false;
            $result = mysqli_query($conn, "SHOW COLUMNS FROM expense_accounts LIKE 'chart_of_account_id'");
            if ($result && mysqli_num_rows($result) > 0) {
                $columns_exist = true;
            }
            
            if ($columns_exist) {
                // Include financial helpers
                include_once 'financial_helpers.php';
                include_once 'journal_entry_handler.php';
                
                // Try to create journal entry
                if (createExpenseJournalEntry($conn, $expense_id, $amount, $account_id, $payment_method, $_SESSION['store_id'] ?? 1, $bank_account_id)) {
                    // Get the journal entry ID
                    $stmt = mysqli_prepare($conn, "SELECT id FROM journal_entries WHERE source_type = 'expense' AND reference_id = ? ORDER BY created_at DESC LIMIT 1");
                    mysqli_stmt_bind_param($stmt, "i", $expense_id);
                    mysqli_stmt_execute($stmt);
                    $result = mysqli_stmt_get_result($stmt);
                    if ($row = mysqli_fetch_assoc($result)) {
                        $journal_entry_id = $row['id'];
                        
                        // Update expense with journal entry ID
                        $update_sql = "UPDATE expenses SET journal_entry_id = ? WHERE id = ?";
                        $stmt = mysqli_prepare($conn, $update_sql);
                        mysqli_stmt_bind_param($stmt, "ii", $journal_entry_id, $expense_id);
                        mysqli_stmt_execute($stmt);
                    }
                    
                    $financial_message = " and journal entry created successfully!";
                } else {
                    $financial_message = " (journal entry creation failed - check mapping)";
                }
            }
        } else {
            $financial_message = " (pending approval - journal entry will be created after approval)";
        }
        
        $success_title = $expense_status === 'pending' ? 'Expense Submitted for Approval!' : 'Expense Added!';
        $success_icon = $expense_status === 'pending' ? 'info' : 'success';
        
        echo "<script>
            window.onload = function() {
                Swal.fire({
                    icon: '$success_icon',
                    title: '$success_title',
                    text: 'The expense has been successfully saved" . $financial_message . "',
                    confirmButtonText: 'OK'
                }).then(() => {
                    window.parent.location.reload();
                });
            };
        </script>";
    } else {
        echo "<script>
            window.onload = function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Error!',
                    text: 'Failed to save expense. Please try again.',
                    confirmButtonText: 'OK'
                });
            };
        </script>";
    }
}
?>

<!-- JS Includes -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="assets/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $('.select2').select2();

    $('#payment_method').on('change', function () {
        if (this.value === 'bank' || this.value === 'card' || this.value === 'upi') {
            $('#bank-account-wrapper').removeClass('d-none');
        } else {
            $('#bank-account-wrapper').addClass('d-none');
            $('#bank_account_id').val('');
        }
    });
    
    // Handle expense account selection to show mapping info
    $('#account_id').on('change', function() {
        const selectedOption = this.options[this.selectedIndex];
        const mappingInfo = $('#mappingInfo');
        const noMappingInfo = $('#noMappingInfo');
        const mappedAccountInfo = $('#mappedAccountInfo');
        
        if (this.value) {
            const isMapped = selectedOption.getAttribute('data-mapped') === 'true';
            
            if (isMapped) {
                const accountCode = selectedOption.getAttribute('data-code');
                const accountName = selectedOption.getAttribute('data-name');
                const category = selectedOption.getAttribute('data-category');
                
                mappedAccountInfo.text(`${accountCode} - ${accountName} (${category})`);
                mappingInfo.show();
                noMappingInfo.hide();
            } else {
                mappingInfo.hide();
                noMappingInfo.show();
            }
        } else {
            mappingInfo.hide();
            noMappingInfo.hide();
        }
    });
</script>

</body>
</html>
