<?php
$languages = tableExists($conn,'languages') ? $conn->query("SELECT * FROM languages ORDER BY is_default DESC, name ASC") : null;
$selected_language_id = (int)($_GET['language_id'] ?? 0);
if (!$selected_language_id && $languages) {
    $firstLang = $languages->fetch_assoc();
    $selected_language_id = (int)($firstLang['id'] ?? 0);
    if ($languages) $languages->data_seek(0);
}
$group_filter = trim($_GET['group'] ?? '');
$search_filter = trim($_GET['q'] ?? '');
$where = [];
if ($group_filter !== '') $where[] = "tk.group_name='".$conn->real_escape_string($group_filter)."'";
if ($search_filter !== '') {
    $q = $conn->real_escape_string('%'.$search_filter.'%');
    $where[] = "(tk.`key` LIKE '$q' OR tk.description LIKE '$q' OR tr.value LIKE '$q')";
}
$whereSql = $where ? 'WHERE '.implode(' AND ', $where) : '';
$groups = tableExists($conn,'translation_keys') ? $conn->query("SELECT DISTINCT group_name FROM translation_keys ORDER BY group_name ASC") : null;
$translations = null;
if ($selected_language_id && tableExists($conn,'translation_keys')) {
    $translations = $conn->query("SELECT tk.id, tk.`key`, tk.group_name, tk.description, COALESCE(tr.value,'') value
        FROM translation_keys tk
        LEFT JOIN translations tr ON tr.key_id=tk.id AND tr.language_id=$selected_language_id
        $whereSql
        ORDER BY tk.group_name ASC, tk.`key` ASC
        LIMIT 1000");
}
?>
<div class="tab-pane <?= ($requested_tab === 'languages') ? 'active' : '' ?>" id="tab-languages">
  <div class="card" style="padding:20px;margin-bottom:16px">
    <div class="card-header" style="display:flex;align-items:center;justify-content:space-between;gap:12px">
      <div>
        <h3 style="margin:0"><?php _e('languages.title','Languages'); ?></h3>
        <p class="text-muted" style="margin:4px 0 0"><?php _e('languages.help','Add any language and translate the whole system from database without changing code.'); ?></p>
      </div>
    </div>

    <form method="post" action="handlers/languages.php" style="display:grid;grid-template-columns:120px 1fr 130px 140px;gap:10px;align-items:end;margin-top:16px">
      <input type="hidden" name="action" value="add_language">
      <div><label><?php _e('languages.code','Code'); ?></label><input class="form-control" name="code" placeholder="fr" required></div>
      <div><label><?php _e('languages.name','Name'); ?></label><input class="form-control" name="name" placeholder="Français" required></div>
      <div><label><?php _e('languages.direction','Direction'); ?></label><select class="form-control" name="direction"><option value="ltr">LTR</option><option value="rtl">RTL</option></select></div>
      <button class="btn btn-primary" type="submit"><?php _e('languages.add_language','Add Language'); ?></button>
    </form>
  </div>

  <div class="card" style="padding:20px;margin-bottom:16px">
    <h3 style="margin-top:0"><?php _e('languages.available_languages','Available Languages'); ?></h3>
    <div class="table-responsive">
      <table class="table">
        <thead><tr><th><?php _e('languages.code','Code'); ?></th><th><?php _e('languages.name','Name'); ?></th><th><?php _e('languages.direction','Direction'); ?></th><th><?php _e('languages.default','Default'); ?></th><th><?php _e('languages.status','Status'); ?></th><th></th></tr></thead>
        <tbody>
        <?php if ($languages): while($lng = $languages->fetch_assoc()): ?>
          <tr>
            <td><?= htmlspecialchars($lng['code']) ?></td>
            <td><?= htmlspecialchars($lng['name']) ?></td>
            <td><?= htmlspecialchars(strtoupper($lng['direction'])) ?></td>
            <td><?= !empty($lng['is_default']) ? '✓' : '' ?></td>
            <td><?= !empty($lng['status']) ? htmlspecialchars(__('languages.active','Active')) : htmlspecialchars(__('languages.inactive','Inactive')) ?></td>
            <td style="text-align:right">
              <?php if (empty($lng['is_default'])): ?>
              <form method="post" action="handlers/languages.php" style="display:inline">
                <input type="hidden" name="action" value="set_default"><input type="hidden" name="id" value="<?= (int)$lng['id'] ?>">
                <button class="btn btn-sm" type="submit"><?php _e('languages.set_default','Set Default'); ?></button>
              </form>
              <?php endif; ?>
              <a class="btn btn-sm btn-primary" href="index.php?page=settings&tab=languages&language_id=<?= (int)$lng['id'] ?>"><?php _e('languages.translate','Translate'); ?></a>
            </td>
          </tr>
        <?php endwhile; endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card" style="padding:20px">
    <h3 style="margin-top:0"><?php _e('languages.translation_manager','Translation Manager'); ?></h3>
    <form method="get" action="index.php" style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px">
      <input type="hidden" name="page" value="settings"><input type="hidden" name="tab" value="languages">
      <select class="form-control" name="language_id" style="max-width:220px">
        <?php $lngList = $conn->query("SELECT * FROM languages ORDER BY is_default DESC, name ASC"); while($l=$lngList->fetch_assoc()): ?>
        <option value="<?= (int)$l['id'] ?>" <?= $selected_language_id===(int)$l['id']?'selected':'' ?>><?= htmlspecialchars($l['name']) ?></option>
        <?php endwhile; ?>
      </select>
      <select class="form-control" name="group" style="max-width:180px"><option value=""><?php _e('languages.all_groups','All groups'); ?></option><?php if($groups): while($g=$groups->fetch_assoc()): $gn=$g['group_name']; ?><option value="<?= htmlspecialchars($gn) ?>" <?= $group_filter===$gn?'selected':'' ?>><?= htmlspecialchars($gn ?: 'general') ?></option><?php endwhile; endif; ?></select>
      <input class="form-control" name="q" value="<?= htmlspecialchars($search_filter) ?>" placeholder="<?php _e('buttons.search','Search'); ?>" style="max-width:240px">
      <button class="btn" type="submit"><?php _e('buttons.filter','Filter'); ?></button>
    </form>
    <form method="post" action="handlers/languages.php">
      <input type="hidden" name="action" value="save_translations">
      <input type="hidden" name="language_id" value="<?= (int)$selected_language_id ?>">
      <div class="table-responsive" style="max-height:650px;overflow:auto">
        <table class="table">
          <thead><tr><th style="width:120px"><?php _e('languages.group','Group'); ?></th><th style="width:260px"><?php _e('languages.key','Key'); ?></th><th><?php _e('languages.english_fallback','English / Fallback'); ?></th><th><?php _e('languages.translation','Translation'); ?></th></tr></thead>
          <tbody>
          <?php if($translations): while($tr=$translations->fetch_assoc()): ?>
            <tr>
              <td><?= htmlspecialchars($tr['group_name']) ?></td>
              <td><code><?= htmlspecialchars($tr['key']) ?></code></td>
              <td><?= htmlspecialchars($tr['description']) ?></td>
              <td><input class="form-control" name="translations[<?= (int)$tr['id'] ?>]" value="<?= htmlspecialchars($tr['value']) ?>"></td>
            </tr>
          <?php endwhile; endif; ?>
          </tbody>
        </table>
      </div>
      <button class="btn btn-primary" type="submit" style="margin-top:14px"><?php _e('languages.save_translations','Save Translations'); ?></button>
    </form>
  </div>
</div>
