<?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';

$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);
    $sdb = supabaseService();

    // If viewing another player's profile, check blocks
    if ($targetId !== $userId) {
        $blocked = $sdb->get('player_blocks', [
            'player_id' => 'eq.' . $targetId,
            'blocked_id' => 'eq.' . $userId,
            'type' => 'eq.block',
            'limit' => 1
        ]);
        if (is_array($blocked) && !isset($blocked['error']) && !empty($blocked)) {
            jsonError('Profile not available', 403);
        }
    }

    $profiles = $db->get('profiles', ['id' => 'eq.' . $targetId, 'select' => '*', 'limit' => 1]);

    if (!is_array($profiles) || isset($profiles['error']) || empty($profiles)) {
        // Auto-create profile for own user (covers Google sign-in, guest-upgrade)
        if ($targetId === $userId) {
            $user = verifyToken($token);
            $meta = $user['user_metadata'] ?? [];
            $name = $meta['display_name'] ?? $meta['full_name'] ?? $meta['name'] ?? explode('@', $user['email'] ?? '')[0] ?? 'Player';
            $sdb->insert('profiles', [
                'id' => $userId,
                'display_name' => $name,
                'username' => $name,
                'avatar_url' => $meta['avatar_url'] ?? $meta['picture'] ?? null,
                'coins' => 0,
                'gems' => 0,
                'xp' => 0,
                'level' => 1,
                'daily_streak' => 0,
            ]);
            $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 : [];

    // Add relationship info when viewing another player
    if ($targetId !== $userId) {
        // Friendship status
        $friendship = $sdb->get('friendships', [
            'or' => "(and(requester_id.eq.{$userId},addressee_id.eq.{$targetId}),and(requester_id.eq.{$targetId},addressee_id.eq.{$userId}))",
            'select' => 'id,requester_id,addressee_id,status',
            'limit' => 1
        ]);
        if (is_array($friendship) && !isset($friendship['error']) && !empty($friendship)) {
            $f = $friendship[0];
            $profile['friendship_status'] = $f['status'];
            $profile['friendship_is_mine'] = ($f['requester_id'] === $userId);
        } else {
            $profile['friendship_status'] = 'none';
            $profile['friendship_is_mine'] = false;
        }

        // Check if current user has blocked/muted this player
        $myBlock = $sdb->get('player_blocks', [
            'player_id' => 'eq.' . $userId,
            'blocked_id' => 'eq.' . $targetId,
            'limit' => 1
        ]);
        if (is_array($myBlock) && !isset($myBlock['error']) && !empty($myBlock)) {
            $profile['block_status'] = $myBlock[0]['type'];
        } else {
            $profile['block_status'] = 'none';
        }

        // Strip private fields for other players
        unset($profile['email']);
    }

    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 === 'ensure') {
        // Create or update profile from auth user_metadata (called after OAuth login)
        $sdb = supabaseService();
        $user = verifyToken($token);
        $meta = $user['user_metadata'] ?? [];
        $name = $meta['full_name'] ?? $meta['name'] ?? $meta['display_name'] ?? $meta['username'] ?? explode('@', $user['email'] ?? '')[0] ?? 'Player';
        $avatar = $meta['avatar_url'] ?? $meta['picture'] ?? null;

        $existing = $sdb->get('profiles', ['id' => 'eq.' . $userId, 'select' => 'id,display_name,avatar_url', 'limit' => 1]);
        if (is_array($existing) && !isset($existing['error']) && !empty($existing)) {
            // Profile exists — update if fields are empty/default
            $updates = [];
            $current = $existing[0];
            if (!$current['display_name'] || $current['display_name'] === 'Player' || str_ends_with($current['display_name'], '_' . substr($userId, 0, 4))) {
                $updates['display_name'] = $name;
                $updates['username'] = $meta['username'] ?? $name;
            }
            if (!$current['avatar_url'] && $avatar) {
                $updates['avatar_url'] = $avatar;
            }
            if (!empty($updates)) {
                $sdb->update('profiles', $updates, ['id' => 'eq.' . $userId]);
            }
        } else {
            // Create new profile
            $sdb->insert('profiles', [
                'id' => $userId,
                'display_name' => $name,
                'username' => $meta['username'] ?? $name,
                'avatar_url' => $avatar,
                'coins' => 0,
                'gems' => 0,
                'xp' => 0,
                'level' => 1,
                'daily_streak' => 0,
            ]);
        }

        // Fetch and return the full profile
        $db = supabase($token);
        $profiles = $db->get('profiles', ['id' => 'eq.' . $userId, 'select' => '*', 'limit' => 1]);
        $profile = is_array($profiles) && !empty($profiles) && !isset($profiles['error']) ? $profiles[0] : null;
        jsonResponse($profile ?? ['id' => $userId, 'display_name' => $name]);
    }

    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 = supabaseService();
        $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 = supabaseService();
        $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);
