<?php
// admin/homepage.php - Manage Homepage Content
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();

$db = get_db();
$message = '';
$error = '';

// Create table if not exists
try {
  $db->exec("CREATE TABLE IF NOT EXISTS homepage_sections (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    section_key TEXT UNIQUE NOT NULL,
    title TEXT,
    subtitle TEXT,
    description TEXT,
    button_text TEXT,
    button_link TEXT,
    status TEXT DEFAULT 'active',
    display_order INTEGER DEFAULT 0,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )");
  
  $db->exec("CREATE TABLE IF NOT EXISTS homepage_features (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    icon TEXT,
    title TEXT NOT NULL,
    description TEXT,
    link TEXT,
    color TEXT DEFAULT 'primary',
    display_order INTEGER DEFAULT 0,
    status TEXT DEFAULT 'active',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )");
} catch (Exception $e) {
  // Tables already exist
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $action = $_POST['action'] ?? '';
  
  if ($action === 'update_about') {
    $title = trim($_POST['about_title'] ?? '');
    $subtitle = trim($_POST['about_subtitle'] ?? '');
    $description = trim($_POST['about_description'] ?? '');
    $button_text = trim($_POST['about_button_text'] ?? '');
    $button_link = trim($_POST['about_button_link'] ?? '');
    
    try {
      $stmt = $db->prepare("INSERT OR REPLACE INTO homepage_sections (section_key, title, subtitle, description, button_text, button_link) VALUES (?, ?, ?, ?, ?, ?)");
      $stmt->execute(['about', $title, $subtitle, $description, $button_text, $button_link]);
      $message = 'About section berhasil diupdate!';
    } catch (Exception $e) {
      $error = 'Gagal update: ' . $e->getMessage();
    }
  }
  
  if ($action === 'add_feature') {
    $icon = trim($_POST['feature_icon'] ?? '');
    $title = trim($_POST['feature_title'] ?? '');
    $description = trim($_POST['feature_description'] ?? '');
    $link = trim($_POST['feature_link'] ?? '');
    $color = trim($_POST['feature_color'] ?? 'primary');
    $order = (int)($_POST['feature_order'] ?? 0);
    
    try {
      $stmt = $db->prepare("INSERT INTO homepage_features (icon, title, description, link, color, display_order) VALUES (?, ?, ?, ?, ?, ?)");
      $stmt->execute([$icon, $title, $description, $link, $color, $order]);
      $message = 'Feature berhasil ditambahkan!';
    } catch (Exception $e) {
      $error = 'Gagal menambahkan: ' . $e->getMessage();
    }
  }
  
  if ($action === 'delete_feature') {
    $id = (int)$_POST['feature_id'];
    try {
      $stmt = $db->prepare("DELETE FROM homepage_features WHERE id = ?");
      $stmt->execute([$id]);
      $message = 'Feature berhasil dihapus!';
    } catch (Exception $e) {
      $error = 'Gagal menghapus: ' . $e->getMessage();
    }
  }
}

// Load about section
$stmt = $db->prepare("SELECT * FROM homepage_sections WHERE section_key = ?");
$stmt->execute(['about']);
$about = $stmt->fetch(PDO::FETCH_ASSOC);

// Load features
$features = $db->query("SELECT * FROM homepage_features ORDER BY display_order ASC, id DESC")->fetchAll(PDO::FETCH_ASSOC);

require '_header.php';
?>

<div class="row">
  <div class="col-12">
    <?php if ($message): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <?php echo e($message); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>
    <?php if ($error): ?>
      <div class="alert alert-danger alert-dismissible fade show">
        <?php echo e($error); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>
  </div>
</div>

<!-- About Section -->
<div class="row mb-4">
  <div class="col-12">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0"><i class="fa fa-info-circle"></i> About Section</h5>
      </div>
      <div class="card-body">
        <form method="post">
          <input type="hidden" name="action" value="update_about">
          
          <div class="mb-3">
            <label class="form-label">Badge Title</label>
            <input type="text" name="about_subtitle" class="form-control" value="<?php echo e($about['subtitle'] ?? 'Tentang Kami'); ?>" placeholder="Tentang Kami">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Main Title <span class="text-danger">*</span></label>
            <input type="text" name="about_title" class="form-control" value="<?php echo e($about['title'] ?? 'Membangun Generasi Unggul dan Berkarakter'); ?>" required>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="about_description" class="form-control" rows="4"><?php echo e($about['description'] ?? 'Kami berkomitmen untuk mendukung pendidikan yang berkualitas dan memberikan peluang bagi setiap siswa untuk berkembang.'); ?></textarea>
          </div>
          
          <div class="row">
            <div class="col-md-6 mb-3">
              <label class="form-label">Button Text</label>
              <input type="text" name="about_button_text" class="form-control" value="<?php echo e($about['button_text'] ?? 'Selengkapnya'); ?>">
            </div>
            <div class="col-md-6 mb-3">
              <label class="form-label">Button Link</label>
              <input type="text" name="about_button_link" class="form-control" value="<?php echo e($about['button_link'] ?? base_url() . '/public/about.php'); ?>">
            </div>
          </div>
          
          <button type="submit" class="btn btn-primary">
            <i class="fa fa-save"></i> Simpan About Section
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<!-- Features / Quick Links -->
<div class="row">
  <div class="col-md-4">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">Tambah Feature</h5>
      </div>
      <div class="card-body">
        <form method="post">
          <input type="hidden" name="action" value="add_feature">
          
          <div class="mb-3">
            <label class="form-label">Icon (FontAwesome) <span class="text-danger">*</span></label>
            <input type="text" name="feature_icon" class="form-control" placeholder="fa-book" required>
            <small class="text-muted">Contoh: fa-book, fa-users, fa-phone</small>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Title <span class="text-danger">*</span></label>
            <input type="text" name="feature_title" class="form-control" required>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Description</label>
            <textarea name="feature_description" class="form-control" rows="3"></textarea>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Link</label>
            <input type="text" name="feature_link" class="form-control" placeholder="/public/page.php">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Color</label>
            <select name="feature_color" class="form-select">
              <option value="primary">Primary (Blue)</option>
              <option value="success">Success (Green)</option>
              <option value="warning">Warning (Yellow)</option>
              <option value="info">Info (Cyan)</option>
              <option value="danger">Danger (Red)</option>
            </select>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Display Order</label>
            <input type="number" name="feature_order" class="form-control" value="0">
          </div>
          
          <button type="submit" class="btn btn-primary w-100">
            <i class="fa fa-plus"></i> Tambah Feature
          </button>
        </form>
      </div>
    </div>
  </div>
  
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">Daftar Features</h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-hover">
            <thead>
              <tr>
                <th>Icon</th>
                <th>Title</th>
                <th>Description</th>
                <th>Color</th>
                <th>Order</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($features)): ?>
                <tr>
                  <td colspan="6" class="text-center">Belum ada feature</td>
                </tr>
              <?php else: ?>
                <?php foreach ($features as $f): ?>
                  <tr>
                    <td><i class="fa <?php echo e($f['icon']); ?> fa-2x text-<?php echo e($f['color']); ?>"></i></td>
                    <td><strong><?php echo e($f['title']); ?></strong></td>
                    <td><small><?php echo e(mb_substr($f['description'], 0, 50)); ?>...</small></td>
                    <td><span class="badge bg-<?php echo e($f['color']); ?>"><?php echo e($f['color']); ?></span></td>
                    <td><?php echo $f['display_order']; ?></td>
                    <td>
                      <form method="post" class="d-inline" onsubmit="return confirm('Yakin ingin menghapus?')">
                        <input type="hidden" name="action" value="delete_feature">
                        <input type="hidden" name="feature_id" value="<?php echo $f['id']; ?>">
                        <button type="submit" class="btn btn-sm btn-danger">
                          <i class="fa fa-trash"></i>
                        </button>
                      </form>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

<?php require '_footer.php'; ?>
