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

class Dashboard extends CI_Controller
{
    /* ====== STATUS KONSTAN (samakan dgn tabel statussiswa) ====== */
    const STS_CALON     = 1;
    const STS_MENUNGGU  = 3; // Menunggu Pembayaran (HSI)
    const STS_DITERIMA  = 4; // sesuaikan kalau beda
    const STS_DITOLAK   = 5;

    /* LPK default untuk HSI */
    const LPK_HSI_ID    = 1;

    public function __construct()
    {
        parent::__construct();
        check_login();

        $this->load->model('Siswa_model');
        $this->load->model('Pembayaran_model');
        $this->load->library('session');
    }

    /** Redirect sesuai role */
    public function index()
    {
        $role_id = (int) $this->session->userdata('role_id');
        if ($role_id === 1) return redirect('dashboard/admin1');
        if ($role_id === 2) return redirect('dashboard/admin2');
        if ($role_id === 3) return redirect('dashboard/user');
        return redirect('auth/logout');
    }

  /** Dashboard Admin1 */
public function admin1()
{
    check_role([1]);

    /* -------- METRIC SISWA -------- */
    $total_siswa = (int)$this->db->count_all('siswa');
    $s_aktif     = (int)$this->db->where('StatusID', 2)->count_all_results('siswa');
    $s_menunggu  = (int)$this->db->where('StatusID', 3)->count_all_results('siswa');

    /* -------- METRIC PEMBAYARAN (all time) -------- */
    $rowApproved = $this->db->select_sum('JumlahBayar', 'n')
        ->from('pembayaran')
        ->where("LOWER(StatusBayar) =", 'approved')
        ->get()->row();
    $total_approved = (float)($rowApproved->n ?? 0);

    $pending_count = (int)$this->db
        ->where("LOWER(StatusBayar) =", 'pending')
        ->count_all_results('pembayaran');

    /* -------- TANGGAL AMAN (fallback kolom) -------- */
    $fields  = array_map('strtolower', $this->db->list_fields('pembayaran'));
    $parts   = [];
    if (in_array('tanggalbayar', $fields, true)) $parts[] = 'TanggalBayar';
    if (in_array('approvedat',   $fields, true)) $parts[] = 'ApprovedAt';
    if (in_array('createdat',    $fields, true)) $parts[] = 'CreatedAt';
    // minimal harus ada satu; kalau tidak, pakai PembayaranID sebagai “tanggal” (jarang terjadi)
    $dateExpr = !empty($parts) ? 'COALESCE('.implode(',', $parts).')' : 'CreatedAt';

    $from = date('Y-m-d', strtotime('-30 days'));

    /* -------- LINE: approved per hari (30 hari, pakai $dateExpr) -------- */
    $series_rows = $this->db->select("DATE($dateExpr) AS d, SUM(JumlahBayar) AS n", false)
        ->from('pembayaran')
        ->where("$dateExpr >=", $from, false)              // penting: false → no-escape expr
        ->where("LOWER(StatusBayar) =", 'approved')
        ->group_by("DATE($dateExpr)", false)
        ->order_by("DATE($dateExpr)", 'ASC', false)
        ->get()->result();

    $line_labels = [];
    $line_values = [];
    foreach ($series_rows as $r) {
        $line_labels[] = (string)$r->d;
        $line_values[] = (float)$r->n;
    }

    /* -------- PIE: komposisi metode (approved, 30 hari, pakai $dateExpr) -------- */
    $pie_rows = $this->db->select("COALESCE(MetodeBayar,'-') AS m, SUM(JumlahBayar) AS n", false)
        ->from('pembayaran')
        ->where("$dateExpr >=", $from, false)
        ->where("LOWER(StatusBayar) =", 'approved')
        ->group_by("COALESCE(MetodeBayar,'-')", false)
        ->order_by('n', 'DESC')
        ->get()->result();

    $pie_labels = [];
    $pie_values = [];
    foreach ($pie_rows as $r) {
        $lbl = trim((string)$r->m);
        if ($lbl === '') $lbl = '-';
        $pie_labels[] = $lbl;
        $pie_values[] = (float)$r->n;
    }

    /* -------- TABEL: 8 transaksi terbaru -------- */
    $recent = $this->db->select('p.*, s.NamaLengkap, u.Email')
        ->from('pembayaran p')
        ->join('siswa s', 's.UserID = p.UserID', 'left')
        ->join('users u', 'u.UserID = p.UserID', 'left')
        ->order_by('p.PembayaranID', 'DESC')
        ->limit(8)
        ->get()->result();

    $data = [
        'title'          => 'Dashboard Admin',
        'total_siswa'    => $total_siswa,
        's_aktif'        => $s_aktif,
        's_menunggu'     => $s_menunggu,
        'total_approved' => $total_approved,
        'pending_count'  => $pending_count,
        'line_labels'    => $line_labels,
        'line_values'    => $line_values,
        'pie_labels'     => $pie_labels,
        'pie_values'     => $pie_values,
        'recent'         => $recent,
    ];

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

    /** Dashboard Admin2 */
    public function admin2()
    {
        check_role([2]);

        $data = [
            'title'       => 'Dashboard Admin2',
            'total_siswa' => $this->Siswa_model->count_all(),
        ];
        $this->load->view('dashboard/admin2', $data);
    }

    /** Kelola semua siswa (Admin1 full akses, Admin2 read-only) */
    public function kelola()
    {
        check_role([1,2]);

        $data = [
            'title' => 'Kelola Siswa',
            // tampilkan semua (termasuk Menunggu Pembayaran & Aktif, exclude Calon)
            'siswa' => $this->Siswa_model->get_all_non_calon(),
        ];
        $this->load->view('dashboard/kelola_siswa', $data);
    }

    /** Page: Calon Siswa HSI */
    public function calon_siswa()
    {
        check_role([1]);

        $data['title'] = 'Calon Siswa HSI';
        $data['calon_siswa'] = $this->db
            ->select('u.UserID, s.SiswaID, s.NamaLengkap, u.Email, u.Phone, s.CreatedAt, ss.NamaStatus, s.StatusPembayaran')
            ->from('siswa s')
            ->join('users u', 's.UserID = u.UserID', 'left')
            ->join('statussiswa ss', 's.StatusID = ss.StatusID', 'left')
            ->where('s.StatusID', self::STS_CALON)
            ->group_start()
                ->where('s.LPKID', self::LPK_HSI_ID)
                ->or_where('s.LPKID IS NULL', null, false)
            ->group_end()
            ->order_by('s.CreatedAt', 'DESC')
            ->get()->result();

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

    /** Page: Calon Siswa LPK Lain */
    public function calon_siswa_lain()
    {
        check_role([1]);

        $data['title'] = 'Calon Siswa LPK Lain';
        $data['calon_siswa'] = $this->db
            ->select('u.UserID, s.SiswaID, s.NamaLengkap, u.Email, u.Phone, s.CreatedAt, ss.NamaStatus, s.StatusPembayaran, 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.StatusID', self::STS_CALON)
            ->where('s.LPKID !=', self::LPK_HSI_ID)
            ->order_by('s.CreatedAt', 'DESC')
            ->get()->result();

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

    /** Dashboard Siswa (role = 3) */
    public function user()
    {
        check_role([3]);
        $siswa_id = $this->session->userdata('SiswaID');
        $data = [
            'title' => 'Dashboard Siswa',
            'siswa' => $siswa_id ? $this->Siswa_model->get_by_id($siswa_id) : null,
        ];
        $this->load->view('dashboard/user', $data);
    }

    /* ================== AKSI CALON (terima/tolak) ================== */

    public function update_status($siswa_id, $aksi = null)
    {
        check_role([1]);

        if (!$siswa_id || !$aksi) show_error('Parameter tidak valid', 400);

        $siswa = $this->db->where('SiswaID', $siswa_id)->get('siswa')->row();
        if (!$siswa) show_error('Siswa tidak ditemukan', 404);

        $status_baru = null;
        if ($aksi === 'terima') {
            $is_hsi = ((int)($siswa->LPKID ?? 0) === self::LPK_HSI_ID);
            $status_baru = $is_hsi ? self::STS_MENUNGGU : self::STS_DITERIMA;
        } elseif ($aksi === 'tolak') {
            $status_baru = self::STS_DITOLAK;
        }

        if ($status_baru) {
            $this->db->where('SiswaID', $siswa_id)->update('siswa', ['StatusID' => $status_baru]);
            $this->session->set_flashdata('success', 'Status siswa berhasil diperbarui.');
        } else {
            $this->session->set_flashdata('error', 'Aksi tidak valid.');
        }

        $back = $this->input->server('HTTP_REFERER') ?: site_url('dashboard/calon_siswa');
        redirect($back);
    }

    /* ================== LIST & AKSI: SISWA DITOLAK ================== */

    public function siswa_ditolak()
{
    check_role([1]);

    // --- resolve nama tabel (aman untuk beda huruf besar/kecil)
    $T_SISWA  = $this->db->table_exists('Siswa') ? 'Siswa' : 'siswa';
    $T_USERS  = $this->db->table_exists('Users') ? 'Users' : 'users';
    $T_LPK    = $this->db->table_exists('LPK')   ? 'LPK'   : 'lpk';

    $hasDeletedAt = $this->db->field_exists('DeletedAt', $T_SISWA);
    $selectExtra  = $hasDeletedAt ? ', s.DeletedAt, s.DeletedPrevStatusID' : '';

    $this->db->select(
        's.SiswaID, s.UserID, s.NamaLengkap, u.Email, u.Phone, l.NamaLPK, s.CreatedAt' . $selectExtra
    )
    ->from("$T_SISWA s")
    ->join("$T_USERS u", 's.UserID = u.UserID', 'left')
    ->join("$T_LPK l",   's.LPKID  = l.LPKID', 'left');

    if ($hasDeletedAt) {
        // tampilkan yg terarsip ATAU berstatus Ditolak (data lama/fallback)
        $this->db->group_start()
                 ->where('s.StatusID', self::STS_DITOLAK)
                 ->or_where('s.DeletedAt IS NOT NULL', null, false)
                 ->group_end();

        // urutkan: yang diarsip duluan, terbaru di atas
        $this->db->order_by('s.DeletedAt IS NULL', 'ASC', false); // NULL last
        $this->db->order_by('s.DeletedAt', 'DESC');
        $this->db->order_by('s.CreatedAt', 'DESC');
    } else {
        // tanpa kolom arsip, pakai status Ditolak saja
        $this->db->where('s.StatusID', self::STS_DITOLAK)
                 ->order_by('s.CreatedAt', 'DESC');
    }

    $data['title'] = 'Siswa Ditolak / Terarsip';
    $data['siswa'] = $this->db->get()->result();

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

    /** Hapus dari Kelola Siswa:
 *  - Ada transaksi approved  -> soft delete (arsip) -> redirect ke Siswa Ditolak
 *  - Tidak ada approved      -> hard delete (permanen) -> redirect ke Kelola Siswa
 */
public function hapus_siswa($siswa_id)
{
    check_role([1]);

    // cek apakah ada transaksi approved untuk siswa ini
    $hasApproved = $this->Siswa_model->has_approved_payments($siswa_id);

    if ($hasApproved) {
        $admin_id = (int)($this->session->userdata('UserID') ?? $this->session->userdata('user_id') ?? 0);
        $ok = $this->Siswa_model->soft_delete($siswa_id, $admin_id);

        $this->session->set_flashdata($ok ? 'success' : 'error',
            $ok ? 'Siswa diarsipkan (punya transaksi approved).'
                : 'Gagal mengarsipkan siswa.');
        return redirect('dashboard/siswa_ditolak');
    }

    // tidak ada approved -> hapus permanen (model juga urus hapus users jika orphan)
    $ok = $this->Siswa_model->hard_delete($siswa_id);

    $this->session->set_flashdata($ok ? 'success' : 'error',
        $ok ? 'Siswa dihapus permanen.'
            : 'Gagal menghapus siswa.');
    return redirect('dashboard/kelola');
}



    /** Kembalikan dari Ditolak/Arsip → ke status sebelumnya & ke Kelola Siswa */
    public function kembalikan_siswa($siswa_id)
    {
        check_role([1]);

        $ok = $this->Siswa_model->restore($siswa_id);

        $this->session->set_flashdata($ok ? 'success' : 'error',
            $ok ? 'Siswa berhasil dikembalikan ke status sebelumnya.'
                : 'Gagal mengembalikan siswa.');

        redirect('dashboard/kelola');
    }

    /** Hapus PERMANEN SEMUA DATA berdasarkan UserID (dari halaman Ditolak) */
    public function hapus_permanen_user($user_id)
    {
        check_role([1]);

        $ok = $this->Siswa_model->hard_delete_by_user((int)$user_id);

        $this->session->set_flashdata($ok ? 'success' : 'error',
            $ok ? 'Semua data siswa (berdasarkan UserID) berhasil dihapus permanen.'
                : 'Gagal menghapus permanen data siswa.');

        redirect('dashboard/siswa_ditolak');
    }
}
