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

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

$token = get_auth_token();

if (!$token) {
    http_response_code(401);
    echo json_encode(['error' => 'unauthorized']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];

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

    switch ($action) {
        case 'my':
            $res = supabase_rest('GET', 'org_members?select=*,org:organizations(*)&order=joined_at.desc', [], $token);
            $orgs = [];
            if ($res['status'] === 200 && is_array($res['data'])) {
                foreach ($res['data'] as $row) {
                    if (isset($row['org'])) {
                        $orgs[] = $row['org'];
                    }
                }
            }
            echo json_encode(['orgs' => $orgs]);
            break;

        case 'browse':
            $res = supabase_rest('GET', 'organizations?select=*&order=members_count.desc&limit=20', [], $token);
            echo json_encode(['orgs' => $res['data'] ?? []]);
            break;

        case 'search':
            $q = $_GET['q'] ?? '';
            if (strlen($q) < 2) {
                echo json_encode(['orgs' => []]);
                break;
            }
            $res = supabase_rest('GET', 'organizations?select=*&name=ilike.*' . urlencode($q) . '*&limit=10', [], $token);
            echo json_encode(['orgs' => $res['data'] ?? []]);
            break;

        case 'detail':
            $id = $_GET['id'] ?? '';
            $orgRes = supabase_rest('GET', "organizations?id=eq.{$id}&select=*", [], $token);
            $org = (!empty($orgRes['data'])) ? $orgRes['data'][0] : null;

            $membersRes = supabase_rest('GET', "org_members?org_id=eq.{$id}&select=*,profile:profiles(username,display_name,elo_blitz)&order=joined_at.asc", [], $token);
            $members = [];
            $isMember = false;
            if ($membersRes['status'] === 200 && is_array($membersRes['data'])) {
                foreach ($membersRes['data'] as $row) {
                    $member = $row['profile'] ?? [];
                    $member['role'] = $row['role'] ?? 'member';
                    $members[] = $member;
                    // is_member check handled client-side
                }
            }

            echo json_encode(['org' => $org, 'members' => $members, 'is_member' => $isMember]);
            break;
    }
} elseif ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $action = $input['action'] ?? '';

    switch ($action) {
        case 'create':
            $name = $input['name'] ?? '';
            $description = $input['description'] ?? '';

            $res = supabase_rest('POST', 'organizations', [
                'name' => $name,
                'description' => $description,
                'members_count' => 1
            ], $token);

            if ($res['status'] >= 200 && $res['status'] < 300 && !empty($res['data'])) {
                $orgId = $res['data'][0]['id'];
                supabase_rest('POST', 'org_members', [
                    'org_id' => $orgId,
                    'role' => 'owner'
                ], $token);
                echo json_encode(['ok' => true, 'org_id' => $orgId]);
            } else {
                http_response_code(400);
                echo json_encode(['error' => 'could not create org']);
            }
            break;

        case 'join':
            $orgId = $input['org_id'] ?? '';
            supabase_rest('POST', 'org_members', [
                'org_id' => $orgId,
                'role' => 'member'
            ], $token);
            echo json_encode(['ok' => true]);
            break;

        case 'leave':
            $orgId = $input['org_id'] ?? '';
            supabase_rest('DELETE', "org_members?org_id=eq.{$orgId}", [], $token);
            echo json_encode(['ok' => true]);
            break;

        default:
            echo json_encode(['error' => 'invalid action']);
    }
}
