<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header("Location: login.php");
    exit;
}

$request_id = intval($_POST['request_id'] ?? 0);

/* =====================================================
   حالت متن به متن (بدون ویدیو)
===================================================== */
if (isset($_POST['text_to_text']) && !empty($_POST['admin_text'])) {

    $admin_text = trim($_POST['admin_text']);

    $stmt = $pdo->prepare("
        SELECT r.id, u.telegram_id 
        FROM requests r 
        JOIN users u ON r.user_id = u.id 
        WHERE r.id=? AND r.type='text_to_text'
    ");
    $stmt->execute([$request_id]);
    $req = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$req) {
        die("درخواست متن به متن معتبر نیست.");
    }

    // ارسال پیام به کاربر
    $ch = curl_init("https://api.telegram.org/bot".BOT_TOKEN."/sendMessage");
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => [
            'chat_id' => $req['telegram_id'],
            'text' => $admin_text
        ],
        CURLOPT_RETURNTRANSFER => true
    ]);
    curl_exec($ch);
    curl_close($ch);

    // بروزرسانی درخواست
    $upd = $pdo->prepare("
        UPDATE requests 
        SET status='done', completed_at=NOW() 
        WHERE id=?
    ");
    $upd->execute([$request_id]);

    header("Location: request_view.php?id=".$request_id."&success=1");
    exit;
}

/* =====================================================
   حالت قبلی: آپلود ویدیو (بدون تغییر)
===================================================== */

$video_url = trim($_POST['video_url'] ?? '');

$uploadDir = __DIR__ . '/../uploads/videos/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

if (empty($_FILES['video_file']['tmp_name']) && empty($video_url)) {
    die("لطفاً فایل ویدیو یا لینک وارد کنید.");
}

if (!empty($_FILES['video_file']['tmp_name'])) {
    $filename = time().'_'.basename($_FILES['video_file']['name']);
    $targetFile = $uploadDir.$filename;
    move_uploaded_file($_FILES['video_file']['tmp_name'], $targetFile);
} else {
    $filename = time().'_'.basename(parse_url($video_url, PHP_URL_PATH));
    $targetFile = $uploadDir.$filename;
    file_put_contents($targetFile, file_get_contents($video_url));
}

$webPath = '/video-bot/uploads/videos/'.$filename;

$upd = $pdo->prepare("
    UPDATE requests 
    SET video_file=?, video_url=?, status='done', completed_at=NOW() 
    WHERE id=?
");
$upd->execute([$webPath, $video_url, $request_id]);

header("Location: request_view.php?id=".$request_id."&success=1");
exit;
