<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Siswa extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        check_login();
        $this->load->model('Siswa_model');
        $this->load->model('Status_model');
        // helper & lib sudah dipakai di project, aman kalau mau:
        $this->load->helper(['url','form']);
        $this->load->library(['session','form_validation']);
    }

    /**
     * List semua siswa (yang sudah approve)
     */
   // controllers/Siswa.php

// public function index() {
//     check_role([1,2]);
//     $data['title'] = 'Kelola Siswa';

//     $keyword = $this->input->get('keyword');

//     // ambil list siswa
//     $siswa = $this->Siswa_model->get_all($keyword);

//     // === tambahkan ini ===
//     $this->load->model('PembayaranSiswa_model', 'ledger');
//     $this->load->model('Biaya_model', 'biaya');

//     // biaya resmi pelatihan (boleh 0 kalau belum diset)
//     $biaya   = $this->biaya->get_current('pelatihan');  // key = 'pelatihan'
//     $nominal = $biaya ? (float)$biaya->Nominal : 0.0;

//     foreach ($siswa as $s) {
//         // default kalau kosong
//         if (empty($s->NamaStatus)) $s->NamaStatus = 'Belum ditentukan';

//         // kalau belum punya SiswaID → calon
//         if (empty($s->SiswaID)) {
//             $s->NamaStatus = 'Calon';
//             continue;
//         }

//         // kalau status eksplisit “Ditolak”, jangan dihitung ulang
//         $is_ditolak = stripos((string)$s->NamaStatus, 'tolak') !== false || strtolower((string)$s->NamaStatus) === 'rejected';
//         if ($is_ditolak) continue;

//         // hitung bayar dinamis (hanya jenis Pelatihan)
//         $paid = (float)$this->ledger->sum_nominal_by_siswa($s->SiswaID, 'Pelatihan');

//         // set nama status dinamis, sama logika seperti halaman pembayaran
//         if ($nominal > 0 && $paid >= $nominal) {
//             $s->NamaStatus = 'Aktif';
//         } else {
//             $s->NamaStatus = 'Menunggu Pembayaran';
//         }
//     }
//     // === sampai sini ===

//     $data['siswa']   = $siswa;
//     $data['keyword'] = $keyword;
//     $this->load->view('dashboard/kelola_siswa', $data);
// }


    /**
     * Detail siswa aktif (pakai SiswaID)
     */
    public function detail($siswa_id)
    {
        check_role([1,2]);

        if (!$siswa_id) {
            $this->session->set_flashdata('error', 'SiswaID tidak valid.');
            return redirect('siswa');
        }

        $data['title'] = 'Detail Siswa';
        $row = $this->Siswa_model->get_by_id($siswa_id);
        if (!$row) {
            show_404();
        }

        $data['siswa']   = $row;
        $data['dokumen'] = $this->Siswa_model->get_dokumen($siswa_id); // ambil semua dokumen

        // sesuai view kamu
        $this->load->view('dashboard/siswa_detail', $data);
    }

    /**
     * Detail calon siswa HSI (pakai UserID)
     */
    public function detail_calon_hsi($user_id)
    {
        check_role([1,2]);

        $this->load->model('User_model');
        $this->load->model('DokumenSiswa_model');

        $user_id = (int)$user_id;
        if ($user_id <= 0) show_404();

        // ambil data user + siswa
        $data['user'] = $this->User_model->get_user_with_siswa($user_id);
        if (!$data['user']) {
            show_404();
        }

        // ambil dokumen berdasarkan UserID
        $data['dokumen'] = $this->DokumenSiswa_model->get_by_siswa($data['user']->SiswaID, $user_id);

        $data['title'] = 'Detail Calon Siswa HSI';
        $this->load->view('dashboard/siswa_detail_calon_hsi', $data);
    }

    /**
     * Detail calon siswa LPK (pakai UserID)
     */
    public function detail_calon_lain($user_id)
    {
        check_role([1]); // hanya Admin

        $user_id = (int)$user_id;
        if ($user_id <= 0) show_404();

        // Standarkan nama tabel ke lowercase (aman untuk Linux)
        $siswa = $this->db
            ->select('s.*, u.Username, u.Email, u.Phone, u.CreatedAt, ss.NamaStatus, l.NamaLPK')
            ->from('siswa s')
            ->join('users u',       's.UserID = u.UserID', 'left')
            ->join('statussiswa ss','s.StatusID = ss.StatusID', 'left')
            ->join('lpk l',         's.LPKID = l.LPKID', 'left')
            ->where('s.UserID', $user_id)
            ->limit(1)
            ->get()->row();

        if (!$siswa) show_404();

        $dokumen = $this->db->where('UserID', $user_id)->get('dokumensiswa')->result();

        $data['title']   = 'Detail Calon Siswa LPK Lain';
        $data['siswa']   = $siswa;
        $data['dokumen'] = $dokumen;

        $this->load->view('dashboard/siswa_detail_calon_lain', $data);
    }

    /**
     * Ubah status siswa
     */
   public function ubahstatus($siswa_id)
{
    check_role([1]); // Admin1

    // Ambil data siswa
    $siswa = $this->Siswa_model->get_by_id($siswa_id);
    if (!$siswa) {
        $this->session->set_flashdata('error', 'Data siswa tidak ditemukan.');
        return redirect('dashboard/kelola');
    }

    // Dropdown status
    $this->load->model('Status_model');
    $status_list = $this->Status_model->get_all(); // SELECT * FROM statussiswa ORDER BY StatusID

    // Submit?
    if ($this->input->method(TRUE) === 'POST') {
        $status_id = (int) $this->input->post('status_id');

        // Validasi sederhana: pastikan id ada di list
        $allowed = array_map(function($r){ return (int)$r->StatusID; }, (array)$status_list);
        if (!in_array($status_id, $allowed, true)) {
            $this->session->set_flashdata('error', 'Status tidak valid.');
            return redirect('siswa/ubahstatus/'.rawurlencode($siswa_id));
        }

        // Simpan
        $ok = $this->Siswa_model->update_status($siswa_id, $status_id);
        if ($ok) {
            $this->session->set_flashdata('success', 'Status siswa berhasil diperbarui.');
        } else {
            $this->session->set_flashdata('error', 'Gagal memperbarui status siswa.');
        }
        return redirect('dashboard/kelola');
    }

    // Tampilkan form
    $data = [
        'title'       => 'Ubah Status Siswa',
        'siswa'       => $siswa,
        'status_list' => $status_list,
    ];
    $this->load->view('dashboard/siswa_ubahstatus', $data);
}

    // application/controllers/Siswa.php

public function hapus($siswa_id)
{
    check_role([1]); // Admin1 saja

    $s = $this->Siswa_model->get_by_id($siswa_id);
    if (!$s) {
        $this->session->set_flashdata('error', 'Siswa tidak ditemukan.');
        return redirect('dashboard/kelola');
    }

    // deteksi ada transaksi approved?
    $has_approved = false;

    // pembayaran sumber
    if ($this->db->table_exists('pembayaran')) {
        $cnt = $this->db->where('SiswaID', $siswa_id)
                        ->where_in('StatusBayar', ['Approved','approved'])
                        ->count_all_results('pembayaran');
        $has_approved = $has_approved || ($cnt > 0);
    }
    // ledger
    if ($this->db->table_exists('pembayaransiswa')) {
        // numeric 1 atau string 'Approved'
        $is_num = $this->db->query("
            SELECT DATA_TYPE FROM information_schema.COLUMNS
             WHERE TABLE_SCHEMA = DATABASE()
               AND TABLE_NAME='pembayaransiswa'
               AND COLUMN_NAME='StatusKonfirmasi'
             LIMIT 1
        ")->row();
        if ($is_num && in_array(strtolower($is_num->DATA_TYPE), ['int','tinyint','smallint','mediumint','bigint'])) {
            $cnt = $this->db->where('SiswaID', $siswa_id)
                            ->where('StatusKonfirmasi', 1)
                            ->count_all_results('pembayaransiswa');
        } else {
            $cnt = $this->db->where('SiswaID', $siswa_id)
                            ->where('StatusKonfirmasi', 'Approved')
                            ->count_all_results('pembayaransiswa');
        }
        $has_approved = $has_approved || ($cnt > 0);
    }

    $admin_id = (int) $this->session->userdata('UserID');
    $is_ditolak = (int)($s->StatusID ?? 0) === 5 || strtolower((string)$s->NamaStatus) === 'ditolak';

    // aturan:
    // - kalau ADA approved => selalu arsipkan
    // - kalau TIDAK ada approved & status = Ditolak => boleh hard delete
    // - selain itu => arsipkan
    if ($has_approved) {
        $ok = $this->Siswa_model->soft_delete($siswa_id, $admin_id);
        $msg = $ok ? 'Siswa diarsipkan (punya transaksi approved).' : 'Gagal mengarsipkan.';
    } else {
        if ($is_ditolak) {
            $ok = $this->Siswa_model->hard_delete($siswa_id);
            $msg = $ok ? 'Siswa dihapus permanen.' : 'Gagal menghapus permanen.';
        } else {
            $ok = $this->Siswa_model->soft_delete($siswa_id, $admin_id);
            $msg = $ok ? 'Siswa diarsipkan.' : 'Gagal mengarsipkan.';
        }
    }

    $this->session->set_flashdata($ok ? 'success' : 'error', $msg);
    return redirect('dashboard/kelola');
}

}
