<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';
require_once __DIR__ . '/admin_auth_lib.php';
require_once __DIR__ . '/telegram_lib.php';
require_once __DIR__ . '/db.php';

mocker_admin_require_permission('telegram-broadcast');

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

try {
    $pdo = mocker_db();
} catch (Throwable $e) {
    http_response_code(503);
    echo json_encode(['ok' => false, 'error' => 'db'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($method === 'GET') {
    $n = (int) $pdo->query('SELECT COUNT(*) AS c FROM telegram_bot_subscribers')->fetch(PDO::FETCH_ASSOC)['c'];
    echo json_encode(
        [
            'ok' => true,
            'subscriberCount' => $n,
            'telegramConfigured' => mocker_telegram_is_configured(),
        ],
        JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
    );
    exit;
}

if ($method !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'method'], JSON_UNESCAPED_UNICODE);
    exit;
}

mocker_require_csrf_post();

if (!mocker_telegram_is_configured()) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'telegram_not_configured'], JSON_UNESCAPED_UNICODE);
    exit;
}

$contentType = (string) ($_SERVER['CONTENT_TYPE'] ?? $_SERVER['HTTP_CONTENT_TYPE'] ?? '');
$isMultipartHeader = stripos($contentType, 'multipart/form-data') === 0;

$hasPhotoField = isset($_FILES['photo']) && is_array($_FILES['photo']);
$isMultipart = $isMultipartHeader || $hasPhotoField;

$parseMode = null;
$text = '';
$photoUrl = '';
$disableLinkPreview = false;
$buttonText = '';
$buttonUrl = '';
$uploadPath = null;
$uploadMime = null;

if ($isMultipart) {
    $text = trim((string) ($_POST['text'] ?? $_POST['caption'] ?? ''));
    $photoUrl = trim((string) ($_POST['photo_url'] ?? ''));
    $pm = trim((string) ($_POST['parse_mode'] ?? ''));
    if ($pm === 'HTML') {
        $parseMode = 'HTML';
    }
    $disableLinkPreview = !empty($_POST['disable_link_preview']) && $_POST['disable_link_preview'] !== '0' && $_POST['disable_link_preview'] !== 'false';
    $buttonText = trim((string) ($_POST['button_text'] ?? ''));
    $buttonUrl = trim((string) ($_POST['button_url'] ?? ''));
    $f = $_FILES['photo'] ?? null;
    if ($hasPhotoField && is_array($f)) {
        $upErr = (int) ($f['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($upErr !== UPLOAD_ERR_OK && $upErr !== UPLOAD_ERR_NO_FILE) {
            $detail = 'Yükleme hatası kodu: ' . $upErr;
            if ($upErr === UPLOAD_ERR_INI_SIZE || $upErr === UPLOAD_ERR_FORM_SIZE) {
                $detail = 'Dosya çok büyük (sunucu upload limiti veya 5 MB).';
            } elseif ($upErr === UPLOAD_ERR_PARTIAL) {
                $detail = 'Dosya yüklemesi yarım kaldı.';
            } elseif ($upErr === UPLOAD_ERR_NO_TMP_DIR) {
                $detail = 'Sunucuda geçici klasör yok.';
            } elseif ($upErr === UPLOAD_ERR_CANT_WRITE) {
                $detail = 'Diske yazılamadı.';
            } elseif ($upErr === UPLOAD_ERR_EXTENSION) {
                $detail = 'PHP uzantısı yüklemeyi engelledi.';
            }
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'upload_failed', 'detail' => $detail], JSON_UNESCAPED_UNICODE);
            exit;
        }
    }
    if (is_array($f) && isset($f['error']) && (int) $f['error'] === UPLOAD_ERR_OK) {
        $tmp = (string) ($f['tmp_name'] ?? '');
        $size = (int) ($f['size'] ?? 0);
        if ($size > 5 * 1024 * 1024) {
            http_response_code(400);
            echo json_encode(
                ['ok' => false, 'error' => 'file_too_large', 'detail' => 'Görsel en fazla 5 MB olabilir.'],
                JSON_UNESCAPED_UNICODE
            );
            exit;
        }
        if ($tmp !== '' && is_readable($tmp) && $size > 0) {
            if (class_exists('finfo', false)) {
                $fi = new finfo(FILEINFO_MIME_TYPE);
                $mime = $fi->file($tmp);
            } else {
                $mime = (string) ($f['type'] ?? 'application/octet-stream');
            }
            $allowed = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (in_array($mime, $allowed, true)) {
                $uploadPath = $tmp;
                $uploadMime = $mime;
            } else {
                http_response_code(400);
                echo json_encode(
                    ['ok' => false, 'error' => 'invalid_image_type', 'detail' => 'İzin verilen türler: JPEG, PNG, GIF, WebP.'],
                    JSON_UNESCAPED_UNICODE
                );
                exit;
            }
        }
    }
} else {
    $input = json_decode((string) file_get_contents('php://input'), true) ?: [];
    $text = trim((string) ($input['text'] ?? $input['caption'] ?? $input['message'] ?? ''));
    $photoUrl = trim((string) ($input['photo_url'] ?? ''));
    $pm = trim((string) ($input['parse_mode'] ?? ''));
    if ($pm === 'HTML') {
        $parseMode = 'HTML';
    }
    $disableLinkPreview = !empty($input['disable_link_preview']);
    $buttonText = trim((string) ($input['button_text'] ?? ''));
    $buttonUrl = trim((string) ($input['button_url'] ?? ''));
}

$hasPhotoUpload = $uploadPath !== null;
$hasPhotoUrl = $photoUrl !== '' && filter_var($photoUrl, FILTER_VALIDATE_URL) && preg_match('#^https?://#i', $photoUrl);
$hasPhoto = $hasPhotoUpload || $hasPhotoUrl;

if (!$hasPhoto && $text === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'empty'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($hasPhoto) {
    $capLen = function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
    if ($capLen > 1024) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'caption_too_long'], JSON_UNESCAPED_UNICODE);
        exit;
    }
} else {
    $textLen = function_exists('mb_strlen') ? mb_strlen($text, 'UTF-8') : strlen($text);
    if ($textLen > 4096) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'too_long'], JSON_UNESCAPED_UNICODE);
        exit;
    }
}

if (($buttonText !== '' && $buttonUrl === '') || ($buttonText === '' && $buttonUrl !== '')) {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'button_fields_required'], JSON_UNESCAPED_UNICODE);
    exit;
}

$replyMarkup = null;
if ($buttonText !== '' && $buttonUrl !== '') {
    $btnLen = function_exists('mb_strlen') ? mb_strlen($buttonText, 'UTF-8') : strlen($buttonText);
    if ($btnLen > 64) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'button_text_too_long'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (!filter_var($buttonUrl, FILTER_VALIDATE_URL) || !preg_match('#^https?://#i', $buttonUrl)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'button_url_invalid'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    $replyMarkup = [
        'inline_keyboard' => [
            [
                [
                    'text' => $buttonText,
                    'url' => $buttonUrl,
                ],
            ],
        ],
    ];
}

$rows = $pdo->query('SELECT chat_id FROM telegram_bot_subscribers')->fetchAll(PDO::FETCH_ASSOC);
$sent = 0;
$failed = 0;
$firstTelegramError = null;

$recordErr = static function (?string $msg) use (&$firstTelegramError): void {
    if ($msg === null || $msg === '') {
        return;
    }
    if ($firstTelegramError === null) {
        $firstTelegramError = $msg;
    }
};

if ($hasPhoto) {
    $caption = $text;
    $fileId = null;
    
    $fileIdIsDocument = false;

    foreach ($rows as $r) {
        $cid = trim((string) ($r['chat_id'] ?? ''));
        if ($cid === '' || $cid === '0') {
            continue;
        }

        if ($fileId !== null) {
            if ($fileIdIsDocument) {
                $res = mocker_telegram_send_document_ref($cid, $fileId, $caption, $parseMode, $replyMarkup);
            } else {
                $res = mocker_telegram_send_photo_ref($cid, $fileId, $caption, $parseMode, $replyMarkup);
            }
            if (!empty($res['ok'])) {
                ++$sent;
            } else {
                ++$failed;
                $recordErr(isset($res['description']) ? (string) $res['description'] : null);
            }
            usleep(50000);
            continue;
        }

        if ($hasPhotoUpload && $uploadPath !== null) {
            $res = mocker_telegram_send_photo_upload($cid, $uploadPath, $uploadMime, $caption, $parseMode, $replyMarkup);
        } else {
            $res = mocker_telegram_send_photo_ref($cid, $photoUrl, $caption, $parseMode, $replyMarkup);
        }

        if (!empty($res['ok'])) {
            ++$sent;
            if (!empty($res['file_id'])) {
                $fileId = $res['file_id'];
                $fileIdIsDocument = !empty($res['is_document']);
            }
        } else {
            ++$failed;
            $recordErr(isset($res['description']) ? (string) $res['description'] : null);
        }
        usleep(50000);
    }
} else {
    foreach ($rows as $r) {
        $cid = trim((string) ($r['chat_id'] ?? ''));
        if ($cid === '' || $cid === '0') {
            continue;
        }
        $p = [
            'chat_id' => $cid,
            'text' => $text,
        ];
        if ($parseMode !== null && $parseMode !== '') {
            $p['parse_mode'] = $parseMode;
        }
        if ($disableLinkPreview) {
            $p['disable_web_page_preview'] = true;
        }
        if (is_array($replyMarkup) && $replyMarkup !== []) {
            $p['reply_markup'] = $replyMarkup;
        }
        $j = mocker_telegram_api_post_json('sendMessage', $p);
        if (is_array($j) && !empty($j['ok'])) {
            ++$sent;
        } else {
            ++$failed;
            $recordErr(mocker_telegram_error_description($j));
        }
        usleep(50000);
    }
}

$total = count($rows);
if ($total === 0 && $firstTelegramError === null) {
    $firstTelegramError = 'Kayıtlı alıcı yok. Kullanıcıların bota özel sohbette /start veya mesaj göndermesi gerekir.';
}

echo json_encode(
    [
        'ok' => true,
        'sent' => $sent,
        'failed' => $failed,
        'total' => $total,
        'telegram_error' => $firstTelegramError,
    ],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
);
