<?php

namespace App\Controllers;

class Jurusan extends BaseController
{
    /**
     * Tampilan Publik
     */
    public function index($slug)
    {
        $db = \Config\Database::connect();
        $jurusan = $db->table('jurusan')->where('slug', $slug)->get()->getRowArray();

        if (!$jurusan) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound("Jurusan $slug tidak ditemukan.");
        }

        $data = [
            'title'   => $jurusan['nama_jurusan'] . ' - SMKN 1 Sukalarang',
            'jurusan' => $jurusan
        ];

        return view('jurusan_detail', $data);
    }

    /**
     * Form Edit Admin
     */
    public function edit($slug)
    {
        if (!session()->get('isLoggedIn')) {
            return redirect()->to(base_url('login'))->with('error', 'Silakan login terlebih dahulu.');
        }

        $db = \Config\Database::connect();
        $jurusan = $db->table('jurusan')->where('slug', $slug)->get()->getRowArray();

        $data = [
            'title'   => 'Edit Jurusan ' . $jurusan['nama_jurusan'],
            'jurusan' => $jurusan
        ];

        return view('admin/edit_jurusan', $data);
    }

    /**
     * Proses Simpan & Upload Gambar
     */
    public function update()
    {
        if (!session()->get('isLoggedIn')) return redirect()->to(base_url('login'));

        $db = \Config\Database::connect();
        $id = $this->request->getPost('id_jurusan');
        $slug = $this->request->getPost('slug');

        // Ambil data lama untuk keperluan hapus file lama jika diganti
        $oldData = $db->table('jurusan')->where('id_jurusan', $id)->get()->getRowArray();

        $dataUpdate = [
            'nama_jurusan' => $this->request->getPost('nama_jurusan'),
            'kaprog'       => $this->request->getPost('kaprog'),
            'deskripsi'    => $this->request->getPost('deskripsi'),
            'visi_jurusan' => $this->request->getPost('visi_jurusan'),
            'misi_jurusan' => $this->request->getPost('misi_jurusan'),
            'guru_produktif' => $this->request->getPost('guru_produktif'),
        ];

        // --- LOGIKA UPLOAD LOGO JURUSAN ---
        $fileLogo = $this->request->getFile('logo_jurusan');
        if ($fileLogo->isValid() && !$fileLogo->hasMoved()) {
            $newNameLogo = $fileLogo->getRandomName();
            $fileLogo->move('assets/img/jurusan/', $newNameLogo);
            
            $dataUpdate['logo_jurusan'] = $newNameLogo;

            // Hapus file lama jika bukan default
            if ($oldData['logo_jurusan'] && file_exists('assets/img/jurusan/' . $oldData['logo_jurusan'])) {
                @unlink('assets/img/jurusan/' . $oldData['logo_jurusan']);
            }
        }

        // --- LOGIKA UPLOAD FOTO KEGIATAN ---
        $fileKegiatan = $this->request->getFile('foto_kegiatan');
        if ($fileKegiatan->isValid() && !$fileKegiatan->hasMoved()) {
            $newNameKegiatan = $fileKegiatan->getRandomName();
            $fileKegiatan->move('assets/img/kegiatan/', $newNameKegiatan);
            
            $dataUpdate['foto_kegiatan'] = $newNameKegiatan;

            // Hapus file lama jika ada
            if ($oldData['foto_kegiatan'] && file_exists('assets/img/kegiatan/' . $oldData['foto_kegiatan'])) {
                @unlink('assets/img/kegiatan/' . $oldData['foto_kegiatan']);
            }
        }

        // Eksekusi Update ke Database
        $db->table('jurusan')->where('id_jurusan', $id)->update($dataUpdate);

        return redirect()->to(base_url('jurusan/' . $slug))->with('success', 'Data dan Gambar berhasil diperbarui!');
    }
    public function list_admin()
{
    // Pastikan hanya yang login bisa akses
    if (!session()->get('isLoggedIn')) return redirect()->to(base_url('login'));

    $db = \Config\Database::connect();
    $data = [
        'title'   => 'Manajemen Konten Jurusan',
        'jurusan' => $db->table('jurusan')->get()->getResultArray() // Ambil semua jurusan
    ];

    // Kita arahkan ke view baru khusus daftar edit
    return view('admin/list_jurusan', $data); 
}
// Tambahkan di app/Controllers/Jurusan.php

public function admin_index()
{
    // Cek Login
    if (!session()->get('isLoggedIn')) {
        return redirect()->to(base_url('login'));
    }

    $db = \Config\Database::connect();
    $data = [
        'title'   => 'Pilih Jurusan untuk Diedit',
        'jurusan' => $db->table('jurusan')->get()->getResultArray()
    ];

    return view('admin/jurusan_list', $data);
}
// Tambahkan fungsi ini di dalam class Jurusan Bapak

public function upload_galeri()
{
    if (!session()->get('isLoggedIn')) return redirect()->to(base_url('login'));

    $id_jurusan = $this->request->getPost('id_jurusan');
    $slug = $this->request->getPost('slug');
    $files = $this->request->getFileMultiple('galeri_foto');

    $db = \Config\Database::connect();

    foreach ($files as $file) {
        if ($file->isValid() && !$file->hasMoved()) {
            $newName = $file->getRandomName();
            $file->move('assets/img/kegiatan/', $newName);

            // Simpan ke tabel galeri
            $db->table('jurusan_galeri')->insert([
                'id_jurusan' => $id_jurusan,
                'foto'       => $newName
            ]);
        }
    }

    return redirect()->to(base_url('admin/jurusan/edit/' . $slug))->with('success', 'Galeri foto berhasil ditambahkan!');
}

public function hapus_foto_galeri($id_foto, $slug)
{
    $db = \Config\Database::connect();
    $foto = $db->table('jurusan_galeri')->where('id_galeri', $id_foto)->get()->getRowArray();

    if ($foto) {
        if (file_exists('assets/img/kegiatan/' . $foto['foto'])) {
            @unlink('assets/img/kegiatan/' . $foto['foto']);
        }
        $db->table('jurusan_galeri')->where('id_galeri', $id_foto)->delete();
    }

    return redirect()->to(base_url('admin/jurusan/edit/' . $slug))->with('success', 'Foto berhasil dihapus!');
}
}