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

$content = file_get_contents("php://input");
$update = json_decode($content, true);
if (!$update) exit;

$chat_id    = $update['message']['chat']['id'] ?? null;
$text       = $update['message']['text'] ?? '';
$message_id = $update['message']['message_id'] ?? null;
$contact    = $update['message']['contact']['phone_number'] ?? '';
$first_name = $update['message']['from']['first_name'] ?? '';
$last_name  = $update['message']['from']['last_name'] ?? '';
$username   = $update['message']['from']['username'] ?? '';


function editLoading($chat_id, $message_id, $percent){
    $bars = floor($percent / 10);
    $line = str_repeat("▓", $bars) . str_repeat("░", 10 - $bars);

    file_get_contents(
        "https://api.telegram.org/bot".BOT_TOKEN."/editMessageText?".
        http_build_query([
            'chat_id' => $chat_id,
            'message_id' => $message_id,
            'text' => "⏳ درحال آماده سازی...\n\n{$percent}% {$line}"
        ])
    );
}



if (isset($update['callback_query'])) {

    $data = $update['callback_query']['data'];
    $chat_id = $update['callback_query']['message']['chat']['id'];

    if (strpos($data, 'like_') === 0) {
        $id = intval(str_replace('like_', '', $data));
        $pdo->prepare("UPDATE requests SET likes = likes + 1 WHERE id=?")->execute([$id]);
        sendMessage($chat_id, "👍 ممنون از بازخوردت");
        exit;
    }

    if (strpos($data, 'dislike_') === 0) {
        $id = intval(str_replace('dislike_', '', $data));
        $pdo->prepare("UPDATE requests SET dislikes = dislikes + 1 WHERE id=?")->execute([$id]);
        sendMessage($chat_id, "👎 بازخوردت ثبت شد");
        exit;
    }

    if (strpos($data, 'continue_') === 0) {
        $id = intval(str_replace('continue_', '', $data));

        $pdo->prepare("
            INSERT INTO user_states (user_id,pending_type,pending_step)
            SELECT user_id,'text_to_text','waiting_text'
            FROM requests WHERE id=?
        ")->execute([$id]);

        sendMessage($chat_id, "✍️ این بخش در حال توسعه هست لطفا چت جدید رو بنویس");
        exit;
    }

    if ($data === 'newchat') {
        $user_id = getUserId($chat_id,$pdo);

        $pdo->prepare("
            INSERT INTO user_states (user_id,pending_type,pending_step)
            VALUES (?, 'text_to_text','waiting_text')
            ON DUPLICATE KEY UPDATE
                pending_type='text_to_text',
                pending_step='waiting_text',
                temp_text=NULL,
                temp_image=NULL
        ")->execute([$user_id]);

        sendMessage($chat_id, "🧠 چی دوس داری بدونی؟ بنویس تا بهت بگم");
        exit;
    }
}




/* ======================= توابع ======================= */

function featureStatus($pdo, $key){
    $s = $pdo->prepare("SELECT setting_value FROM bot_settings WHERE setting_key=?");
    $s->execute([$key]);
    return $s->fetchColumn() ?: 'disabled';
}

function getUserId($chat_id, $pdo){
    $stmt = $pdo->prepare("SELECT id FROM users WHERE telegram_id=? LIMIT 1");
    $stmt->execute([$chat_id]);
    return $stmt->fetchColumn();
}

function normalizeText($text){
    return str_replace(
        ['[Enter_LF]', '[ENTER_LF]', '[LF]'],
        "\n",
        $text
    );
}

function sendMessage($chat_id, $text, $keyboard=null){
    $text = normalizeText($text);
    $url = "https://api.telegram.org/bot".BOT_TOKEN."/sendMessage";
    $data = ['chat_id'=>$chat_id,'text'=>$text];
    if($keyboard){
        $data['reply_markup'] = json_encode($keyboard, JSON_UNESCAPED_UNICODE);
    }
    file_get_contents($url.'?'.http_build_query($data));
}

/* ======================= دریافت شماره ======================= */

if (isset($update['message']['contact'])) {

    $stmt = $pdo->prepare("
        INSERT INTO users (telegram_id, first_name, last_name, username, phone, created_at)
        VALUES (?, ?, ?, ?, ?, NOW())
        ON DUPLICATE KEY UPDATE
            first_name=?, last_name=?, username=?, phone=?
    ");
    $stmt->execute([
        $chat_id,$first_name,$last_name,$username,$contact,
        $first_name,$last_name,$username,$contact
    ]);

    $keyboard = ['keyboard'=>[], 'resize_keyboard'=>true];

    if(featureStatus($pdo,'text_to_video')!='disabled')
        $keyboard['keyboard'][] = [['text'=>'ساخت ویدیو با متن']];

    if(featureStatus($pdo,'image_to_video')!='disabled')
        $keyboard['keyboard'][] = [['text'=>'ساخت ویدیو از روی عکس']];

    if(featureStatus($pdo,'text_to_text')!='disabled')
    $keyboard['keyboard'][] = [['text'=>'چت جدید با هوش مصنوعی']];

    sendMessage($chat_id,"گزینه مورد نظر را انتخاب کنید:",$keyboard);
    exit;
}

/* ======================= /start ======================= */

if ($text == '/start') {

    $user_id = getUserId($chat_id, $pdo);

    if ($user_id) {
        $keyboard = ['keyboard'=>[], 'resize_keyboard'=>true];

        if(featureStatus($pdo,'text_to_video')!='disabled')
            $keyboard['keyboard'][] = [['text'=>'ساخت ویدیو با متن']];

        if(featureStatus($pdo,'image_to_video')!='disabled')
            $keyboard['keyboard'][] = [['text'=>'ساخت ویدیو از روی عکس']];

        if(featureStatus($pdo,'text_to_text')!='disabled')
    $keyboard['keyboard'][] = [['text'=>'چت جدید با هوش مصنوعی']];


        sendMessage(
            $chat_id,
            "خوش اومدی 👋\nیکی از گزینه‌ها رو انتخاب کن:",
            $keyboard
        );
        exit;
    }

    sendMessage($chat_id,"سلام! شماره خود را ارسال کنید:",[
        'keyboard'=>[[['text'=>'ارسال شماره','request_contact'=>true]]],
        'resize_keyboard'=>true
    ]);
    exit;
}

/* ======================= بعد از start ======================= */

$user_id = getUserId($chat_id,$pdo);
if(!$user_id) exit;

/* ======================= متن به متن ======================= */

if($text=='چت جدید با هوش مصنوعی'){
    if(featureStatus($pdo,'text_to_text')=='maintenance'){
        sendMessage($chat_id,"⏳ این بخش در حال توسعه است");
        exit;
    }

    $pdo->prepare("
        INSERT INTO user_states (user_id,pending_type,pending_step)
        VALUES (?, 'text_to_text','waiting_text')
        ON DUPLICATE KEY UPDATE
            pending_type='text_to_text',
            pending_step='waiting_text',
            temp_text=NULL,
            temp_image=NULL
    ")->execute([$user_id]);

    sendMessage($chat_id,"لطفاً متن خود را ارسال کنید:");
    exit;
}

/* ======================= متن به ویدیو ======================= */

if($text=='ساخت ویدیو با متن'){
    if(featureStatus($pdo,'text_to_video')=='maintenance'){
        sendMessage($chat_id,"⏳ این بخش در حال توسعه است");
        exit;
    }

    $pdo->prepare("
        INSERT INTO user_states (user_id,pending_type,pending_step)
        VALUES (?, 'text_to_video','waiting_text')
        ON DUPLICATE KEY UPDATE
            pending_type='text_to_video',
            pending_step='waiting_text',
            temp_text=NULL,
            temp_image=NULL
    ")->execute([$user_id]);

    sendMessage($chat_id,"لطفاً متن ویدیو را ارسال کنید:");
    exit;
}

/* ======================= عکس به ویدیو ======================= */

if($text=='ساخت ویدیو از روی عکس'){
    if(featureStatus($pdo,'image_to_video')=='maintenance'){
        sendMessage($chat_id,"⏳ این بخش در حال توسعه است");
        exit;
    }

    $pdo->prepare("
        INSERT INTO user_states (user_id,pending_type,pending_step)
        VALUES (?, 'image_to_video','waiting_image')
        ON DUPLICATE KEY UPDATE
            pending_type='image_to_video',
            pending_step='waiting_image',
            temp_text=NULL,
            temp_image=NULL
    ")->execute([$user_id]);

    sendMessage($chat_id,"لطفاً ابتدا عکس خود را ارسال کنید:");
    exit;
}

/* ======================= دریافت عکس ======================= */

if(isset($update['message']['photo'])){

    $stmt = $pdo->prepare("
        SELECT * FROM user_states
        WHERE user_id=? AND pending_type='image_to_video'
    ");
    $stmt->execute([$user_id]);
    $state = $stmt->fetch(PDO::FETCH_ASSOC);

    if(!$state){
        sendMessage($chat_id,"درخواستی برای عکس به ویدیو ندارید.");
        exit;
    }

    $photos = $update['message']['photo'];
    $photo_id = end($photos)['file_id'];

    $res = json_decode(
        file_get_contents("https://api.telegram.org/bot".BOT_TOKEN."/getFile?file_id=".$photo_id),
        true
    );

    $file_path = $res['result']['file_path'] ?? null;
    if(!$file_path) exit;

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

    $filename = time().'_'.basename($file_path);
    $save_path = $uploadDir.$filename;

    file_put_contents(
        $save_path,
        file_get_contents("https://api.telegram.org/file/bot".BOT_TOKEN."/".$file_path)
    );

    $web_path = '/video-bot/uploads/images/'.$filename;

    $pdo->prepare("
        UPDATE user_states
        SET temp_image=?, pending_step='waiting_text'
        WHERE user_id=?
    ")->execute([$web_path,$user_id]);

    sendMessage($chat_id,"عکس دریافت شد. لطفاً متن خود را ارسال کنید:");
    exit;
}

/* ======================= دریافت متن نهایی ======================= */

if($text){

    $stmt = $pdo->prepare("SELECT * FROM user_states WHERE user_id=?");
    $stmt->execute([$user_id]);
    $state = $stmt->fetch(PDO::FETCH_ASSOC);

    if($state){

        $text = normalizeText($text);

        $pdo->prepare("
            INSERT INTO requests
            (user_id,type,text_content,image_file,status,step,created_at,user_message_id)
            VALUES (?,?,?,?, 'new','complete',NOW(),?)
        ")->execute([
            $user_id,
            $state['pending_type'],
            $text,
            $state['temp_image'],
            $message_id
        ]);

        $pdo->prepare("DELETE FROM user_states WHERE user_id=?")
            ->execute([$user_id]);







// ارسال پیام لودینگ
$res = file_get_contents(
    "https://api.telegram.org/bot".BOT_TOKEN."/sendMessage?".
    http_build_query([
        'chat_id' => $chat_id,
        'text' => "⏳ در حال آماده سازی...\n\n0% ░░░░░░░░░░"
    ])
);

$data = json_decode($res, true);
$loading_message_id = $data['result']['message_id'] ?? null;

// ذخیره message_id لودینگ
$pdo->prepare("
    UPDATE requests 
    SET loading_message_id = ?
    WHERE user_message_id = ?
")->execute([$loading_message_id, $message_id]);

// شبیه‌سازی حرکت اولیه
sleep(1);
editLoading($chat_id, $loading_message_id, 10);
sleep(2);
editLoading($chat_id, $loading_message_id, 20);
sleep(2);
editLoading($chat_id, $loading_message_id, 30);
sleep(2);
editLoading($chat_id, $loading_message_id, 40);
sleep(2);
editLoading($chat_id, $loading_message_id, 50);
sleep(3);
editLoading($chat_id, $loading_message_id, 60);
sleep(3);
editLoading($chat_id, $loading_message_id, 70);
sleep(3);
editLoading($chat_id, $loading_message_id, 80);
sleep(3);
editLoading($chat_id, $loading_message_id, 90);
sleep(3);
editLoading($chat_id, $loading_message_id, 100);




        exit;
    }

    sendMessage($chat_id,"لطفاً یکی از گزینه‌ها را انتخاب کنید.");
    exit;
}
