<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'live_call_common.php';

try {
    $pdo = getDBConnection();
    $settings = liveCallSettings($pdo);

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = liveCallReadInput();
        $action = $input['action'] ?? '';

        if ($action === 'save_settings') {
            $allowed = [
                'live_call_system_enabled',
                'guru_online',
                'live_call_audio_enabled',
                'live_call_video_enabled',
                'live_call_min_first_call_balance',
                'live_call_min_wallet_balance',
                'live_call_audio_rate_per_minute',
                'live_call_video_rate_per_minute',
                'live_call_agora_app_id',
                'live_call_agora_app_certificate',
                'live_call_tick_seconds',
                'onesignal_app_id',
                'onesignal_rest_api_key'
            ];
            $oldOnline = liveCallBool($settings['guru_online'] ?? 'off');
            foreach ($allowed as $key) {
                if (array_key_exists($key, $input)) {
                    if (in_array($key, ['onesignal_rest_api_key', 'live_call_agora_app_certificate'], true)
                        && trim((string)$input[$key]) === '') {
                        continue;
                    }
                    liveCallSaveSetting($pdo, $key, (string)$input[$key]);
                }
            }
            $newOnline = liveCallBool($input['guru_online'] ?? ($settings['guru_online'] ?? 'off'));
            $systemEnabled = liveCallBool($input['live_call_system_enabled'] ?? ($settings['live_call_system_enabled'] ?? 'off'));
            $pushResult = null;
            if (!$oldOnline && $newOnline && $systemEnabled) {
                $pushResult = liveCallNotifyGuruOnline($pdo);
            }
            liveCallJson(['success' => true, 'message' => 'Live call settings saved', 'push' => $pushResult]);
        }

        if ($action === 'set_guru_status') {
            $status = liveCallBool($input['guru_online'] ?? 'off') ? 'on' : 'off';
            $systemEnabled = liveCallBool($input['live_call_system_enabled'] ?? ($settings['live_call_system_enabled'] ?? 'on'));
            liveCallSaveSetting($pdo, 'live_call_system_enabled', $systemEnabled ? 'on' : 'off');
            liveCallSaveSetting($pdo, 'guru_online', $status);
            $pushResult = null;
            if ($status === 'on' && $systemEnabled) {
                $pushResult = liveCallNotifyGuruOnline($pdo);
            }
            liveCallJson(['success' => true, 'message' => $status === 'on' ? 'Guruji online ho gaye' : 'Guruji offline ho gaye', 'push' => $pushResult]);
        }

        if ($action === 'send_test_push') {
            $pushResult = liveCallNotifyGuruOnline($pdo);
            $ok = !empty($pushResult['onesignal_sent']);
            liveCallJson([
                'success' => $ok,
                'message' => $ok ? 'Test push OneSignal ko send ho gaya' : 'Test push fail hua: ' . ($pushResult['onesignal_error'] ?: 'OneSignal response check karo'),
                'push' => $pushResult
            ], $ok ? 200 : 400);
        }

        if ($action === 'accept') {
            $sessionId = (int)($input['session_id'] ?? 0);
            if ($sessionId <= 0) {
                throw new Exception('Valid session_id required');
            }
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET status = 'active', accepted_at = NOW(), started_at = COALESCE(started_at, NOW()), last_heartbeat_at = NOW()
                WHERE id = ? AND status IN ('requested','ringing','active')
            ");
            $stmt->execute([$sessionId]);
            $session = liveCallSessionById($pdo, $sessionId);
            if (!$session) {
                throw new Exception('Call session not found');
            }
            liveCallJson(['success' => true, 'message' => 'Call accepted', 'session_status' => $session['status']]);
        }

        if ($action === 'reject') {
            $sessionId = (int)($input['session_id'] ?? 0);
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET status = 'rejected', ended_at = NOW(), end_reason = 'Rejected by Guruji'
                WHERE id = ? AND status IN ('requested','ringing')
            ");
            $stmt->execute([$sessionId]);
            liveCallJson(['success' => true, 'message' => 'Call rejected']);
        }

        if ($action === 'extend') {
            $sessionId = (int)($input['session_id'] ?? 0);
            $seconds = max(30, (int)($input['seconds'] ?? 60));
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET admin_extension_seconds = admin_extension_seconds + ?
                WHERE id = ? AND status IN ('ringing','active')
            ");
            $stmt->execute([$seconds, $sessionId]);
            liveCallJson(['success' => true, 'message' => 'Call extended', 'seconds' => $seconds]);
        }

        throw new Exception('Unknown action');
    }

    $active = liveCallActiveSession($pdo);
    if ($active) {
        $active['balance'] = liveCallBalance($pdo, (int)$active['user_id']);
        $active['guru_agora_token'] = liveCallAgoraToken($settings, (string)$active['channel_name'], (int)$active['guru_uid']);
        $active['agora_token_required'] = trim((string)($settings['live_call_agora_app_certificate'] ?? '')) !== '';
        $active['agora_token_ready'] = !empty($active['guru_agora_token']);
    }
    $queueStmt = $pdo->query("
        SELECT q.*, u.name AS user_name, u.mobile AS user_mobile
        FROM live_call_queue q
        LEFT JOIN users u ON u.id = q.user_id
        WHERE q.status = 'waiting'
        ORDER BY q.created_at ASC
    ");

    $notificationCount = 0;
    $pendingPushCount = 0;
    $deviceTokenCount = 0;
    try {
        $deviceTokenCount = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE device_token IS NOT NULL AND device_token != ''")->fetchColumn();
        $pdo->exec("
            CREATE TABLE IF NOT EXISTS push_notifications (
                id INT AUTO_INCREMENT PRIMARY KEY,
                user_id INT NULL,
                title VARCHAR(255) NOT NULL,
                body TEXT NOT NULL,
                device_token VARCHAR(500) NULL,
                status VARCHAR(50) DEFAULT 'sent',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ");
        $notificationCount = (int)$pdo->query("SELECT COUNT(*) FROM push_notifications")->fetchColumn();
        $pendingPushCount = (int)$pdo->query("SELECT COUNT(*) FROM push_notifications WHERE status = 'pending'")->fetchColumn();
    } catch (Exception $e) {}

    $clientSettings = $settings;
    $clientSettings['onesignal_rest_api_key'] = '';
    $clientSettings['live_call_agora_app_certificate'] = '';

    liveCallJson([
        'success' => true,
        'settings' => $clientSettings,
        'active_session' => $active,
        'queue' => $queueStmt->fetchAll(PDO::FETCH_ASSOC),
        'diagnostics' => [
            'system_ready' => liveCallBool($settings['live_call_system_enabled'] ?? 'off') && liveCallBool($settings['guru_online'] ?? 'off'),
            'agora_configured' => trim($settings['live_call_agora_app_id'] ?? '') !== '',
            'onesignal_app_configured' => trim($settings['onesignal_app_id'] ?? '') !== '',
            'onesignal_key_configured' => trim($settings['onesignal_rest_api_key'] ?? '') !== '',
            'device_token_count' => $deviceTokenCount,
            'notification_count' => $notificationCount,
            'pending_push_count' => $pendingPushCount
        ]
    ]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
