<?php
namespace App\Controllers;

use Core\Controller;
use App\Models\DataPMB;
use App\Middleware\Security;

class DataPegPMBController extends Controller
{
    protected $model;
    protected $csrf_token;
    
    public function __construct()
    {
        if (!isset($_SESSION['user'])) {
            header('Location: /logout');
            exit;
        }
    
        $this->model = new DataPMB();
        $this->csrf_token = \App\Middleware\Security::generateCSRF(); // token CSRF
    }

    public function index()
    {
        $search = htmlspecialchars($_GET['search'] ?? '', ENT_QUOTES);
        $page = isset($_GET['page_no']) && is_numeric($_GET['page_no']) ? (int)$_GET['page_no'] : 1;
        $limit = 25;
        $offset = ($page - 1) * $limit;

        $totalRows = $this->model->countData($search);
        $totalPages = ceil($totalRows / $limit);
        $data = $this->model->getData($search, $limit, $offset);

        $this->view('pegawai/pegawai_data_pmb', [
            'data_pmb' => $data,
            'search' => $search,
            'page_no' => $page,
            'totalPages' => $totalPages,
            'offset' => $offset,
            'tahun_list' => $this->model->getDistinctTahunMasuk(),
            'csrf_token' => $_SESSION['csrf_token'],
            'pesan' => $_SESSION['pesan'] ?? '',
            'status_alert' => $_SESSION['status_alert'] ?? '',
        ]);

        unset($_SESSION['pesan'], $_SESSION['status_alert']);
    }

    public function delete()
    {
        Security::csrfCheck(); // cek token CSRF

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id_pmb'])) {
            $id = (int)$_POST['id_pmb'];
            $deleted = $this->model->deleteData($id);

            $_SESSION['pesan'] = $deleted ? "Data berhasil dihapus!" : "Gagal menghapus data!";
            $_SESSION['status_alert'] = $deleted ? "success" : "danger";
        }

        header("Location: /dashboard/pegawai-data_pmb");
        exit;
    }

    public function edit($id)
    {
        $id = (int)$id;
        $data = $this->model->getDataById($id);

        if (!$data) {
            $_SESSION['pesan'] = "Data tidak ditemukan!";
            $_SESSION['status_alert'] = "danger";
            header("Location: /dashboard/pegawai-data_pmb");
            exit;
        }

        $this->view('pegawai/pegawai_edit_pmb', [
            'data_pmb' => $data,
            'csrf_token' => $_SESSION['csrf_token']
        ]);
    }

    public function update()
    {
        Security::csrfCheck(); // cek token CSRF

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $id = (int)$_POST['id_pmb'];
            $nama = htmlspecialchars(trim($_POST['nama_camaba']), ENT_QUOTES);
            $nisn = htmlspecialchars(trim($_POST['nisn']), ENT_QUOTES);
            $npsn = htmlspecialchars(trim($_POST['npsn']), ENT_QUOTES);
            $wa = htmlspecialchars(trim($_POST['wa']), ENT_QUOTES);

            $updated = $this->model->updateData($id, $nama, $nisn, $npsn, $wa);

            $_SESSION['pesan'] = $updated ? "Data berhasil diperbarui!" : "Gagal memperbarui data!";
            $_SESSION['status_alert'] = $updated ? "success" : "danger";

            header("Location: /dashboard/pegawai-data_pmb");
            exit;
        }
    }

    public function importExcel()
    {
        Security::csrfCheck();
    
        ini_set('upload_tmp_dir', '/home/babunnaj/tmp');
    
        require_once __DIR__ . '/../libraries/PHPExcel/PHPExcel.php';
        require_once __DIR__ . '/../libraries/PHPExcel/IOFactory.php';
    
        // Validasi file
        if (!isset($_FILES['file_excel']) || $_FILES['file_excel']['error'] !== UPLOAD_ERR_OK) {
            $_SESSION['pesan'] = "File Excel belum dipilih atau gagal diupload!";
            $_SESSION['status_alert'] = "danger";
            header("Location: /dashboard/pegawai-data_pmb");
            exit;
        }
    
        try {
            $excelFile = $_FILES['file_excel']['tmp_name'];
    
            $fileType = \PHPExcel_IOFactory::identify($excelFile);
            $reader   = \PHPExcel_IOFactory::createReader($fileType);
            $excel    = $reader->load($excelFile);
    
            $sheet      = $excel->getSheet(0);
            $highestRow = $sheet->getHighestDataRow();
    
            $tahun = date('Y');
    
            $insert = 0;
            $duplicate = 0;
            $invalid = 0;
            $duplicateRows = [];
    
            // Loop data (mulai baris ke-2)
            for ($row = 2; $row <= $highestRow; $row++) {
    
                $nama = trim($sheet->getCell("A{$row}")->getValue());
                $nisn = trim($sheet->getCell("B{$row}")->getValue());
    
                // Skip baris kosong
                if ($nama === '' || $nisn === '') {
                    $invalid++;
                    continue;
                }
    
                // 🔴 CEK DUPLIKAT NISN
                if ($this->model->isNisnExist($nisn)) {
                    $duplicate++;
                    $duplicateRows[] = "Baris {$row} (NISN: {$nisn})";
                    continue;
                }
    
                $data = [
                    'nama_camaba'  => $nama,
                    'nisn'         => $nisn,
                    'asal_sekolah' => trim($sheet->getCell("C{$row}")->getValue()),
                    'npsn'         => trim($sheet->getCell("D{$row}")->getValue()),
                    'tahun_lulus'  => trim($sheet->getCell("E{$row}")->getValue()),
                    'wa'           => trim($sheet->getCell("F{$row}")->getValue()),
                    'id_prodi'     => trim($sheet->getCell("G{$row}")->getValue()),
                    'gelombang'    => trim($sheet->getCell("H{$row}")->getValue()),
                    'tanggal'      => trim($sheet->getCell("I{$row}")->getValue()),
                    'tahun'        => $tahun
                ];
    
                $this->model->insertImport($data);
                $insert++;
            }
    
            // Pesan hasil
            $msg = "Import selesai. Berhasil: {$insert} data";
    
            if ($duplicate > 0) {
                $msg .= ", Duplikat NISN: {$duplicate}";
            }
    
            if ($invalid > 0) {
                $msg .= ", Data tidak valid: {$invalid}";
            }
    
            if (!empty($duplicateRows)) {
                $msg .= " → " . implode('; ', $duplicateRows);
            }
    
            $_SESSION['pesan'] = $msg;
            $_SESSION['status_alert'] = $insert > 0 ? "success" : "warning";
    
            header("Location: /dashboard/pegawai-data_pmb");
            exit;
    
        } catch (\Exception $e) {
            $_SESSION['pesan'] = "Gagal import Excel: " . $e->getMessage();
            $_SESSION['status_alert'] = "danger";
            header("Location: /dashboard/pegawai-data_pmb");
            exit;
        }
    }

}
