<?php
if(!isset($active)) $active = '';
$user_name = $_SESSION["user_name"] ?? "User";
$dongle = $_SESSION["dongle_serial"] ?? ($_SESSION["dongle"] ?? "-");
$sub_end = $_SESSION["sub_end"] ?? ($_SESSION["subscription_end"] ?? "-");
$ip = $_SERVER["REMOTE_ADDR"] ?? "-";

/* Country detection (best-effort):
   1) GeoIP PHP ext if available
   2) Fallback to public IP geo endpoint (ipwho.is) if outbound HTTP allowed
*/
$country_code = "UN";
$country_name = "Unknown";
if (function_exists("geoip_country_code_by_name")) {
  $cc = @geoip_country_code_by_name($ip);
  $cn = @geoip_country_name_by_name($ip);
  if ($cc) $country_code = strtoupper($cc);
  if ($cn) $country_name = $cn;
}

// Fallback if geoip extension is not present or returns unknown
if ($country_code === "UN" || $country_code === "" || $country_name === "Unknown") {
  // Skip localhost/private ranges
  $is_private = false;
  if ($ip === "127.0.0.1" || $ip === "::1") $is_private = true;
  if (preg_match('/^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[0-1])\.)/', $ip)) $is_private = true;

  if (!$is_private && function_exists('file_get_contents')) {
    $ctx = stream_context_create([
      'http' => [
        'timeout' => 2,
        'header' => "User-Agent: ECUPRATIX/1.0\r\n"
      ]
    ]);
    $json = @file_get_contents("https://ipwho.is/" . urlencode($ip), false, $ctx);
    if ($json) {
      $data = @json_decode($json, true);
      if (is_array($data) && !empty($data['success'])) {
        if (!empty($data['country_code'])) $country_code = strtoupper($data['country_code']);
        if (!empty($data['country'])) $country_name = $data['country'];
      }
    }
  }
}

function flag_url($cc){
  $cc = strtolower(trim($cc));
  if(strlen($cc) != 2) return "";
  return "https://flagcdn.com/24x18/" . $cc . ".png";
}

/* Packages (best-effort) */
$packs = $_SESSION["packs"] ?? ($_SESSION["packages"] ?? []);
if(!is_array($packs)) $packs = [];
$pack_defs = [
  "CAR" => "car",
  "TRUCK" => "truck",
  "TRACTOR" => "tractor",
  "MACHINERY" => "machinery",
  "FULL" => "full"
];

/* DTC daily limit (best-effort) */
$dtc_daily_total = (int)($_SESSION["dtc_daily_total"] ?? ($_SESSION["daily_limit_total"] ?? 0));
$dtc_daily_used  = (int)($_SESSION["dtc_daily_used"] ?? ($_SESSION["daily_limit_used"] ?? 0));
$dtc_daily_left  = max(0, $dtc_daily_total - $dtc_daily_used);
?>
<aside class="ux-side">
  <div class="ux-usercard">
    <div class="ux-user-title">Kullanıcı Bilgileri</div>
    <div class="ux-usergrid">
      <div class="ug"><span class="k">K. Adı</span><span class="v"><?= htmlspecialchars($user_name) ?></span></div>
      <div class="ug"><span class="k">Dongle</span><span class="v"><?= htmlspecialchars($dongle) ?></span></div>
      <div class="ug"><span class="k">Abonelik</span><span class="v"><?= htmlspecialchars($sub_end) ?></span></div>
      <div class="ug"><span class="k">IP</span><span class="v"><?= htmlspecialchars($ip) ?></span></div>
      <div class="ug"><span class="k">Ülke</span><span class="v"><?php $fu = flag_url($country_code); if($fu): ?><img class="ux-flag" src="<?= htmlspecialchars($fu) ?>" alt="<?= htmlspecialchars($country_code) ?>" loading="lazy" /><?php endif; ?><?= htmlspecialchars($country_name) ?></span></div>
    </div>

    <!-- DTC DAILY LIMIT (moved into user info) -->
    <div class="ux-dtclimit in-user">
      <div class="ux-pack-title">DTC Günlük Limit</div>
      <div class="ux-limitbar">
        <div class="bar">
          <?php $pct = ($dtc_daily_total>0) ? min(100, round(($dtc_daily_left/$dtc_daily_total)*100)) : 0; ?>
          <div class="fill" style="width: <?= $pct ?>%"></div>
        </div>
        <div class="ux-limitmeta">
          <span>Kalan</span>
          <b><?= (int)$dtc_daily_left ?></b>
          <span>/ <?= (int)$dtc_daily_total ?></span>
        </div>
      </div>
    </div>
  </div>

  <?php
    // Demo: Bekleyen biletler (son 5)
    $tickets = [
      ["id"=>"TCK-1042", "title"=>"Stage1 talebi", "status"=>"WAITING", "updated"=>"2026-02-03"],
      ["id"=>"TCK-1041", "title"=>"DTC listesini kontrol", "status"=>"OPEN", "updated"=>"2026-02-02"],
      ["id"=>"TCK-1039", "title"=>"EGR/DPF opsiyon sorusu", "status"=>"REPLY", "updated"=>"2026-02-01"],
      ["id"=>"TCK-1036", "title"=>"Dosya indirilemiyor", "status"=>"WAITING", "updated"=>"2026-01-31"],
      ["id"=>"TCK-1032", "title"=>"Yeni ECU ekleme", "status"=>"OPEN", "updated"=>"2026-01-30"],
    ];
  ?>
  <div class="ux-tickets">
    <div class="ux-tickets-h">
      <div class="ux-tickets-title">Bekleyen Biletler</div>
      <div class="ux-tickets-sub">Son 5</div>
    </div>
    <div class="ux-tickets-list">
      <?php foreach($tickets as $t){
        $st = strtoupper((string)$t['status']);
        $cls = 'open';
        if($st==='WAITING') $cls='waiting';
        if($st==='REPLY') $cls='reply';
      ?>
      <div class="ux-ticket">
        <div class="ux-ticket-top">
          <div class="ux-ticket-id"><?= htmlspecialchars($t['id']) ?></div>
          <div class="ux-ticket-badge <?= $cls ?>"><?= htmlspecialchars($st) ?></div>
        </div>
        <div class="ux-ticket-title"><?= htmlspecialchars($t['title']) ?></div>
        <div class="ux-ticket-meta">Son güncelleme: <b><?= htmlspecialchars($t['updated']) ?></b></div>
      </div>
      <?php } ?>
    </div>
  </div>

  <div class="ux-foot"><div class="ux-redline"></div></div>
</aside>
