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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Get expense ID from URL
$expense_id = $_GET['id'] ?? 0;

if (!$expense_id) {
    header('Location: list_expenses.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get expense details
$expense_query = "SELECT * FROM expenses WHERE expense_id = ?";
$stmt = $conn->prepare($expense_query);
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$expense = $stmt->get_result()->fetch_assoc();

if (!$expense) {
    header('Location: list_expenses.php?error=expense_not_found');
    exit();
}

// Check if expense can be edited
if (!in_array($expense['status'], ['DRAFT', 'PENDING'])) {
    header('Location: view_expense.php?id=' . $expense_id . '&error=cannot_edit');
    exit();
}

// Get expense categories
$categories_query = "SELECT * FROM expense_categories WHERE is_active = 1 ORDER BY category_name";
$categories = $conn->query($categories_query);

// Get funds for selection
$funds_query = "SELECT * FROM funds WHERE is_active = 1 ORDER BY fund_name";
$funds = $conn->query($funds_query);

// Handle form submission
$success_message = '';
$error_message = '';

if ($_POST && isset($_POST['update_expense'])) {
    $expense_title = trim($_POST['expense_title']);
    $category_id = $_POST['category_id'];
    $amount = floatval($_POST['amount']);
    $expense_date = $_POST['expense_date'];
    $payment_method = $_POST['payment_method'];
    $payment_reference = trim($_POST['payment_reference']);
    $vendor_name = trim($_POST['vendor_name']);
    $vendor_contact = trim($_POST['vendor_contact']);
    $receipt_number = trim($_POST['receipt_number']);
    $location = trim($_POST['location']);
    $fund_id = !empty($_POST['fund_id']) ? intval($_POST['fund_id']) : null;
    $description = trim($_POST['description']);
    $tags = trim($_POST['tags']);
    $notes = trim($_POST['notes']);
    $is_recurring = isset($_POST['is_recurring']) ? 1 : 0;
    $recurring_frequency = $is_recurring ? $_POST['recurring_frequency'] : null;
    $next_due_date = ($is_recurring && !empty($_POST['next_due_date'])) ? $_POST['next_due_date'] : null;
    
    // Validation
    if (empty($expense_title) || empty($category_id) || $amount <= 0 || empty($expense_date)) {
        $error_message = "Please fill in all required fields.";
    } else {
        $update_query = "UPDATE expenses SET 
                        expense_title = ?, 
                        category_id = ?, 
                        amount = ?, 
                        expense_date = ?, 
                        payment_method = ?, 
                        payment_reference = ?, 
                        vendor_name = ?, 
                        vendor_contact = ?, 
                        receipt_number = ?, 
                        location = ?, 
                        fund_id = ?, 
                        description = ?, 
                        tags = ?, 
                        notes = ?, 
                        is_recurring = ?, 
                        recurring_frequency = ?, 
                        next_due_date = ?,
                        updated_at = NOW()
                        WHERE expense_id = ?";
        
        $stmt_update = $conn->prepare($update_query);
        $stmt_update->bind_param("sissssssssissssssi", 
            $expense_title, $category_id, $amount, $expense_date, $payment_method,
            $payment_reference, $vendor_name, $vendor_contact, $receipt_number,
            $location, $fund_id, $description, $tags, $notes, $is_recurring,
            $recurring_frequency, $next_due_date, $expense_id
        );
        
        if ($stmt_update->execute()) {
            // Log the activity
            $activity_query = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values) VALUES (?, 'UPDATE', 'EXPENSES', ?, 'EXPENSE', ?)";
            $activity_stmt = $conn->prepare($activity_query);
            $activity_data = json_encode([
                'expense_title' => $expense_title,
                'amount' => $amount,
                'expense_date' => $expense_date
            ]);
            $activity_stmt->bind_param("iis", $user_id, $expense_id, $activity_data);
            $activity_stmt->execute();
            
            $success_message = "Expense updated successfully!";
            
            // Refresh expense data
            $stmt->execute();
            $expense = $stmt->get_result()->fetch_assoc();
        } else {
            $error_message = "Failed to update expense. Please try again.";
        }
    }
}

// Handle AJAX form submission
if ($_POST && isset($_POST['ajax_update'])) {
    header('Content-Type: application/json');
    
    $expense_title = trim($_POST['expense_title']);
    $category_id = $_POST['category_id'];
    $amount = floatval($_POST['amount']);
    $expense_date = $_POST['expense_date'];
    $payment_method = $_POST['payment_method'];
    $payment_reference = trim($_POST['payment_reference']);
    $vendor_name = trim($_POST['vendor_name']);
    $vendor_contact = trim($_POST['vendor_contact']);
    $receipt_number = trim($_POST['receipt_number']);
    $location = trim($_POST['location']);
    $fund_id = !empty($_POST['fund_id']) ? intval($_POST['fund_id']) : null;
    $description = trim($_POST['description']);
    $tags = trim($_POST['tags']);
    $notes = trim($_POST['notes']);
    $is_recurring = isset($_POST['is_recurring']) ? 1 : 0;
    $recurring_frequency = $is_recurring ? $_POST['recurring_frequency'] : null;
    $next_due_date = ($is_recurring && !empty($_POST['next_due_date'])) ? $_POST['next_due_date'] : null;
    
    $response = ['success' => false, 'message' => ''];
    
    // Validation
    if (empty($expense_title) || empty($category_id) || $amount <= 0 || empty($expense_date)) {
        $response['message'] = "Please fill in all required fields.";
    } else {
        $update_query = "UPDATE expenses SET 
                        expense_title = ?, 
                        category_id = ?, 
                        amount = ?, 
                        expense_date = ?, 
                        payment_method = ?, 
                        payment_reference = ?, 
                        vendor_name = ?, 
                        vendor_contact = ?, 
                        receipt_number = ?, 
                        location = ?, 
                        fund_id = ?, 
                        description = ?, 
                        tags = ?, 
                        notes = ?, 
                        is_recurring = ?, 
                        recurring_frequency = ?, 
                        next_due_date = ?,
                        updated_at = NOW()
                        WHERE expense_id = ?";
        
        $stmt_update = $conn->prepare($update_query);
        $stmt_update->bind_param("sissssssssissssssi", 
            $expense_title, $category_id, $amount, $expense_date, $payment_method,
            $payment_reference, $vendor_name, $vendor_contact, $receipt_number,
            $location, $fund_id, $description, $tags, $notes, $is_recurring,
            $recurring_frequency, $next_due_date, $expense_id
        );
        
        if ($stmt_update->execute()) {
            $response['success'] = true;
            $response['message'] = 'Expense updated successfully!';
            $response['redirect'] = 'view_expense.php?id=' . $expense_id;
        } else {
            $response['message'] = 'Failed to update expense. Please try again.';
        }
    }
    
    echo json_encode($response);
    exit();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Expense - Personal Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Form Card */
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 2rem;
        }
        
        .form-section {
            margin-bottom: 2rem;
            padding-bottom: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .form-section:last-child {
            border-bottom: none;
            margin-bottom: 0;
        }
        
        .section-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        /* Form Controls */
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
            transition: all 0.2s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #f59e0b;
            box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1);
        }
        
        .form-control.is-invalid {
            border-color: #dc2626;
        }
        
        .invalid-feedback {
            color: #dc2626;
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        /* Required field indicator */
        .required {
            color: #dc2626;
        }
        
        /* Buttons */
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary { background: #f59e0b; color: white; }
        .btn-primary:hover { background: #d97706; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-secondary { background: #6b7280; color: white; }
        .btn-secondary:hover { background: #4b5563; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border: none;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Checkbox and Radio Styles */
        .form-check-input {
            margin-top: 0.25rem;
        }
        
        .form-check-label {
            font-weight: 500;
            color: #374151;
        }
        
        /* Recurring Options */
        .recurring-options {
            background: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 1rem;
            margin-top: 1rem;
            display: none;
        }
        
        .recurring-options.show {
            display: block;
        }
        
        /* File Upload */
        .file-upload-area {
            border: 2px dashed #e2e8f0;
            border-radius: 8px;
            padding: 2rem;
            text-align: center;
            background: #f8fafc;
            transition: all 0.2s ease;
        }
        
        .file-upload-area:hover {
            border-color: #f59e0b;
            background: #fef3c7;
        }
        
        .file-upload-area.dragover {
            border-color: #f59e0b;
            background: #fef3c7;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .form-card {
                padding: 1.5rem;
            }
            
            .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Edit Expense</h1>
                        <p class="page-subtitle">Expense #<?php echo htmlspecialchars($expense['expense_number']); ?></p>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <i class="ph-check-circle me-2"></i>
                            <?php echo htmlspecialchars($success_message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger">
                            <i class="ph-warning-circle me-2"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                        </div>
                    <?php endif; ?>

                    <!-- Main Form -->
                    <div class="form-card">
                        <form id="expenseForm" method="POST">
                            <input type="hidden" name="update_expense" value="1">
                            
                            <!-- Basic Information -->
                            <div class="form-section">
                                <h3 class="section-title">Basic Information</h3>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">Expense Title <span class="required">*</span></label>
                                        <input type="text" class="form-control" name="expense_title" 
                                               value="<?php echo htmlspecialchars($expense['expense_title']); ?>" 
                                               placeholder="Enter expense title" required>
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Category <span class="required">*</span></label>
                                        <select class="form-select" name="category_id" required>
                                            <option value="">Select Category</option>
                                            <?php while ($category = $categories->fetch_assoc()): ?>
                                                <option value="<?php echo $category['category_id']; ?>" 
                                                        <?php echo $expense['category_id'] == $category['category_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($category['category_name']); ?> 
                                                    (<?php echo ucfirst(str_replace('_', ' ', strtolower($category['category_type']))); ?>)
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-4">
                                        <label class="form-label">Amount (KES) <span class="required">*</span></label>
                                        <input type="number" class="form-control" name="amount" step="0.01" min="0" 
                                               value="<?php echo $expense['amount']; ?>" 
                                               placeholder="0.00" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Expense Date <span class="required">*</span></label>
                                        <input type="date" class="form-control" name="expense_date" 
                                               value="<?php echo $expense['expense_date']; ?>" required>
                                    </div>
                                    <div class="col-md-4">
                                        <label class="form-label">Payment Method <span class="required">*</span></label>
                                        <select class="form-select" name="payment_method" required>
                                            <option value="">Select Method</option>
                                            <option value="CASH" <?php echo $expense['payment_method'] == 'CASH' ? 'selected' : ''; ?>>Cash</option>
                                            <option value="CARD" <?php echo $expense['payment_method'] == 'CARD' ? 'selected' : ''; ?>>Card</option>
                                            <option value="BANK_TRANSFER" <?php echo $expense['payment_method'] == 'BANK_TRANSFER' ? 'selected' : ''; ?>>Bank Transfer</option>
                                            <option value="MPESA" <?php echo $expense['payment_method'] == 'MPESA' ? 'selected' : ''; ?>>M-Pesa</option>
                                            <option value="MOBILE_MONEY" <?php echo $expense['payment_method'] == 'MOBILE_MONEY' ? 'selected' : ''; ?>>Mobile Money</option>
                                            <option value="CHEQUE" <?php echo $expense['payment_method'] == 'CHEQUE' ? 'selected' : ''; ?>>Cheque</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-12">
                                        <label class="form-label">Description</label>
                                        <textarea class="form-control" name="description" rows="3" 
                                                  placeholder="Enter expense description"><?php echo htmlspecialchars($expense['description']); ?></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Vendor & Payment Details -->
                            <div class="form-section">
                                <h3 class="section-title">Vendor & Payment Details</h3>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">Vendor Name</label>
                                        <input type="text" class="form-control" name="vendor_name" 
                                               value="<?php echo htmlspecialchars($expense['vendor_name']); ?>" 
                                               placeholder="Enter vendor name">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Vendor Contact</label>
                                        <input type="text" class="form-control" name="vendor_contact" 
                                               value="<?php echo htmlspecialchars($expense['vendor_contact']); ?>" 
                                               placeholder="Phone or email">
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Payment Reference</label>
                                        <input type="text" class="form-control" name="payment_reference" 
                                               value="<?php echo htmlspecialchars($expense['payment_reference']); ?>" 
                                               placeholder="Transaction reference">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Receipt Number</label>
                                        <input type="text" class="form-control" name="receipt_number" 
                                               value="<?php echo htmlspecialchars($expense['receipt_number']); ?>" 
                                               placeholder="Receipt number">
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-6">
                                        <label class="form-label">Location</label>
                                        <input type="text" class="form-control" name="location" 
                                               value="<?php echo htmlspecialchars($expense['location']); ?>" 
                                               placeholder="Where expense occurred">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="form-label">Fund Source</label>
                                        <select class="form-select" name="fund_id">
                                            <option value="">Select Fund (Optional)</option>
                                            <?php while ($fund = $funds->fetch_assoc()): ?>
                                                <option value="<?php echo $fund['fund_id']; ?>" 
                                                        <?php echo $expense['fund_id'] == $fund['fund_id'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($fund['fund_name']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Additional Information -->
                            <div class="form-section">
                                <h3 class="section-title">Additional Information</h3>
                                
                                <div class="row">
                                    <div class="col-md-6">
                                        <label class="form-label">Tags</label>
                                        <input type="text" class="form-control" name="tags" 
                                               value="<?php echo htmlspecialchars($expense['tags']); ?>" 
                                               placeholder="e.g., office, travel, equipment (comma separated)">
                                        <small class="text-muted">Separate multiple tags with commas</small>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-check mt-4">
                                            <input class="form-check-input" type="checkbox" name="is_recurring" 
                                                   id="isRecurring" <?php echo $expense['is_recurring'] ? 'checked' : ''; ?>>
                                            <label class="form-check-label" for="isRecurring">
                                                This is a recurring expense
                                            </label>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Recurring Options -->
                                <div class="recurring-options <?php echo $expense['is_recurring'] ? 'show' : ''; ?>" id="recurringOptions">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <label class="form-label">Frequency</label>
                                            <select class="form-select" name="recurring_frequency">
                                                <option value="">Select Frequency</option>
                                                <option value="DAILY" <?php echo $expense['recurring_frequency'] == 'DAILY' ? 'selected' : ''; ?>>Daily</option>
                                                <option value="WEEKLY" <?php echo $expense['recurring_frequency'] == 'WEEKLY' ? 'selected' : ''; ?>>Weekly</option>
                                                <option value="MONTHLY" <?php echo $expense['recurring_frequency'] == 'MONTHLY' ? 'selected' : ''; ?>>Monthly</option>
                                                <option value="QUARTERLY" <?php echo $expense['recurring_frequency'] == 'QUARTERLY' ? 'selected' : ''; ?>>Quarterly</option>
                                                <option value="YEARLY" <?php echo $expense['recurring_frequency'] == 'YEARLY' ? 'selected' : ''; ?>>Yearly</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="form-label">Next Due Date</label>
                                            <input type="date" class="form-control" name="next_due_date" 
                                                   value="<?php echo $expense['next_due_date']; ?>">
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="row mt-3">
                                    <div class="col-md-12">
                                        <label class="form-label">Additional Notes</label>
                                        <textarea class="form-control" name="notes" rows="3" 
                                                  placeholder="Any additional notes about this expense"><?php echo htmlspecialchars($expense['notes']); ?></textarea>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Actions -->
                            <div class="d-flex gap-3 justify-content-end">
                                <a href="view_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn btn-secondary">
                                    <i class="ph-arrow-left"></i> Cancel
                                </a>
                                <button type="button" class="btn btn-success" onclick="saveAndContinue()">
                                    <i class="ph-floppy-disk"></i> Save & Continue Editing
                                </button>
                                <button type="submit" class="btn btn-primary">
                                    <i class="ph-check"></i> Update Expense
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.all.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Toggle recurring options
            $('#isRecurring').change(function() {
                if ($(this).is(':checked')) {
                    $('#recurringOptions').addClass('show');
                } else {
                    $('#recurringOptions').removeClass('show');
                }
            });

            // Form submission with SweetAlert
            $('#expenseForm').submit(function(e) {
                e.preventDefault();
                
                Swal.fire({
                    title: 'Update Expense?',
                    text: 'Are you sure you want to update this expense?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#f59e0b',
                    cancelButtonColor: '#6b7280',
                    confirmButtonText: 'Yes, Update',
                    cancelButtonText: 'Cancel'
                }).then((result) => {
                    if (result.isConfirmed) {
                        submitForm(false);
                    }
                });
            });

            // Auto-save functionality
            let autoSaveTimer;
            $('#expenseForm input, #expenseForm select, #expenseForm textarea').on('input change', function() {
                clearTimeout(autoSaveTimer);
                autoSaveTimer = setTimeout(function() {
                    autoSave();
                }, 30000); // Auto-save after 30 seconds of inactivity
            });
        });

        function saveAndContinue() {
            Swal.fire({
                title: 'Save Changes?',
                text: 'This will save your current changes and keep the form open for editing.',
                icon: 'info',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Save Changes',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    submitForm(true);
                }
            });
        }

        function submitForm(stayOnPage = false) {
            const formData = new FormData($('#expenseForm')[0]);
            formData.append('ajax_update', '1');
            
            Swal.fire({
                title: 'Updating...',
                text: 'Please wait while we update the expense.',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });

            $.ajax({
                url: window.location.href,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: response.message,
                            icon: 'success',
                            confirmButtonColor: '#059669'
                        }).then(() => {
                            if (!stayOnPage && response.redirect) {
                                window.location.href = response.redirect;
                            } else if (!stayOnPage) {
                                window.location.href = 'view_expense.php?id=<?php echo $expense_id; ?>';
                            }
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: response.message,
                            icon: 'error',
                            confirmButtonColor: '#dc2626'
                        });
                    }
                },
                error: function() {
                    Swal.fire({
                        title: 'Error!',
                        text: 'An unexpected error occurred. Please try again.',
                        icon: 'error',
                        confirmButtonColor: '#dc2626'
                    });
                }
            });
        }

        function autoSave() {
            const formData = new FormData($('#expenseForm')[0]);
            formData.append('ajax_update', '1');
            
            $.ajax({
                url: window.location.href,
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function(response) {
                    if (response.success) {
                        // Show subtle notification for auto-save
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 2000,
                            timerProgressBar: true
                        });
                        
                        Toast.fire({
                            icon: 'success',
                            title: 'Changes saved automatically'
                        });
                    }
                },
                error: function() {
                    // Silently fail for auto-save
                    console.log('Auto-save failed');
                }
            });
        }

        // Warn before leaving page with unsaved changes
        let hasUnsavedChanges = false;
        $('#expenseForm input, #expenseForm select, #expenseForm textarea').on('input change', function() {
            hasUnsavedChanges = true;
        });

        $(window).on('beforeunload', function() {
            if (hasUnsavedChanges) {
                return 'You have unsaved changes. Are you sure you want to leave?';
            }
        });

        // Remove warning when form is submitted
        $('#expenseForm').on('submit', function() {
            hasUnsavedChanges = false;
        });

        // Validation
        function validateForm() {
            let isValid = true;
            
            // Required fields
            const requiredFields = ['expense_title', 'category_id', 'amount', 'expense_date', 'payment_method'];
            
            requiredFields.forEach(function(field) {
                const element = $('[name="' + field + '"]');
                if (!element.val() || (field === 'amount' && parseFloat(element.val()) <= 0)) {
                    element.addClass('is-invalid');
                    isValid = false;
                } else {
                    element.removeClass('is-invalid');
                }
            });
            
            return isValid;
        }

        // Real-time validation
        $('#expenseForm input, #expenseForm select').on('blur', function() {
            const field = $(this).attr('name');
            if (['expense_title', 'category_id', 'amount', 'expense_date', 'payment_method'].includes(field)) {
                if (!$(this).val() || (field === 'amount' && parseFloat($(this).val()) <= 0)) {
                    $(this).addClass('is-invalid');
                } else {
                    $(this).removeClass('is-invalid');
                }
            }
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>

<?php $conn->close(); ?>