<?php
// admin/kurikulum.php - CRUD Kurikulum
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 = '';

// Auto-create table if not exists
try {
  $db->exec("CREATE TABLE IF NOT EXISTS kurikulum (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    judul TEXT NOT NULL,
    deskripsi TEXT,
    tingkat TEXT,
    jurusan TEXT,
    mata_pelajaran TEXT,
    kompetensi_dasar TEXT,
    materi_pokok TEXT,
    file_dokumen TEXT,
    urutan INTEGER DEFAULT 0,
    status TEXT DEFAULT 'aktif',
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
    updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )");
} catch (Exception $e) {
  // Table already exists or other error
}

// Handle Delete
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];
  try {
    // Delete file if exists
    $stmt = $db->prepare("SELECT file_dokumen FROM kurikulum WHERE id = ?");
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($row && $row['file_dokumen']) {
      $filePath = __DIR__ . '/../data/uploads/kurikulum/' . $row['file_dokumen'];
      if (file_exists($filePath)) {
        unlink($filePath);
      }
    }
    
    $stmt = $db->prepare("DELETE FROM kurikulum WHERE id = ?");
    $stmt->execute([$id]);
    $message = 'Kurikulum berhasil dihapus!';
  } catch (Exception $e) {
    $error = 'Gagal menghapus: ' . $e->getMessage();
  }
}

// Handle Add/Edit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
  $judul = trim($_POST['judul'] ?? '');
  $deskripsi = trim($_POST['deskripsi'] ?? '');
  $tingkat = trim($_POST['tingkat'] ?? '');
  $jurusan = trim($_POST['jurusan'] ?? '');
  $mata_pelajaran = trim($_POST['mata_pelajaran'] ?? '');
  $kompetensi_dasar = trim($_POST['kompetensi_dasar'] ?? '');
  $materi_pokok = trim($_POST['materi_pokok'] ?? '');
  $urutan = (int)($_POST['urutan'] ?? 0);
  $status = $_POST['status'] ?? 'aktif';
  
  $file_dokumen = '';
  
  // Handle file upload
  if (isset($_FILES['file_dokumen']) && $_FILES['file_dokumen']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . '/../data/uploads/kurikulum/';
    if (!is_dir($uploadDir)) {
      mkdir($uploadDir, 0755, true);
    }
    
    $fileName = time() . '_' . basename($_FILES['file_dokumen']['name']);
    $uploadFile = $uploadDir . $fileName;
    
    if (move_uploaded_file($_FILES['file_dokumen']['tmp_name'], $uploadFile)) {
      $file_dokumen = $fileName;
      
      // Delete old file if updating
      if ($id > 0) {
        $stmt = $db->prepare("SELECT file_dokumen FROM kurikulum WHERE id = ?");
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row && $row['file_dokumen']) {
          $oldFile = $uploadDir . $row['file_dokumen'];
          if (file_exists($oldFile)) {
            unlink($oldFile);
          }
        }
      }
    }
  }
  
  try {
    if ($id > 0) {
      // Update
      if ($file_dokumen) {
        $stmt = $db->prepare("UPDATE kurikulum SET judul=?, deskripsi=?, tingkat=?, jurusan=?, mata_pelajaran=?, kompetensi_dasar=?, materi_pokok=?, file_dokumen=?, urutan=?, status=? WHERE id=?");
        $stmt->execute([$judul, $deskripsi, $tingkat, $jurusan, $mata_pelajaran, $kompetensi_dasar, $materi_pokok, $file_dokumen, $urutan, $status, $id]);
      } else {
        $stmt = $db->prepare("UPDATE kurikulum SET judul=?, deskripsi=?, tingkat=?, jurusan=?, mata_pelajaran=?, kompetensi_dasar=?, materi_pokok=?, urutan=?, status=? WHERE id=?");
        $stmt->execute([$judul, $deskripsi, $tingkat, $jurusan, $mata_pelajaran, $kompetensi_dasar, $materi_pokok, $urutan, $status, $id]);
      }
      $message = 'Kurikulum berhasil diupdate!';
    } else {
      // Insert
      $stmt = $db->prepare("INSERT INTO kurikulum (judul, deskripsi, tingkat, jurusan, mata_pelajaran, kompetensi_dasar, materi_pokok, file_dokumen, urutan, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
      $stmt->execute([$judul, $deskripsi, $tingkat, $jurusan, $mata_pelajaran, $kompetensi_dasar, $materi_pokok, $file_dokumen, $urutan, $status]);
      $message = 'Kurikulum berhasil ditambahkan!';
    }
  } catch (Exception $e) {
    $error = 'Gagal menyimpan: ' . $e->getMessage();
  }
}

// Get data for edit
$editData = null;
if (isset($_GET['edit'])) {
  $id = (int)$_GET['edit'];
  $stmt = $db->prepare("SELECT * FROM kurikulum WHERE id = ?");
  $stmt->execute([$id]);
  $editData = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Get all kurikulum
$stmt = $db->query("SELECT * FROM kurikulum ORDER BY urutan ASC, id DESC");
$kurikulums = $stmt->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>

<div class="row">
  <div class="col-md-4">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0"><?php echo $editData ? 'Edit' : 'Tambah'; ?> Kurikulum</h5>
      </div>
      <div class="card-body">
        <form method="post" enctype="multipart/form-data">
          <?php if ($editData): ?>
            <input type="hidden" name="id" value="<?php echo $editData['id']; ?>">
          <?php endif; ?>
          
          <div class="mb-3">
            <label class="form-label">Judul <span class="text-danger">*</span></label>
            <input type="text" name="judul" class="form-control" value="<?php echo e($editData['judul'] ?? ''); ?>" required>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Deskripsi</label>
            <textarea name="deskripsi" class="form-control" rows="3"><?php echo e($editData['deskripsi'] ?? ''); ?></textarea>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Tingkat/Kelas</label>
            <input type="text" name="tingkat" class="form-control" value="<?php echo e($editData['tingkat'] ?? ''); ?>" placeholder="X, XI, XII">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Jurusan</label>
            <input type="text" name="jurusan" class="form-control" value="<?php echo e($editData['jurusan'] ?? ''); ?>" placeholder="TKJ, Multimedia, dll">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Mata Pelajaran</label>
            <input type="text" name="mata_pelajaran" class="form-control" value="<?php echo e($editData['mata_pelajaran'] ?? ''); ?>">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Kompetensi Dasar</label>
            <textarea name="kompetensi_dasar" class="form-control" rows="2"><?php echo e($editData['kompetensi_dasar'] ?? ''); ?></textarea>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Materi Pokok</label>
            <textarea name="materi_pokok" class="form-control" rows="2"><?php echo e($editData['materi_pokok'] ?? ''); ?></textarea>
          </div>
          
          <div class="mb-3">
            <label class="form-label">File Dokumen (PDF)</label>
            <input type="file" name="file_dokumen" class="form-control" accept=".pdf,.doc,.docx">
            <?php if ($editData && $editData['file_dokumen']): ?>
              <small class="text-muted">File saat ini: <?php echo e($editData['file_dokumen']); ?></small>
            <?php endif; ?>
          </div>
          
          <div class="mb-3">
            <label class="form-label">Urutan</label>
            <input type="number" name="urutan" class="form-control" value="<?php echo e($editData['urutan'] ?? 0); ?>">
          </div>
          
          <div class="mb-3">
            <label class="form-label">Status</label>
            <select name="status" class="form-select">
              <option value="aktif" <?php echo ($editData['status'] ?? 'aktif') === 'aktif' ? 'selected' : ''; ?>>Aktif</option>
              <option value="tidak_aktif" <?php echo ($editData['status'] ?? '') === 'tidak_aktif' ? 'selected' : ''; ?>>Tidak Aktif</option>
            </select>
          </div>
          
          <div class="d-grid gap-2">
            <button type="submit" class="btn btn-primary">
              <i class="fa fa-save"></i> Simpan
            </button>
            <?php if ($editData): ?>
              <a href="kurikulum.php" class="btn btn-secondary">
                <i class="fa fa-times"></i> Batal
              </a>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>
  </div>
  
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">
        <h5 class="card-title mb-0">Daftar Kurikulum</h5>
      </div>
      <div class="card-body">
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead>
              <tr>
                <th>No</th>
                <th>Judul</th>
                <th>Tingkat</th>
                <th>Jurusan</th>
                <th>Status</th>
                <th>Aksi</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($kurikulums)): ?>
                <tr>
                  <td colspan="6" class="text-center">Belum ada data kurikulum</td>
                </tr>
              <?php else: ?>
                <?php foreach ($kurikulums as $i => $k): ?>
                  <tr>
                    <td><?php echo $i + 1; ?></td>
                    <td>
                      <strong><?php echo e($k['judul']); ?></strong>
                      <?php if ($k['file_dokumen']): ?>
                        <br><small class="text-muted"><i class="fa fa-file"></i> <?php echo e($k['file_dokumen']); ?></small>
                      <?php endif; ?>
                    </td>
                    <td><?php echo e($k['tingkat']); ?></td>
                    <td><?php echo e($k['jurusan']); ?></td>
                    <td>
                      <span class="badge bg-<?php echo $k['status'] === 'aktif' ? 'success' : 'secondary'; ?>">
                        <?php echo ucfirst($k['status']); ?>
                      </span>
                    </td>
                    <td>
                      <a href="?edit=<?php echo $k['id']; ?>" class="btn btn-sm btn-warning" title="Edit">
                        <i class="fa fa-edit"></i>
                      </a>
                      <a href="?delete=<?php echo $k['id']; ?>" class="btn btn-sm btn-danger" 
                         onclick="return confirm('Yakin ingin menghapus?')" title="Hapus">
                        <i class="fa fa-trash"></i>
                      </a>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

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