<?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;
    }

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        echo json_encode(['success' => false, 'message' => 'Method not allowed']);
        exit;
    }

    $pdo = getDBConnection();

    // Get POST data
    $type = $_POST['type'] ?? '';
    $amount = $_POST['amount'] ?? '';
    $description = $_POST['description'] ?? '';
    $member_id = $_POST['member_id'] ?? null;
    $category = $_POST['category'] ?? '';

    // Validate required fields
    if (empty($type) || empty($amount) || empty($description)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        exit;
    }

    // Create transactions table if it doesn't exist
    $createTable = "CREATE TABLE IF NOT EXISTS transactions (
        id INT AUTO_INCREMENT PRIMARY KEY,
        type ENUM('income', 'expense') NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        description TEXT NOT NULL,
        member_id INT NULL,
        category VARCHAR(100),
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        created_by INT,
        FOREIGN KEY (member_id) REFERENCES members(id) ON DELETE SET NULL
    )";
    $pdo->exec($createTable);

    // Insert transaction
    $stmt = $pdo->prepare("INSERT INTO transactions (type, amount, description, member_id, category, created_by) VALUES (?, ?, ?, ?, ?, ?)");
    $result = $stmt->execute([$type, $amount, $description, $member_id ?: null, $category, $_SESSION['user_id'] ?? 1]);

    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Transaction added successfully',
            'id' => $pdo->lastInsertId()
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add transaction']);
    }

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