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

class Import_pegawai extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->library(['upload', 'session']);
        $this->load->helper('url');
    }

    public function index() {
        $this->load->view('import_pegawai_form');
    }

    public function process() {
        // Gunakan FCPATH untuk path absolut
        $config['upload_path']   = FCPATH . 'assets/uploads/';
        $config['allowed_types'] = 'xlsx'; // Hanya xlsx sesuai file referensi
        $config['max_size']      = 5120;
        $config['file_name']     = 'referensi_pegawai';
        $config['overwrite']     = TRUE;

        // Buat folder jika belum ada
        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, TRUE);
        }

        $this->upload->initialize($config);

        if (!$this->upload->do_upload('file_excel')) {
            $error = $this->upload->display_errors();
            $this->session->set_flashdata('error', $error);
            redirect('import_pegawai');
        }

        $upload_data = $this->upload->data();
        $file_path = $upload_data['full_path'];

        try {
            // Muat PhpSpreadsheet
            $inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($file_path);
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
            $spreadsheet = $reader->load($file_path);

            $this->db->trans_start();
            $this->db->truncate('pegawai'); // Hapus data lama

            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();
            $inserted = 0;

            // Mulai dari baris 2 (abaikan header)
            for ($row = 2; $row <= $highestRow; $row++) {
                $id_peg = $sheet->getCell("A{$row}")->getValue();
                // Hentikan jika baris kosong di kolom A
                if (is_null($id_peg) || $id_peg === '') {
                    continue;
                }

                $data = [
                    'id_peg' => $id_peg,
                    'nip' => $sheet->getCell("B{$row}")->getValue(),
                    'nama' => $sheet->getCell("C{$row}")->getValue(),
                    'jabatan' => $sheet->getCell("D{$row}")->getValue(),
                    'jenis_jabatan' => $sheet->getCell("E{$row}")->getValue(),
                    'golru' => $sheet->getCell("F{$row}")->getValue(),
                    'unor_id' => $sheet->getCell("G{$row}")->getValue(),
                    'unor_nama' => $sheet->getCell("H{$row}")->getValue()
                ];

                // Validasi minimal: pastikan NIP ada
                if (!empty($data['nip'])) {
                    $this->db->insert('pegawai', $data);
                    $inserted++;
                }
            }

            $this->db->trans_complete();
            unlink($file_path);

            if ($this->db->trans_status() === FALSE) {
                throw new Exception("Transaksi database gagal.");
            }

            $this->session->set_flashdata('success', "Berhasil mengimpor {$inserted} data pegawai.");
            redirect('pegawai');

        } catch (Exception $e) {
            unlink($file_path);
            $this->session->set_flashdata('error', 'Error: ' . $e->getMessage());
            redirect('import_pegawai');
        }
    }
}