<?php

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

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

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

$token = requireAuth();
$userId = getUserId($token);
if (!$userId) jsonError('Invalid user', 401);

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $targetId = $_GET['id'] ?? $userId;
    $db = supabase($token);
    $profiles = $db->get('profiles', ['id' => 'eq.' . $targetId, 'select' => '*', 'limit' => 1]);

    if (!is_array($profiles) || isset($profiles['error']) || empty($profiles)) {
        jsonError('Profile not found', 404);
    }

    $profile = $profiles[0];
    $ratings = $db->get('player_game_ratings', ['player_id' => 'eq.' . $targetId, 'select' => 'game_key,time_control,rating,games_played,wins,losses,draws']);

    $profile['ratings'] = is_array($ratings) && !isset($ratings['error']) ? $ratings : [];

    jsonResponse($profile);
}

if ($method === 'PATCH') {
    $input = getInput();
    $allowed = [
        'display_name', 'display_name_ar', 'avatar_url', 'frame_id', 'border_color',
        'bio', 'bio_ar', 'country_code', 'city', 'preferred_language',
        'fide_id', 'fide_rating_standard', 'fide_rating_rapid', 'fide_rating_blitz', 'fide_title'
    ];
    $data = array_intersect_key($input, array_flip($allowed));

    if (empty($data)) jsonError('No valid fields to update');

    // Validate fide_title if provided
    if (isset($data['fide_title']) && $data['fide_title'] !== null && $data['fide_title'] !== '') {
        $validTitles = ['GM', 'IM', 'FM', 'CM', 'WGM', 'WIM', 'WFM', 'WCM'];
        if (!in_array($data['fide_title'], $validTitles)) {
            jsonError('Invalid FIDE title');
        }
    }

    // Validate numeric fields
    $numericFields = ['fide_rating_standard', 'fide_rating_rapid', 'fide_rating_blitz'];
    foreach ($numericFields as $field) {
        if (isset($data[$field]) && $data[$field] !== null && $data[$field] !== '') {
            $data[$field] = (int)$data[$field];
            if ($data[$field] < 0 || $data[$field] > 4000) {
                jsonError("Invalid $field value");
            }
        }
    }

    // Validate preferred_language
    if (isset($data['preferred_language']) && !in_array($data['preferred_language'], ['ar', 'en'])) {
        jsonError('Invalid preferred_language');
    }

    $db = supabase($token);
    $result = $db->update('profiles', $data, ['id' => 'eq.' . $userId]);

    if (isset($result['error'])) {
        jsonError($result['error']);
    }

    jsonResponse($result[0] ?? ['success' => true]);
}

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

    if ($action === 'get-orgs') {
        $db = supabaseService();
        $orgs = $db->get('organizations', ['select' => 'id,name,slug,logo_url,country_code', 'order' => 'name.asc']);
        if (isset($orgs['error'])) jsonError($orgs['error']);
        jsonResponse($orgs);
    }

    if ($action === 'my-memberships') {
        $db = supabase($token);
        $memberships = $db->get('org_memberships', [
            'user_id' => 'eq.' . $userId,
            'select' => 'id,organization_id,role,status,joined_at,organizations(id,name,slug,logo_url)'
        ]);
        if (isset($memberships['error'])) jsonError($memberships['error']);
        jsonResponse(is_array($memberships) ? $memberships : []);
    }

    if ($action === 'my-applications') {
        $db = supabase($token);
        $apps = $db->get('org_membership_applications', [
            'player_id' => 'eq.' . $userId,
            'select' => 'id,org_id,status,document_type,notes,rejection_reason,created_at,organizations(id,name,slug,logo_url)',
            'order' => 'created_at.desc',
            'limit' => 50
        ]);
        if (isset($apps['error'])) jsonError($apps['error']);
        jsonResponse(is_array($apps) ? $apps : []);
    }

    if ($action === 'apply-org') {
        $orgId = $input['org_id'] ?? null;
        $documentType = $input['document_type'] ?? null;
        $notes = $input['notes'] ?? '';
        $documentUrl = $input['document_url'] ?? null;

        if (!$orgId || !$documentType) {
            jsonError('org_id and document_type are required');
        }

        // Check if already a member
        $db = supabase($token);
        $existing = $db->get('org_memberships', [
            'user_id' => 'eq.' . $userId,
            'organization_id' => 'eq.' . $orgId,
            'status' => 'eq.active',
            'limit' => 1
        ]);
        if (is_array($existing) && !isset($existing['error']) && !empty($existing)) {
            jsonError('Already a member of this organization');
        }

        // Check if pending application exists
        $pending = $db->get('org_membership_applications', [
            'player_id' => 'eq.' . $userId,
            'org_id' => 'eq.' . $orgId,
            'status' => 'eq.pending',
            'limit' => 1
        ]);
        if (is_array($pending) && !isset($pending['error']) && !empty($pending)) {
            jsonError('You already have a pending application for this organization');
        }

        $appData = [
            'org_id' => $orgId,
            'player_id' => $userId,
            'status' => 'pending',
            'document_type' => $documentType,
            'notes' => $notes
        ];
        if ($documentUrl) {
            $appData['document_url'] = $documentUrl;
        }

        $dbService = supabaseService();
        $result = $dbService->insert('org_membership_applications', $appData);
        if (isset($result['error'])) jsonError($result['error']);

        jsonResponse($result[0] ?? ['success' => true]);
    }

    jsonError('Invalid action');
}

jsonError('Method not allowed', 405);
