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

session_start();
require_once '../includes/db.php';

if (!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

function get_templates($dir) {
    $templates = [];
    if (is_dir($dir)) {
        foreach (scandir($dir) as $entry) {
            if ($entry !== '.' && $entry !== '..' && is_dir("$dir/$entry")) {
                $templates[] = $entry;
            }
        }
    }
    return $templates;
}

$templates_dir = __DIR__ . '/../templates';
$available = get_templates($templates_dir);

$stmt = $pdo->query("SELECT template_name FROM settings LIMIT 1");
$current_template = $stmt->fetchColumn() ?: 'migamex';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['template'])) {
    $selected = $_POST['template'];
    if (in_array($selected, $available)) {
        $stmt = $pdo->prepare("UPDATE settings SET template_name = ?");
        $stmt->execute([$selected]);
        $current_template = $selected;
        $message = "✔ تم اختيار القالب: " . htmlspecialchars($selected);
    } else {
        $message = "❌ القالب غير موجود.";
    }
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
  <meta charset="UTF-8">
  <title>إعدادات القالب</title>
</head>
<body>
  <h2>اختيار القالب</h2>
  <?php if ($message): ?><p><?= $message ?></p><?php endif; ?>
  <form method="post">
    <select name="template">
      <?php foreach ($available as $tpl): ?>
        <option value="<?= htmlspecialchars($tpl) ?>" <?= $tpl === $current_template ? 'selected' : '' ?>>
          <?= htmlspecialchars($tpl) ?>
        </option>
      <?php endforeach; ?>
    </select>
    <button type="submit">💾 حفظ</button>
  </form>
</body>
</html>
