<?php
declare(strict_types=1);
ini_set('display_errors','1'); error_reporting(E_ALL);

require_once 'config.php';
require_once 'functions.php';

if (!defined('TOKEN')) define('TOKEN', '6984456345:AAH2c4sr8kRtbUTWzx71hddcdX2GE1m5WVQ');
if (!defined('CHANNEL')) define('CHANNEL', '@playercubevideo');
define('WATERMARK_TEXT', 'Playerscubebot');
define('FOOTER_BOT', '@Playerscubebot');

require_once 'top_players.php';

$SAVE_DIR = realpath(__DIR__.'/../assets') ?: (__DIR__.'/../assets');
if (!is_dir($SAVE_DIR)) @mkdir($SAVE_DIR, 0775, true);

$leagues = [
  '65' => 'Premier League (England)',
  '75' => 'LaLiga (Spain)',
  '77' => 'Serie A (Italy)',
  '67' => 'Bundesliga (Germany)',
  '68' => 'Ligue 1 (France)',
  '403'=> 'Saudi Pro League',
  '145'=> 'MLS (USA)',
  'stage:iran/pro-league/2' => 'Persian Gulf Pro League (Iran)',
  '64' => 'Eredivisie (Netherlands)',
  '79' => 'Primeira Liga (Portugal)',
  '692' => 'AFC Champions League',
  '60' => 'UEFA Champions League (Group Stage)',
];

$sel = $_GET['competition'] ?? $_POST['competition'] ?? '65';
if (!array_key_exists($sel, $leagues)) $sel = '65';

function fetchLeagueTable(string $sel): array {
  if (strpos($sel, 'stage:') === 0) {
    // مثال: stage:iran/pro-league/2  →  iran/pro-league/2
    $stagePath = substr($sel, 6);
    $url = "https://prod-cdn-public-api.livescore.com/v1/api/app/stage/soccer/{$stagePath}?locale=en";
  } else {
    $id  = (string)$sel;
    $url = "https://prod-cdn-public-api.livescore.com/v1/api/app/competition/{$id}/leagueTable/?locale=en";
  }

  $json = @file_get_contents($url);
  if (!$json) return [];
  $data = json_decode($json, true);

  // هر دو endpoint معمولاً Stages دارند
  $stage = $data['Stages'][0] ?? null;
  if (!$stage) return [];

  // نام مسابقات
  $compName = trim(($stage['Cnm'] ?? '').' / '.($stage['Snm'] ?? 'League'));

  // مسیرهای مختلف برای جدول
  $paths = [
    ['LeagueTable','L',0,'Tables',0,'team'],
    ['LeagueTable','Tables',0,'team'],
    ['LeagueTable','L',0,'team'],
    ['LeagueTable','team'],
  ];
  $teams = [];
  foreach ($paths as $path){
    $tmp = $stage;
    foreach ($path as $k){
      if (!isset($tmp[$k])) { $tmp = null; break; }
      $tmp = $tmp[$k];
    }
    if (is_array($tmp) && $tmp){ $teams = $tmp; break; }
  }
  return ['comp'=>$compName,'teams'=>$teams];
}

function resolveFontPath(): ?string {
  // مسیر دقیق فونت روی هاست
  $fontPath = __DIR__ . '/assets/DejaVuSans.ttf';
  if (is_readable($fontPath)) {
    return $fontPath;
  }

  // در صورت نبود، تلاش برای نسخه‌های دیگر DejaVu
  $candidates = glob(__DIR__ . '/assets/DejaVuSans*.ttf');
  if (!empty($candidates)) {
    return $candidates[0];
  }

  // آخرین fallback
  error_log("⚠️ No suitable DejaVuSans font found in assets directory.");
  return null;
}

function mb_strrev(string $s): string {
  $out = '';
  for ($i = mb_strlen($s, 'UTF-8') - 1; $i >= 0; $i--) {
    $out .= mb_substr($s, $i, 1, 'UTF-8');
  }
  return $out;
}

function ttf_metrics(int $size, string $font, string $text): array {
  $bb = imagettfbbox($size, 0, $font, $text);
  $width   = abs($bb[2] - $bb[0]);
  $height  = abs($bb[7] - $bb[1]); // کل ارتفاع با صعود/نزول
  $ascent  = abs($bb[7]);          // بالای baseline (عددی مثبت)
  $descent = abs($bb[1]);          // پایین baseline
  return compact('width','height','ascent','descent');
}

function draw_cell_left($img, int $xLeft, int $rowTop, int $rowH, int $size, int $color, string $font, string $text): void {
  $bbox = imagettfbbox($size, 0, $font, $text);
  $textW = abs($bbox[2] - $bbox[0]);
  $textH = abs($bbox[7] - $bbox[1]);
  $descent = abs($bbox[1]);
  $baselineY = (int) round($rowTop + ($rowH + $textH) / 2 - $descent);
  imagettftext($img, $size, 0, $xLeft, $baselineY, $color, $font, $text);
}

function render_table_image_gd(string $title, array $teams, string $fontPath, string $savePath): bool {
  if (!function_exists('imagettftext')) return false;
  if (!is_readable($fontPath)) return false;
  
  // Layout
  $w = 1000;
  $marginX = 50;
  $marginY = 30;
  $rowH   = 44;
  $titleH = 78;
  $headerH= 50;
  $footerH = 72;

  // Height
  $rows = max(1, count($teams));
  $h = $marginY * 2 + $titleH + $headerH + ($rows * $rowH) + $footerH;
  if ($h < 300) $h = 300;

  // Canvas
  $img = imagecreatetruecolor($w, $h);
  $bg = imagecolorallocate($img, 11, 15, 22);
  imagefilledrectangle($img, 0, 0, $w, $h, $bg);

  // Colors
  $white    = imagecolorallocate($img, 232, 238, 247);
  $muted    = imagecolorallocate($img, 170, 181, 198);
  $green    = imagecolorallocate($img, 76, 175, 80);
  $headerBg = imagecolorallocatealpha($img, 255, 255, 255, 115);
  imagealphablending($img, true);
  imagesavealpha($img, true);

  // Watermark background
  $wmText  = defined('WATERMARK_TEXT') ? WATERMARK_TEXT : 'Playerscubebot';
  $wmAlpha = 120; // transparency
  $wmColor = imagecolorallocatealpha($img, 255, 255, 255, $wmAlpha);
  $wmSize  = 22;
  $wmAngle = 30;
  $stepX   = 260;
  $stepY   = 180;

  for ($yy = -60; $yy < $h; $yy += $stepY) {
    for ($xx = -120; $xx < $w; $xx += $stepX) {
      imagettftext($img, $wmSize, $wmAngle, $xx, $yy, $wmColor, $fontPath, $wmText);
    }
  }

  $rowEvenBg = imagecolorallocatealpha($img, 255, 255, 255, 118);
  $grid      = imagecolorallocatealpha($img, 255, 255, 255, 90);

  // Title
  $titleClean = trim($title);
  $line2      = $titleClean;

  $yTitle1 = $marginY + 24;
  $lineGap   = 20;
  $yTitle2   = $yTitle1 + $lineGap;
  $bbox2     = imagettfbbox(24, 0, $fontPath, $line2);
  $line2W    = $bbox2[2] - $bbox2[0];
imagettftext($img, 24, 0, $marginX, $yTitle2, $white, $fontPath, "\u{202A}" . $line2);

  $y = $marginY + $titleH;

  // Header bar
  imagefilledrectangle($img, $marginX, $y, $w - $marginX, $y + $headerH, $headerBg);

  // Column x positions (left to right for English)
  $x_rank = $marginX + 35;
  $x_team = $x_rank + 80;
  $x_pld  = $x_team + 350;
  $x_win  = $x_pld + 80;
  $x_draw = $x_win + 80;
  $x_loss = $x_draw + 80;
  $x_pts  = $x_loss + 80;

  // Header labels (LTR)
  $headerSize = 16;
  $headerTop  = $y;
  draw_cell_left($img, $x_rank, $headerTop, $headerH, $headerSize, $white, $fontPath, "Rank");
  draw_cell_left($img, $x_team, $headerTop, $headerH, $headerSize, $white, $fontPath, "Team");
  draw_cell_left($img, $x_pld,  $headerTop, $headerH, $headerSize, $white, $fontPath, "P");
  draw_cell_left($img, $x_win,  $headerTop, $headerH, $headerSize, $white, $fontPath, "W");
  draw_cell_left($img, $x_draw, $headerTop, $headerH, $headerSize, $white, $fontPath, "D");
  draw_cell_left($img, $x_loss, $headerTop, $headerH, $headerSize, $white, $fontPath, "L");
  draw_cell_left($img, $x_pts,  $headerTop, $headerH, $headerSize, $green, $fontPath, "Pts");

  $yRowsStart = $y + $headerH;

  // --- Rows
  $rowSize = 18;
  $rank    = 1;
  for ($i=0; $i<count($teams); $i++) {
    $t = $teams[$i];
    $rowTop = $yRowsStart + $i*$rowH;

    if ($i % 2 === 0) {
      imagefilledrectangle($img, $marginX, $rowTop, $w - $marginX, $rowTop + $rowH, $rowEvenBg);
    }
    imageline($img, $marginX, $rowTop, $w - $marginX, $rowTop, $grid);

    $rnk  = $t['rnk'] ?? $t['rank'] ?? $rank;
    $team = $t['Tnm'] ?? $t['teamName'] ?? 'Team';
    $pld  = $t['pld'] ?? $t['Pl'] ?? 0;
    $w_   = $t['win'] ?? $t['W'] ?? 0;
    $d    = $t['drw'] ?? $t['D'] ?? 0;
    $l    = $t['lst'] ?? $t['L'] ?? 0;
    $pts  = $t['pts'] ?? $t['Pts'] ?? 0;

    draw_cell_left($img, $x_rank, $rowTop, $rowH, $rowSize, $muted, $fontPath, (string)$rnk);
    draw_cell_left($img, $x_team, $rowTop, $rowH, $rowSize, $white, $fontPath, $team);
    draw_cell_left($img, $x_pld,  $rowTop, $rowH, $rowSize, $muted, $fontPath, (string)$pld);
    draw_cell_left($img, $x_win,  $rowTop, $rowH, $rowSize, $muted, $fontPath, (string)$w_);
    draw_cell_left($img, $x_draw, $rowTop, $rowH, $rowSize, $muted, $fontPath, (string)$d);
    draw_cell_left($img, $x_loss, $rowTop, $rowH, $rowSize, $muted, $fontPath, (string)$l);
    draw_cell_left($img, $x_pts,  $rowTop, $rowH, $rowSize+2, $green, $fontPath, (string)$pts);

    $rank++;
  }

  // Footer
  $lastBottom = $yRowsStart + count($teams)*$rowH;
  imageline($img, $marginX, $lastBottom, $w - $marginX, $lastBottom, $grid);

  $footerTop   = $lastBottom + 18;
  $footer1 = "First live scores & standings robot on Telegram";
  $footer2 = defined('FOOTER_BOT') ? FOOTER_BOT : '@Playerscubebot';

  // Centered text
  $centerText = function($size, $y, $color, $text) use ($img, $fontPath, $w) {
    $bb = imagettfbbox($size, 0, $fontPath, $text);
    $tw = $bb[2] - $bb[0];
    $x  = (int) round(($w - $tw) / 2);
    imagettftext($img, $size, 0, $x, $y, $color, $fontPath, $text);
  };

  $centerText(16, $footerTop + 16, $muted, $footer1);
  $centerText(18, $footerTop + 16 + 26, $white, $footer2);

  // Crop & save
  $finalHeight = $lastBottom + $footerH;
  $croppedImg  = imagecreatetruecolor($w, $finalHeight);
  imagecopy($croppedImg, $img, 0, 0, 0, 0, $w, $finalHeight);
  imagedestroy($img);

  imagepng($croppedImg, $savePath);
  imagedestroy($croppedImg);

  return is_file($savePath) && filesize($savePath) > 0;
}

function tg_sendPhoto(string $chatId, string $imagePath, string $caption=''): bool {
  $url = "https://api.telegram.org/bot".TOKEN."/sendPhoto";

  // تعیین MIME به‌صورت امن
  $mime = 'image/png';
  if (function_exists('mime_content_type')) {
      $detected = @mime_content_type($imagePath);
      if (!empty($detected)) $mime = $detected;
  }

  $post = [
    'chat_id'    => $chatId,
    'caption'    => $caption,
    'parse_mode' => 'HTML',
    'photo'      => new CURLFile($imagePath, $mime, basename($imagePath)),
  ];

  $ch = curl_init($url);
  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $post,
    CURLOPT_TIMEOUT        => 30
  ]);
  $res = curl_exec($ch);
  if ($res === false) {
    error_log('cURL error: '.curl_error($ch));
    curl_close($ch);
    return false;
  }

  $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  $j = json_decode($res, true);
  if ($http !== 200 || empty($j['ok'])) {
    error_log("Telegram API error (HTTP $http): $res");
    return false;
  }
  return true;
}

$data = fetchLeagueTable($sel);
$compTitle = $leagues[$sel] ?? ($data['comp'] ?? 'league');
$teams     = $data['teams'] ?? [];
$msg = '';

if (isset($_POST['send'])) {
  if (empty($teams)) {
    $msg = '❌ جدول در دسترس نیست.';
  } else {
    $safeId = str_replace(['stage:','/'], ['stage_','-'], $sel);
    $png = $SAVE_DIR.'/standings_'.$safeId.'_'.date('Ymd_His').'.png';

    $ok = false;

    // === تابع بررسی وجود مرورگر headless (برای fallback) ===
    function find_binary(array $binaries): ?string {
      foreach ($binaries as $bin) {
        $out = @shell_exec("command -v $bin 2>/dev/null");
        if (is_string($out) && trim($out) !== '') return trim($out);
      }
      return null;
    }

    // First, try GD as it's more direct for text-based tables
    $fontPath = resolveFontPath();
    if ($fontPath) {
      $ok = render_table_image_gd($compTitle, $teams, $fontPath, $png);
      error_log("DEBUG: Using font path => " . $fontPath);

      if (!$ok) {
        error_log("GD failed to create image. Font path: $fontPath");
      }
      error_log("DEBUG: GD result => " . ($ok ? "SUCCESS" : "FAILED"));

    } else {
      error_log("No suitable font file found for GD rendering.");
    }
    
    // If GD failed, try the headless browser method as a fallback
    if (!$ok && function_exists('shell_exec') && find_binary(['google-chrome','chromium-browser'])) {
        error_log("DEBUG: Trying fallback HTML→PNG method");

      $html = build_html($compTitle, $teams);
      $ok = html_to_png($html, $png);
      if (!$ok) {
        error_log("Headless browser failed to create image.");
      }
    }

    // === تابع HTML به PNG برای fallback (در صورت نبود GD) ===
    function html_to_png(string $html, string $savePath): bool {
      $tmpHtml = sys_get_temp_dir() . '/tmp_league_' . uniqid() . '.html';
      file_put_contents($tmpHtml, $html);

      $chrome = find_binary(['google-chrome', 'chromium', 'chromium-browser', 'wkhtmltoimage']);
      if (!$chrome) {
        error_log("No Chrome/Chromium or wkhtmltoimage binary found for html_to_png.");
        return false;
      }

      // دستور بر اساس نوع مرورگر
      if (str_contains($chrome, 'wkhtmltoimage')) {
        $cmd = escapeshellcmd($chrome) . " --quality 90 --width 1000 " . escapeshellarg($tmpHtml) . " " . escapeshellarg($savePath) . " 2>&1";
      } else {
        // chrome/chromium
        $cmd = escapeshellcmd($chrome) . " --headless --disable-gpu --screenshot=" . escapeshellarg($savePath) .
               " --window-size=1000,1200 " . escapeshellarg($tmpHtml) . " 2>&1";
      }

      $out = shell_exec($cmd);
      @unlink($tmpHtml);

      if (!is_file($savePath) || filesize($savePath) === 0) {
        error_log("html_to_png failed. Output: $out");
        return false;
      }
      return true;
    }

    // === تابع HTML ساز برای fallback ===
    function build_html(string $title, array $teams): string {
      $rows = '';
      foreach ($teams as $i => $t) {
        $rank = $t['rnk'] ?? $t['rank'] ?? $i+1;
        $team = htmlspecialchars($t['Tnm'] ?? $t['teamName'] ?? 'Team');
        $pts  = $t['pts'] ?? $t['Pts'] ?? 0;
        $rows .= "<tr><td>$rank</td><td>$team</td><td>$pts</td></tr>";
      }
      return "<html><body style='font-family:sans-serif;background:#0b0f16;color:#e8eef7;text-align:center;'>
      <h2>$title</h2><table style='width:100%;border-collapse:collapse'>
      $rows</table></body></html>";
    }

    if ($ok) {

      $capTitle = '📇 ' . $compTitle;

      $top   = array_slice($teams, 0, 6);
      $lines = [];
      $rank  = 1;

      foreach ($top as $t) {
          $teamRaw = $t['Tnm'] ?? $t['teamName'] ?? 'Team';
          $team    = $teamRaw;
          $ptsVal  = (int)($t['pts'] ?? $t['Pts'] ?? $t['pt'] ?? 0);

          $lines[] = $rank . '. ' . $team . ': ' . $ptsVal . ' pts';
          $rank++;
      }

      $ctas = [
          "👈🏻  All live league tables available in the Mini App:\n@Playerscubebot",
          "👈🏻  Goals and match statistics:\n@playercubevideo",
      ];

      $topCaption = (function_exists('getTopPlayersCaption')) ? getTopPlayersCaption($sel) : '';
      $topCaptionSafe = (is_string($topCaption) && $topCaption !== '') ? trim($topCaption) : '';

      $cap = $capTitle . "\n\n"
           . implode("\n", $lines)
           . ($topCaptionSafe !== '' ? "\n\n".$topCaptionSafe : '')
           . "\n\n" . implode("\n\n", $ctas);

      if (mb_strlen($cap, 'UTF-8') > 1024) {
          $cap = mb_substr($cap, 0, 1010, 'UTF-8') . "…";
      }

      $sent = tg_sendPhoto(CHANNEL, $png, $cap);
      $msg  = $sent ? '✅ League table image sent to channel.' : '❌ Failed to send the image.';

    } else if (!$msg) {
      $msg = '❌ Could not generate the image. Make sure GD with FreeType or a headless browser (e.g., Chrome) is available.';
    }

  }
}
?>
<!doctype html>
<html lang="fa" dir="rtl">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>ارسال جدول لیگ‌ها (تصویر)</title>
<script src="https://cdn.tailwindcss.com"></script>
<style>
:root{ --border:rgba(255,255,255,.12); --muted:#aab5c6; }
body{ margin:0; padding:16px; min-height:100vh; background:#0b0f16; color:#e8eef7; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Vazirmatn", sans-serif;}
.container{max-width:900px;margin:0 auto}
.card{ background:linear-gradient(180deg, rgba(255,255,255,.05), rgba(255,255,255,.03)); border:1px solid var(--border); border-radius:10px; padding:16px; }
.btn{ background:#4CAF50; color:#fff; padding:.55rem .9rem; border-radius:8px; text-decoration:none; display:inline-block }
.select{ background:#0f1723; border:1px solid var(--border); color:#e8eef7; border-radius:8px; padding:.55rem 1rem }
</style>
</head>
<body>
<div class="container">
  <div class="card" style="display:flex;align-items:center;justify-content:space-between;">
    <h1 class="text-xl md:text-2xl font-bold">ارسال جدول لیگ‌ها (تصویر)</h1>
    <!--<a href="index.html" class="btn">بازگشت</a>-->
  </div>

  <div class="card" style="margin-top:14px">
    <form method="GET" class="flex items-center gap-3">
      <select name="competition" class="select" onchange="this.form.submit()">
        <?php foreach ($leagues as $id => $name): 
              $idStr = (string)$id; ?>
          <option value="<?php echo htmlspecialchars($idStr); ?>" 
                  <?php echo ($idStr === (string)$sel ? 'selected' : ''); ?>>
            <?php echo htmlspecialchars($name); ?>
          </option>
        <?php endforeach; ?>

      </select>
      <div class="text-sm text-[var(--muted)]">ارسال به: <b><?php echo htmlspecialchars(CHANNEL); ?></b></div>
    </form>
  </div>

  <form method="POST" class="card" style="margin-top:14px">
    <input type="hidden" name="competition" value="<?php echo htmlspecialchars((string)$sel); ?>">
    <button type="submit" name="send" value="1" class="btn">ساخت تصویر و ارسال</button>
    <?php if (!empty($msg)): ?>
      <div class="mt-3 text-sm <?php echo (strpos($msg,'✅')===0?'text-green-400':'text-red-400'); ?>"><?php echo htmlspecialchars($msg); ?></div>
    <?php endif; ?>
  </form>
          <div class="mt-8 text-center">
            <a href="dashboard.php" class="text-blue-600 hover:text-blue-800 font-medium">⬅️ بازگشت به داشبورد</a>
        </div>
</div>
</body>
</html>