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

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

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

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

try {
    $pdo = getDBConnection();
    
    // Generate auto KSO ID
    try {
        $pdo->query("INSERT INTO kso_id_sequence () VALUES ()");
        $sequence_id = $pdo->lastInsertId();
    } catch (Exception $e) {
        // If kso_id_sequence table doesn't exist, create it
        $pdo->exec("CREATE TABLE IF NOT EXISTS `kso_id_sequence` (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `created_at` timestamp DEFAULT current_timestamp(),
          PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");
        
        // Insert initial record and get ID
        $pdo->query("INSERT INTO kso_id_sequence () VALUES ()");
        $sequence_id = $pdo->lastInsertId();
    }
    
    $kso_id = 'KSOCHD' . str_pad($sequence_id, 3, '0', STR_PAD_LEFT);
    
    // Default password hash
    $default_password = password_hash('password123', PASSWORD_DEFAULT);
    
    $stmt = $pdo->prepare("
        INSERT INTO members (
            kso_id, first_name, last_name, email, password_hash, phone, 
            date_of_birth, gender, college, course, membership_type, 
            blood_group, status, created_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
    ");
    
    $result = $stmt->execute([
        $kso_id,
        $_POST['first_name'],
        $_POST['last_name'],
        $_POST['email'],
        $default_password,
        $_POST['phone'] ?? null,
        $_POST['date_of_birth'] ?? null,
        $_POST['gender'] ?? null,
        $_POST['college'],
        $_POST['course'],
        $_POST['membership_type'],
        $_POST['blood_group'] ?? null
    ]);
    
    if ($result) {
        $member_id = $pdo->lastInsertId();
        
        // Log activity
        $admin_id = $_SESSION['admin_id'] ?? 1;
        $pdo->prepare("
            INSERT INTO activity_logs (user_id, action, details, ip_address, created_at) 
            VALUES (?, 'member_added', ?, ?, NOW())
        ")->execute([$admin_id, "Added new member: {$_POST['first_name']} {$_POST['last_name']}", $_SERVER['REMOTE_ADDR']]);
        
        echo json_encode([
            'success' => true, 
            'message' => 'Member added successfully',
            'member_id' => $member_id,
            'kso_id' => $kso_id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to add member']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
