<?php

error_reporting(E_ALL);
ini_set('display_errors', 0);

set_exception_handler(function($e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode(['error' => $e->getMessage(), 'line' => $e->getLine()]);
    exit;
});

set_error_handler(function($errno, $errstr, $errfile, $errline) {
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
});

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit; }

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

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

// Validate required fields
$orgId = $_POST['org_id'] ?? null;
$documentType = $_POST['document_type'] ?? null;
$notes = $_POST['notes'] ?? '';

if (!$orgId) jsonError('org_id is required');
if (!$documentType) jsonError('document_type is required');

// Validate document_type
$validTypes = ['membership_card', 'id_card', 'receipt', 'other'];
if (!in_array($documentType, $validTypes)) {
    jsonError('Invalid document_type. Allowed: ' . implode(', ', $validTypes));
}

// Check if already a member
$db = supabaseService();
$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');
}

// Handle file upload
$documentUrl = null;
if (isset($_FILES['proof_document'])) {
    if ($_FILES['proof_document']['error'] !== UPLOAD_ERR_OK) {
        $errors = [1 => 'File exceeds server limit', 2 => 'File exceeds form limit', 3 => 'Partial upload', 4 => 'No file sent', 6 => 'No tmp dir', 7 => 'Write failed'];
        jsonError($errors[$_FILES['proof_document']['error']] ?? 'Upload error code ' . $_FILES['proof_document']['error']);
    }

    $file = $_FILES['proof_document'];
    if ($file['size'] > 5 * 1024 * 1024) {
        jsonError('File too large (max 5MB)');
    }

    $mime = mime_content_type($file['tmp_name']);
    $allowed = ['image/jpeg', 'image/png', 'image/webp'];

    if (!in_array($mime, $allowed)) {
        jsonError('Invalid file type: ' . $mime . '. Allowed: JPEG, PNG, WebP');
    }

    $ext = match($mime) {
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'image/webp' => 'webp',
        default => 'jpg'
    };

    $filename = $userId . '_' . time() . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $storagePath = 'org-proofs/' . $userId . '/' . $filename;
    $bucket = 'assets';

    $storageUrl = SUPABASE_STORAGE . '/object/' . $bucket . '/' . $storagePath;
    $fileContents = file_get_contents($file['tmp_name']);

    if ($fileContents === false) {
        jsonError('Failed to read uploaded file');
    }

    $ch = curl_init($storageUrl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . SUPABASE_SERVICE_KEY,
        'apikey: ' . SUPABASE_SERVICE_KEY,
        'Content-Type: ' . $mime,
        'x-upsert: true'
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fileContents);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        jsonError('Storage connection failed: ' . $curlError, 500);
    }

    if ($httpCode >= 400) {
        $decoded = json_decode($response, true);
        jsonError('Storage error (' . $httpCode . '): ' . ($decoded['message'] ?? $decoded['error'] ?? $response), 500);
    }

    $documentUrl = SUPABASE_STORAGE . '/object/public/' . $bucket . '/' . $storagePath . '?apikey=' . SUPABASE_ANON_KEY;
}

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

$result = $db->insert('org_membership_applications', $appData);
if (isset($result['error'])) {
    jsonError('Failed to submit application: ' . $result['error']);
}

jsonResponse([
    'success' => true,
    'application_id' => $result[0]['id'] ?? null,
    'document_url' => $documentUrl
]);
