<?php
require_once '../includes/User.php';
require_once '../includes/db_config.php';

header('Content-Type: application/json');

if (!User::isLoggedIn() || !User::isAdmin()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized access']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    $pdo = getDBConnection();
    
    switch ($method) {
        case 'GET':
            if (isset($_GET['id'])) {
                $stmt = $pdo->prepare("SELECT * FROM expenses WHERE id = ?");
                $stmt->execute([$_GET['id']]);
                $expense = $stmt->fetch(PDO::FETCH_ASSOC);
                
                if ($expense) {
                    echo json_encode(['success' => true, 'data' => $expense]);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Expense not found']);
                }
            } else {
                $stmt = $pdo->prepare("
                    SELECT * FROM expenses 
                    ORDER BY expense_date DESC, created_at DESC 
                    LIMIT 100
                ");
                $stmt->execute();
                $expenses = $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                echo json_encode(['success' => true, 'data' => $expenses]);
            }
            break;
            
        case 'POST':
            $data = $_POST;
            
            if (isset($data['id']) && !empty($data['id'])) {
                $stmt = $pdo->prepare("
                    UPDATE expenses 
                    SET category = ?, description = ?, amount = ?, expense_date = ?, 
                        receipt_number = ?, notes = ?
                    WHERE id = ?
                ");
                $result = $stmt->execute([
                    $data['category'],
                    $data['description'],
                    $data['amount'],
                    $data['expense_date'],
                    $data['receipt_number'] ?? null,
                    $data['notes'] ?? null,
                    $data['id']
                ]);
                
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Expense updated successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to update expense']);
                }
            } else {
                
                $stmt = $pdo->prepare("
                    INSERT INTO expenses (category, description, amount, expense_date, receipt_number, notes) 
                    VALUES (?, ?, ?, ?, ?, ?)
                ");
                $result = $stmt->execute([
                    $data['category'],
                    $data['description'],
                    $data['amount'],
                    $data['expense_date'],
                    $data['receipt_number'] ?? null,
                    $data['notes'] ?? null
                ]);
                
                if ($result) {
                    echo json_encode(['success' => true, 'message' => 'Expense added successfully']);
                } else {
                    echo json_encode(['success' => false, 'error' => 'Failed to add expense']);
                }
            }
            break;
            
        case 'DELETE':
            $input = json_decode(file_get_contents('php://input'), true);
            
            if (!isset($input['id'])) {
                echo json_encode(['success' => false, 'error' => 'Expense ID is required']);
                exit();
            }
            
            $stmt = $pdo->prepare("DELETE FROM expenses WHERE id = ?");
            $result = $stmt->execute([$input['id']]);
            
            if ($result) {
                echo json_encode(['success' => true, 'message' => 'Expense deleted successfully']);
            } else {
                echo json_encode(['success' => false, 'error' => 'Failed to delete expense']);
            }
            break;
            
        default:
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            break;
    }
    
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Error: ' . $e->getMessage()]);
}
?>
