<?php
require_once '../config/database.php';

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

try {
    // Check if user is authenticated
    if (!isAuthenticated()) {
        echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
        exit;
    }

    $database = new Database();
    $conn = $database->getConnection();

    // Check if transactions table exists, if not create a sample one
    $checkTable = "SHOW TABLES LIKE 'transactions'";
    $stmt = $conn->prepare($checkTable);
    $stmt->execute();
    
    if ($stmt->rowCount() == 0) {
        // Create transactions table if it doesn't exist
        $createTable = "CREATE TABLE transactions (
            id INT AUTO_INCREMENT PRIMARY KEY,
            member_id INT,
            member_name VARCHAR(255),
            type ENUM('income', 'expense') NOT NULL,
            category VARCHAR(100),
            amount DECIMAL(10,2) NOT NULL,
            description TEXT,
            status ENUM('pending', 'completed', 'cancelled') DEFAULT 'pending',
            payment_method VARCHAR(50),
            reference_number VARCHAR(100),
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (member_id) REFERENCES members(id) ON DELETE SET NULL
        )";
        $conn->exec($createTable);
        
        // Insert sample transactions
        $sampleTransactions = [
            [null, 'Membership Fee - John Doe', 'income', 'Membership', 500.00, 'Annual membership fee', 'completed', 'UPI', 'TXN001'],
            [null, 'Event Registration - Jane Smith', 'income', 'Events', 200.00, 'Cultural event registration', 'completed', 'Cash', 'TXN002'],
            [null, 'Office Supplies', 'expense', 'Administrative', 150.00, 'Stationery and office supplies', 'completed', 'Cash', 'TXN003'],
            [null, 'Venue Booking - Raj Kumar', 'income', 'Events', 300.00, 'Sports tournament registration', 'pending', 'Bank Transfer', 'TXN004'],
            [null, 'Utilities Bill', 'expense', 'Utilities', 250.00, 'Monthly electricity bill', 'completed', 'Bank Transfer', 'TXN005']
        ];
        
        $insertStmt = $conn->prepare("INSERT INTO transactions (member_id, member_name, type, category, amount, description, status, payment_method, reference_number) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        foreach ($sampleTransactions as $transaction) {
            $insertStmt->execute($transaction);
        }
    }

    // Fetch recent transactions (last 10)
    $query = "SELECT 
                t.id,
                t.member_id,
                t.member_name,
                t.type,
                t.category,
                t.amount,
                t.description,
                t.status,
                t.payment_method,
                t.reference_number,
                t.created_at,
                m.full_name as member_full_name
              FROM transactions t 
              LEFT JOIN members m ON t.member_id = m.id
              ORDER BY t.created_at DESC 
              LIMIT 10";

    $stmt = $conn->prepare($query);
    $stmt->execute();
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Format the data
    $formattedTransactions = [];
    foreach ($transactions as $transaction) {
        $formattedTransactions[] = [
            'id' => $transaction['id'],
            'member_id' => $transaction['member_id'],
            'member_name' => $transaction['member_full_name'] ?: $transaction['member_name'],
            'type' => $transaction['type'],
            'category' => $transaction['category'],
            'amount' => $transaction['amount'],
            'description' => $transaction['description'],
            'status' => $transaction['status'],
            'payment_method' => $transaction['payment_method'],
            'reference_number' => $transaction['reference_number'],
            'created_at' => $transaction['created_at']
        ];
    }

    echo json_encode([
        'success' => true,
        'data' => $formattedTransactions,
        'count' => count($formattedTransactions)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching recent transactions: ' . $e->getMessage()
    ]);
}
?>
