<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
require_once __DIR__ . '/../includes/require_auth.php';
require_role(['admin', 'accountant', 'cashier']);

header('Content-Type: application/json');
require_once '../config.php';

$action = $_GET['action'] ?? '';

try {
    $conn = getDBConnection();
    
    // Handle JSON responses for add/update/delete
    if (in_array($action, ['add', 'update', 'delete'])) {
        if ($action === 'add') {
            $expense_date   = trim((string) ($_POST['expense_date']   ?? ''));
            $category       = trim((string) ($_POST['category']       ?? ''));
            $description    = trim((string) ($_POST['description']    ?? ''));
            $amount         = floatval($_POST['amount'] ?? 0);
            $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
            $vendor         = trim((string) ($_POST['vendor']         ?? ''));

            if (empty($expense_date) || empty($category) || empty($description) || $amount <= 0) {
                echo json_encode(['success' => false, 'message' => 'Please fill all required fields']);
                exit;
            }

            $stmt = $conn->prepare("INSERT INTO expenses (expense_date, category, description, amount, payment_method, vendor) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssdss", $expense_date, $category, $description, $amount, $payment_method, $vendor);

            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Expense added successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to add expense: ' . $stmt->error]);
            }
            $stmt->close();
        }
        elseif ($action === 'update') {
            $id             = intval($_POST['id'] ?? 0);
            $expense_date   = trim((string) ($_POST['expense_date']   ?? ''));
            $category       = trim((string) ($_POST['category']       ?? ''));
            $description    = trim((string) ($_POST['description']    ?? ''));
            $amount         = floatval($_POST['amount'] ?? 0);
            $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
            $vendor         = trim((string) ($_POST['vendor']         ?? ''));

            $stmt = $conn->prepare("UPDATE expenses SET expense_date = ?, category = ?, description = ?, amount = ?, payment_method = ?, vendor = ? WHERE id = ?");
            $stmt->bind_param("sssdssi", $expense_date, $category, $description, $amount, $payment_method, $vendor, $id);

            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Expense updated successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to update expense: ' . $stmt->error]);
            }
            $stmt->close();
        }
        elseif ($action === 'delete') {
            $id = intval($_GET['id'] ?? 0);
            
            $stmt = $conn->prepare("DELETE FROM expenses WHERE id = ?");
            $stmt->bind_param("i", $id);

            if ($stmt->execute()) {
                echo json_encode(['success' => true, 'message' => 'Expense deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Failed to delete expense: ' . $stmt->error]);
            }
            $stmt->close();
        }
        
        $conn->close();
        exit;
    }
    
    // Handle HTML response for edit
    if ($action === 'edit') {
        header('Content-Type: text/html; charset=utf-8');
        $id = intval($_GET['id'] ?? 0);
        $result = $conn->query("SELECT * FROM expenses WHERE id = $id");
        $expense = $result ? $result->fetch_assoc() : null;

        if ($expense) {
            echo '<input type="hidden" name="id" value="' . $expense['id'] . '">';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Expense Date</label>';
            echo '<input type="date" class="form-control" name="expense_date" value="' . htmlspecialchars($expense['expense_date']) . '" required>';
            echo '</div>';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Category</label>';
            echo '<select class="form-select" name="category" required>';
            $categories = ['Salaries', 'Utilities', 'Supplies', 'Maintenance', 'Transport', 'Events', 'Other'];
            foreach ($categories as $cat) {
                $selected = ($expense['category'] === $cat) ? 'selected' : '';
                echo "<option value='$cat' $selected>$cat</option>";
            }
            echo '</select></div>';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Description</label>';
            echo '<textarea class="form-control" name="description" rows="2" required>' . htmlspecialchars($expense['description']) . '</textarea>';
            echo '</div>';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Amount</label>';
            echo '<input type="number" class="form-control" name="amount" value="' . $expense['amount'] . '" step="0.01" required>';
            echo '</div>';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Payment Method</label>';
            echo '<select class="form-select" name="payment_method">';
            echo '<option value="cash" ' . ($expense['payment_method'] === 'cash' ? 'selected' : '') . '>Cash</option>';
            echo '<option value="card" ' . ($expense['payment_method'] === 'card' ? 'selected' : '') . '>Card</option>';
            echo '<option value="bank_transfer" ' . ($expense['payment_method'] === 'bank_transfer' ? 'selected' : '') . '>Bank Transfer</option>';
            echo '</select></div>';
            echo '<div class="mb-3">';
            echo '<label class="form-label">Vendor</label>';
            echo '<input type="text" class="form-control" name="vendor" value="' . htmlspecialchars($expense['vendor']) . '">';
            echo '</div>';
            echo '<script>
                $("#editExpenseForm").on("submit", function(e) {
                    e.preventDefault();
                    showLoader();
                    $.ajax({
                        url: "ajax/expenses.php?action=update",
                        type: "POST",
                        data: $(this).serialize(),
                        dataType: "json",
                        success: function(response) {
                            hideLoader();
                            if (response.success) {
                                showToast(response.message, "success");
                                $("#editExpenseModal").modal("hide");
                                setTimeout(function() { location.reload(); }, 1000);
                            } else {
                                showToast(response.message, "error");
                            }
                        },
                        error: function(xhr, status, error) {
                            hideLoader();
                            showToast("Error: " + error, "error");
                        }
                    });
                });
            </script>';
        } else {
            echo '<p>Expense not found</p>';
        }
        
        $conn->close();
        exit;
    }
    
    // Default response
    echo json_encode(['success' => false, 'message' => 'Invalid action']);
    $conn->close();
    
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>