<?php

header('Content-Type: application/json');
require_once __DIR__ . '/../includes/cors.php';

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once __DIR__ . '/../includes/supabase.php';
require_once __DIR__ . '/../includes/auth.php';

$method = $_SERVER['REQUEST_METHOD'];
$db = supabaseService();

if ($method === 'GET') {
    $action = $_GET['action'] ?? 'list';

    if ($action === 'list') {
        $orgs = $db->get('el3ab_organizations', [
            'select' => 'id,name,name_ar,logo_url,banner_url,description,member_count,game_focus,country,is_active',
            'is_active' => 'eq.true',
            'order' => 'member_count.desc',
            'limit' => 30
        ]);
        jsonResponse(['organizations' => is_array($orgs) && !isset($orgs['error']) ? $orgs : []]);
    }

    if ($action === 'detail') {
        $id = $_GET['id'] ?? '';
        if (!$id) jsonError('id required');
        $org = $db->getOne('el3ab_organizations', ['id' => 'eq.' . $id]);
        if (!$org || isset($org['error'])) jsonError('Not found', 404);

        $members = $db->get('org_members', ['org_id' => 'eq.' . $id, 'select' => 'user_id,role,joined_at', 'limit' => 50]);
        $org['members'] = is_array($members) && !isset($members['error']) ? $members : [];
        jsonResponse($org);
    }

    if ($action === 'my-org') {
        $token = requireAuth();
        $userId = getUserId($token);
        $membership = $db->getOne('org_members', ['user_id' => 'eq.' . $userId, 'select' => 'org_id,role']);
        if ($membership && !isset($membership['error'])) {
            $org = $db->getOne('el3ab_organizations', ['id' => 'eq.' . $membership['org_id']]);
            jsonResponse(['org' => $org, 'role' => $membership['role']]);
        }
        jsonResponse(['org' => null]);
    }
}

if ($method === 'POST') {
    $token = requireAuth();
    $userId = getUserId($token);
    $input = getInput();
    $action = $input['action'] ?? '';

    if ($action === 'join') {
        $orgId = $input['org_id'] ?? '';
        if (!$orgId) jsonError('org_id required');

        $existing = $db->get('org_members', ['user_id' => 'eq.' . $userId, 'org_id' => 'eq.' . $orgId, 'select' => 'id']);
        if (!empty($existing) && !isset($existing['error'])) jsonError('Already a member');

        $db->insert('org_members', ['user_id' => $userId, 'org_id' => $orgId, 'role' => 'member']);
        jsonResponse(['success' => true]);
    }

    if ($action === 'leave') {
        $orgId = $input['org_id'] ?? '';
        if (!$orgId) jsonError('org_id required');
        $db->delete('org_members', ['user_id' => 'eq.' . $userId, 'org_id' => 'eq.' . $orgId]);
        jsonResponse(['success' => true]);
    }
}

jsonError('Invalid request');
