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

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

// Ensure only authenticated admin users can add registrations
if (!isAuthenticated() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

try {
    $pdo = getDBConnection();
    
    // Validate input
    $requiredFields = ['event_id', 'member_id'];
    $missingFields = [];
    
    foreach ($requiredFields as $field) {
        if (empty($_POST[$field])) {
            $missingFields[] = $field;
        }
    }
    
    if (!empty($missingFields)) {
        echo json_encode([
            'success' => false, 
            'message' => 'Missing required fields: ' . implode(', ', $missingFields)
        ]);
        exit;
    }
    
    $eventId = (int)$_POST['event_id'];
    $memberId = (int)$_POST['member_id'];
    $paymentStatus = $_POST['payment_status'] ?? 'pending';
    $amountPaid = !empty($_POST['amount_paid']) ? (float)$_POST['amount_paid'] : 0.00;
    $status = $_POST['status'] ?? 'confirmed';
    $notes = $_POST['notes'] ?? '';
    
    // Check if event exists
    $stmt = $pdo->prepare("SELECT id, registration_fee FROM events WHERE id = :id");
    $stmt->execute([':id' => $eventId]);
    $event = $stmt->fetch();
    
    if (!$event) {
        echo json_encode(['success' => false, 'message' => 'Event not found']);
        exit;
    }
    
    // Check if member exists
    $stmt = $pdo->prepare("SELECT id FROM members WHERE id = :id");
    $stmt->execute([':id' => $memberId]);
    
    if ($stmt->rowCount() == 0) {
        echo json_encode(['success' => false, 'message' => 'Member not found']);
        exit;
    }
    
    // Check if member is already registered for this event
    try {
        // First check if table exists
        $stmt = $pdo->query("SHOW TABLES LIKE 'event_registrations'");
        
        if ($stmt->rowCount() > 0) {
            $stmt = $pdo->prepare("
                SELECT id FROM event_registrations 
                WHERE event_id = :event_id AND member_id = :member_id
            ");
            $stmt->execute([':event_id' => $eventId, ':member_id' => $memberId]);
            
            if ($stmt->rowCount() > 0) {
                echo json_encode([
                    'success' => false, 
                    'message' => 'This member is already registered for this event'
                ]);
                exit;
            }
        } else {
            // Create event_registrations table if it doesn't exist
            $pdo->exec("
                CREATE TABLE event_registrations (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    event_id INT NOT NULL,
                    member_id INT NOT NULL,
                    registration_date DATETIME NOT NULL,
                    payment_status ENUM('pending', 'completed', 'waived', 'failed') NOT NULL DEFAULT 'pending',
                    amount_paid DECIMAL(10,2) NOT NULL DEFAULT 0.00,
                    status ENUM('confirmed', 'pending', 'cancelled') NOT NULL DEFAULT 'pending',
                    notes TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
                    UNIQUE KEY uk_event_member (event_id, member_id),
                    FOREIGN KEY (event_id) REFERENCES events(id) ON DELETE CASCADE,
                    FOREIGN KEY (member_id) REFERENCES members(id) ON DELETE CASCADE
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
            ");
        }
    } catch (Exception $e) {
        // If there's an error checking/creating the table, log it but continue
        error_log('Error with event_registrations table: ' . $e->getMessage());
    }
    
    // Add registration
    $stmt = $pdo->prepare("
        INSERT INTO event_registrations (
            event_id,
            member_id,
            registration_date,
            payment_status,
            amount_paid,
            status,
            notes
        ) VALUES (
            :event_id,
            :member_id,
            NOW(),
            :payment_status,
            :amount_paid,
            :status,
            :notes
        )
    ");
    
    $stmt->execute([
        ':event_id' => $eventId,
        ':member_id' => $memberId,
        ':payment_status' => $paymentStatus,
        ':amount_paid' => $amountPaid,
        ':status' => $status,
        ':notes' => $notes
    ]);
    
    $registrationId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true, 
        'message' => 'Registration added successfully',
        'registration_id' => $registrationId
    ]);
    
} catch (PDOException $e) {
    error_log('Error adding event registration: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
} catch (Exception $e) {
    error_log('General error adding registration: ' . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
