<?php
// --- اتصال به دیتابیس ---
$host = "localhost";
$db   = "tabrizli_arkbam";
$user = "tabrizli_arkbamuser";
$pass = "01478520Mi!!";
$charset = "utf8mb4";
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
];
try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

$lang = $_GET['lang'] ?? 'fa';

// گرفتن متن‌ها بر اساس کد
function getMessageByCode(PDO $pdo, string $lang, string $code): ?array {
    $sql = "
        SELECT tr.Title, tr.Body
        FROM MessageTemplate mt
        JOIN MessageTemplateTranslation tr 
            ON mt.MessageID = tr.MessageID
        WHERE tr.LanguageCode = :lang
          AND mt.Code = :code
        LIMIT 1
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        'lang' => $lang,
        'code' => $code
    ]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}

// گرفتن لوگو
$stmt = $pdo->query("SELECT FileName FROM SiteLogo ORDER BY LogoID DESC LIMIT 1");
$logo = $stmt->fetchColumn();

// گرفتن دسته‌ها
$stmt = $pdo->prepare("
    SELECT c.CategoryID, c.ParentID, c.Level, t.Name, c.SortOrder
    FROM Category c
    JOIN CategoryTranslation t ON c.CategoryID = t.CategoryID
    WHERE t.LanguageCode = :lang
    ORDER BY c.Level, c.SortOrder
");
$stmt->execute(['lang' => $lang]);
$categories = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE);

// گرفتن آیتم‌ها
$stmt = $pdo->prepare("
    SELECT i.ItemID, i.CategoryID, i.Price, i.Image, t.Description
    FROM ItemDetail i
    LEFT JOIN ItemDetailTranslation t ON i.ItemID = t.ItemID AND t.LanguageCode = :lang
");
$stmt->execute(['lang' => $lang]);
$items = $stmt->fetchAll();
$itemByCategory = [];
foreach ($items as $it) {
    $itemByCategory[$it['CategoryID']][] = $it;
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang) ?>" dir="rtl">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>کافه بام ارک</title>
  <link rel="stylesheet" href="css/arkbam.css?v=1.3">
</head>
<body>
<main class="main-class class-custom">
  <!-- Logo -->
  <div id="logo" class="logo-class">
    <?php if ($logo): ?>
      <img src="logo/<?= htmlspecialchars($logo) ?>" alt="لوگو" width="120">
    <?php endif; ?>
  </div>
  
  <!-- زبان‌ها -->
  <div class="mb-3">
    <a href="?lang=fa">فارسی</a> |
    <a href="?lang=en">English</a> |
    <a href="?lang=tr">Türkçe</a> |
    <a href="?lang=ar">العربية</a>
  </div>

  <!-- Info text (کد 1) -->
  <div id="text-info1" class="text-info-class">
    <?= htmlspecialchars((getMessageByCode($pdo, $lang, '1')['Body'] ?? 'متنی ثبت نشده است')) ?>
  </div>

  <?php
  foreach ($categories as $catID => $cat) {
      if ($cat['Level'] == 1) {
          echo "<div class='level1 level1-{$catID}'>
                  <h4>".htmlspecialchars($cat['Name'])."</h4>";

          echo "<div class='tabs tabs-parent-{$catID}'>";
          echo "<div class='tab-buttons'>";
          foreach ($categories as $subID => $sub) {
              if ($sub['Level']==2 && $sub['ParentID']==$catID) {
                  echo "<button class='tab-btn tab-btn-{$subID}' data-tab='tab$subID'>".htmlspecialchars($sub['Name'])."</button>";
              }
          }
          echo "</div>";

          foreach ($categories as $subID => $sub) {
              if ($sub['Level']==2 && $sub['ParentID']==$catID) {
                  echo "<div id='tab$subID' class='tab-content tab-content-{$subID}'>
                          <button class='close-tab' data-target='tab$subID'>&times;</button>";
                         echo "<h5>".htmlspecialchars($sub['Name'])."</h5>";

                  foreach ($categories as $sub2ID => $sub2) {
                      if ($sub2['Level']==3 && $sub2['ParentID']==$subID) {
                          
                          if (isset($itemByCategory[$sub2ID])) {
                              echo "<ul class='item-list'>";
                              foreach ($itemByCategory[$sub2ID] as $it) {
                                  echo "<li class='item'>";
                                  
                                  // فقط وقتی عکس وجود داشته باشه
                                  if (!empty($it['Image'])) {
                                      $img = htmlspecialchars($it['Image']);
                                      echo "<div class='item-left'>
                                              <img class='item-img' src='Uploads/{$img}' alt=''>
                                            </div>";
                                  }

                                  echo "<div class='item-right'>
                                          <div class='item-top'>
                                            <span class='item-name'>".htmlspecialchars($sub2['Name'])."</span>
                                            <span class='price'>".number_format($it['Price'] ?? 0)." 
                                            <span class='toman'> هزارتومان</span>
                                            </span>

                                          </div>
                                          <div class='item-desc'>".htmlspecialchars($it['Description'] ?? '')."</div>
                                        </div>
                                        </li>";
                              }
                              echo "</ul>";
                          }
                      }
                  }
                  echo "</div>";
              }
          }
          echo "</div></div>";
      }
  }
  ?>

  <!-- Copyright info (کد 2) -->
  <div id="text-copyright" class="text-copyright-class">
    <?= htmlspecialchars((getMessageByCode($pdo, $lang, '2')['Body'] ?? 'متنی ثبت نشده است')) ?>
  </div>
</main>

<script>
document.addEventListener("DOMContentLoaded", () => {
  const buttons = document.querySelectorAll(".tab-btn");
  const contents = document.querySelectorAll(".tab-content");
  const closeBtns = document.querySelectorAll(".close-tab");

  buttons.forEach(btn => {
    btn.addEventListener("click", () => {
      buttons.forEach(b => b.classList.remove("active"));
      contents.forEach(c => c.classList.remove("active"));
      btn.classList.add("active");
      document.getElementById(btn.dataset.tab).classList.add("active");
    });
  });

  closeBtns.forEach(close => {
    close.addEventListener("click", () => {
      const target = document.getElementById(close.dataset.target);
      if (target) target.classList.remove("active");
      buttons.forEach(b => b.classList.remove("active"));
    });
  });
});
</script>
</body>
</html>
