<?php
/**
 * PAKClub Admin Panel - API Endpoint
 * Returns app information based on package name
 * 
 * Usage: GET/POST /endpoint/app.php?pkg=com.example.app
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key');
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');

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

require_once __DIR__ . '/../config.php';

// ── Rate Limiting (simple IP-based) ──
$clientIP = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
$rateLimit = (int) getSetting('api_rate_limit', 100);

// ── Check maintenance mode ──
$maintenanceMode = getSetting('maintenance_mode', '0');
if ($maintenanceMode === '1') {
    $msg = getSetting('maintenance_message', 'Service temporarily unavailable.');
    http_response_code(503);
    echo json_encode([
        'status' => 'error',
        'code' => 503,
        'message' => $msg
    ]);
    exit;
}

// ── Get package name and optional audio_class ──
$pkgName = '';
$audioClass = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);
    $pkgName = $input['pkg'] ?? $input['pkg_name'] ?? $input['package'] ?? $_POST['pkg'] ?? $_POST['pkg_name'] ?? '';
    $audioClass = $input['audio_class'] ?? $_POST['audio_class'] ?? '';
} else {
    $pkgName = $_GET['pkg'] ?? $_GET['pkg_name'] ?? $_GET['package'] ?? '';
    $audioClass = $_GET['audio_class'] ?? '';
}

$pkgName = trim($pkgName);
$audioClass = trim($audioClass);

// If only audio_class is requested (no pkg needed for global audios)
if (empty($pkgName) && !empty($audioClass)) {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT class_name, audio_title, audio_file FROM audios WHERE class_name = ? AND is_active = 1 AND app_id IS NULL LIMIT 1");
        $stmt->execute([$audioClass]);
        $audio = $stmt->fetch();
        if ($audio) {
            $audioUrl = filter_var($audio['audio_file'], FILTER_VALIDATE_URL) ? $audio['audio_file'] : getAudioBaseUrl() . $audio['audio_file'];
            $db->prepare("UPDATE audios SET play_count = play_count + 1 WHERE class_name = ? AND app_id IS NULL")->execute([$audioClass]);
            echo json_encode(['status' => 'success', 'code' => 200, 'data' => ['class_name' => $audio['class_name'], 'title' => $audio['audio_title'], 'audio_url' => $audioUrl]]);
        } else {
            echo json_encode(['status' => 'error', 'code' => 404, 'message' => 'Audio not found for class: ' . $audioClass]);
        }
    } catch (Exception $e) {
        echo json_encode(['status' => 'error', 'code' => 500, 'message' => 'Server error']);
    }
    exit;
}

if (empty($pkgName)) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'code' => 400,
        'message' => 'Package name is required. Use ?pkg=com.example.app or ?audio_class=login_audio'
    ]);
    exit;
}

// ── Check if device is blocked ──
$deviceId = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = $input ?? json_decode(file_get_contents('php://input'), true);
    $deviceId = $input['device_id'] ?? $_POST['device_id'] ?? '';
}
if (!empty($deviceId)) {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT id, reason FROM blocked_devices WHERE device_id = ?");
        $stmt->execute([$deviceId]);
        $blocked = $stmt->fetch();
        if ($blocked) {
            http_response_code(403);
            echo json_encode([
                'status' => 'error',
                'code' => 403,
                'message' => 'Device is blocked',
                'reason' => $blocked['reason'] ?? 'Violation of terms'
            ]);
            exit;
        }
    } catch (Exception $e) {
        // Continue silently
    }
}

try {
    $db = getDB();
    
    // ── Fetch app data ──
    $stmt = $db->prepare("SELECT * FROM apps WHERE pkg_name = ? LIMIT 1");
    $stmt->execute([$pkgName]);
    $app = $stmt->fetch();
    
    if (!$app) {
        http_response_code(404);
        echo json_encode([
            'status' => 'error',
            'code' => 404,
            'message' => 'App not found for package: ' . $pkgName
        ]);
        exit;
    }
    
    // ── Update API call stats ──
    $updateStmt = $db->prepare("UPDATE apps SET api_calls = api_calls + 1, last_api_call = NOW() WHERE id = ?");
    $updateStmt->execute([$app['id']]);
    
    // ── Build logo URL ──
    $logoUrl = '';
    if (!empty($app['app_logo'])) {
        if (filter_var($app['app_logo'], FILTER_VALIDATE_URL)) {
            $logoUrl = $app['app_logo'];
        } else {
            $logoUrl = getUploadBaseUrl() . $app['app_logo'];
        }
    }
    
    // ── Build full refer link ──
    $referLink = '';
    if (!empty($app['refer_link'])) {
        $referLink = buildReferLink($app['refer_link'], $app['app_domain'] ?? '');
    }
    
    // ── Parse custom data ──
    $customData = null;
    if (!empty($app['custom_data'])) {
        $customData = json_decode($app['custom_data'], true);
    }
    
    // ── Build response ──
    $response = [
        'status' => 'success',
        'code' => 200,
        'data' => [
            'app_name' => $app['app_name'],
            'pkg_name' => $app['pkg_name'],
            'whatsapp_link' => $app['whatsapp_link'] ?? '',
            'refer_link' => $referLink,
            'app_logo' => $logoUrl,
            'app_version' => $app['app_version'] ?? '1.0.0',
            'app_status' => $app['app_status'] ?? 'active',
            'min_version' => $app['min_version'] ?? '1.0.0',
            'force_update' => (bool)($app['force_update'] ?? false),
            'update_url' => $app['update_url'] ?? '',
            'description' => $app['app_description'] ?? '',
            
            // Notification
            'notification' => [
                'title' => $app['notification_title'] ?? '',
                'body' => $app['notification_body'] ?? '',
                'image' => $app['notification_image'] ?? '',
                'url' => $app['notification_url'] ?? ''
            ],
            
            // Popup
            'popup' => [
                'enabled' => (bool)($app['popup_enabled'] ?? false),
                'title' => $app['popup_title'] ?? '',
                'message' => $app['popup_message'] ?? '',
                'button_text' => $app['popup_button_text'] ?? 'OK',
                'button_url' => $app['popup_button_url'] ?? '',
                'image' => $app['popup_image'] ?? ''
            ],
            
            // Ads
            'ads' => [
                'enabled' => (bool)($app['ads_enabled'] ?? false),
                'network' => $app['ad_network'] ?? 'none',
                'interstitial_id' => $app['interstitial_ad_id'] ?? '',
                'banner_id' => $app['banner_ad_id'] ?? '',
                'rewarded_id' => $app['rewarded_ad_id'] ?? '',
                'native_id' => $app['native_ad_id'] ?? ''
            ],
            
            // Custom data
            'custom_data' => $customData,
            
            // Global settings
            'whatsapp_support' => getSetting('whatsapp_support', ''),
        ],
        'timestamp' => time()
    ];

    // ── Fetch audios for this app ──
    $audioStmt = $db->prepare("SELECT class_name, audio_title, audio_file FROM audios WHERE (app_id = ? OR app_id IS NULL) AND is_active = 1 ORDER BY class_name");
    $audioStmt->execute([$app['id']]);
    $audios = $audioStmt->fetchAll();
    $audioMap = [];
    foreach ($audios as $aud) {
        $aUrl = filter_var($aud['audio_file'], FILTER_VALIDATE_URL) ? $aud['audio_file'] : getAudioBaseUrl() . $aud['audio_file'];
        $audioMap[$aud['class_name']] = ['title' => $aud['audio_title'], 'url' => $aUrl];
    }
    $response['data']['audios'] = $audioMap;

    // ── If specific audio_class requested, include it at top level ──
    if (!empty($audioClass)) {
        if (isset($audioMap[$audioClass])) {
            $response['data']['requested_audio'] = $audioMap[$audioClass];
            $db->prepare("UPDATE audios SET play_count = play_count + 1 WHERE class_name = ? AND (app_id = ? OR app_id IS NULL)")->execute([$audioClass, $app['id']]);
        } else {
            $response['data']['requested_audio'] = null;
        }
    }
    
    // ── Log this API call ──
    try {
        $logStmt = $db->prepare("INSERT INTO admin_logs (action, details, ip_address, user_agent) VALUES ('api_call', ?, ?, ?)");
        $logStmt->execute([
            "App: {$app['app_name']} ({$pkgName})",
            $clientIP,
            $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
        ]);
    } catch (Exception $e) {
        // Silent fail for logging
    }
    
    echo json_encode($response, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'code' => 500,
        'message' => 'Internal server error'
    ]);
}
