<?php
/**
 * Admin tutorials management - service aware
 */
require_once 'config.php';

$input = json_decode(file_get_contents('php://input'), true) ?: $_GET;
$userId = miniapp_require_admin();

function normalizeServiceType($s): string {  $s=strtolower(trim((string)$s)); return in_array($s, ['windscribe','expressvpn','v2ray','openvpn_l2tp'], true) ? $s : 'openvpn_l2tp'; }
function getDeviceLabel(string $device): string { return ['ANDROID'=>'اندروید','IPHONE'=>'آیفون','WINDOWS'=>'ویندوز'][$device] ?? $device; }
function getServiceLabel(string $s): string { $s = normalizeServiceType($s); return $s==='windscribe' ? 'Windscribe' : ($s==='expressvpn' ? 'ExpressVPN' : ($s==='v2ray' ? 'V2Ray' : 'OpenVPN | L2TP')); }

$serviceType = normalizeServiceType($input['service_type'] ?? $_GET['service_type'] ?? 'openvpn_l2tp');

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $pdo->prepare("SELECT * FROM tutorials WHERE service_type = ? ORDER BY FIELD(device, 'ANDROID', 'IPHONE', 'WINDOWS')");
    $stmt->execute([$serviceType]);
    $tutorials = $stmt->fetchAll();
    $devices = ['ANDROID','IPHONE','WINDOWS'];
    $existing = array_column($tutorials, 'device');
    foreach ($devices as $device) {
        if (!in_array($device, $existing, true)) {
            $tutorials[] = ['id'=>null,'service_type'=>$serviceType,'device'=>$device,'text_content'=>'','video_file_id'=>null,'updated_at'=>null];
        }
    }
    usort($tutorials, function($a,$b){ $order=['ANDROID'=>0,'IPHONE'=>1,'WINDOWS'=>2]; return ($order[$a['device']]??9)-($order[$b['device']]??9); });
    echo json_encode(['ok'=>true,'data'=>['service_type'=>$serviceType,'service_label'=>getServiceLabel($serviceType),'tutorials'=>$tutorials]], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $device = strtoupper(trim($input['device'] ?? ''));
    $textContent = trim($input['text_content'] ?? '');
    $videoFileId = trim($input['video_file_id'] ?? '');
    if (!in_array($device, ['ANDROID','IPHONE','WINDOWS'], true)) {
        echo json_encode(['ok'=>false,'error'=>'device باید ANDROID, IPHONE یا WINDOWS باشد'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $stmt = $pdo->prepare("\n        INSERT INTO tutorials (service_type, device, text_content, video_file_id)\n        VALUES (?, ?, ?, ?)\n        ON DUPLICATE KEY UPDATE text_content = VALUES(text_content), video_file_id = VALUES(video_file_id), updated_at = NOW()\n    ");
    $stmt->execute([$serviceType, $device, $textContent ?: null, $videoFileId ?: null]);
    gemaccAdminActionNotify('آموزش سرویس ذخیره شد', ['سرویس'=>getServiceLabel($serviceType), 'دستگاه'=>getDeviceLabel($device), 'دارای ویدیو'=>$videoFileId !== '' ? 'بله' : 'خیر'], $userId);
    echo json_encode(['ok'=>true,'message'=>'آموزش '.getServiceLabel($serviceType).' - '.getDeviceLabel($device).' ذخیره شد'], JSON_UNESCAPED_UNICODE);
}
