<?php

namespace App\Controllers;

use Core\Database;
use PDO;

class AddMahasiswaController
{
    private $db;

    public function __construct()
    {
        $this->db = Database::getConnection();
    }
    
    public function index()
    {
        // Ambil data kurikulum untuk dropdown
        $stmt = $this->db->query("SELECT id_kurikulum, nama_kurikulum FROM tb_kurikulum");
        $kurikulums = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
        // Cek keyword pencarian
        $search = isset($_GET['search']) ? trim($_GET['search']) : '';
    
        // Siapkan query mahasiswa
        if (!empty($search)) {
            $query = "SELECT m.nim, m.nama, m.id_prodi, k.nama_kurikulum 
                      FROM tb_mahasiswa m
                      LEFT JOIN tb_kurikulum k ON m.id_kurikulum = k.id_kurikulum
                      WHERE m.nim LIKE :search OR m.nama LIKE :search
                      ORDER BY m.nim ASC LIMIT 20";
            $stmt2 = $this->db->prepare($query);
            $stmt2->execute(['search' => "%$search%"]);
        } else {
            $query = "SELECT m.nim, m.nama, m.id_prodi, k.nama_kurikulum 
                      FROM tb_mahasiswa m
                      LEFT JOIN tb_kurikulum k ON m.id_kurikulum = k.id_kurikulum
                      ORDER BY m.nim ASC LIMIT 20";
            $stmt2 = $this->db->query($query);
        }
    
        $mahasiswa = $stmt2->fetchAll(PDO::FETCH_ASSOC);
    
        require_once __DIR__ . '/../Views/admin/add_mahasiswa.php';
    }

    public function store()
    {
        $nim            = $_POST['nim'];
        $id_prodi       = $_POST['id_prodi'];
        $nama           = $_POST['nama'];
        $alamat         = $_POST['alamat'];
        $telpon         = $_POST['telpon'];
        $tempat_lahir   = $_POST['tempat_lahir'];
        $tgl_lahir      = $_POST['tgl_lahir'];
        $agama          = $_POST['agama'];
        $jenis_kelamin  = $_POST['jenis_kelamin'];
        $tahun_masuk    = $_POST['tahun_masuk'];
        $id_kurikulum   = $_POST['id_kurikulum'];

        // Insert ke tb_mahasiswa
        $stmt = $this->db->prepare("INSERT INTO tb_mahasiswa (nim, id_prodi, nama, alamat, telpon, 	tmpt_lahir, tgl_lahir, agama, jenis_kelamin, tahun_masuk, id_kurikulum)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$nim, $id_prodi, $nama, $alamat, $telpon, $tempat_lahir, $tgl_lahir, $agama, $jenis_kelamin, $tahun_masuk, $id_kurikulum]);

        // Insert ke tb_user
        $username = $nim;
        $password = md5('mahasiswa');
        $level = 'Mahasiswa';
        $stmt = $this->db->prepare("INSERT INTO tb_user (nama, username, password, level) VALUES (?, ?, ?, ?)");
        $stmt->execute([$nama, $username, $password, $level]);

        header("Location: /dashboard/admin-add_mahasiswa?success=1");
        exit();
    }
}
