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

use PhpOffice\PhpSpreadsheet\IOFactory;

class Import extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->database();
        $this->load->helper('url');
    }

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

    public function process() {
        $config['upload_path']   = './assets/uploads/';
        $config['allowed_types'] = 'xls|xlsx';
        $config['max_size']      = 2048;
        $config['file_name']     = 'daftar_pegawai';

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('file_excel')) {
            $error = $this->upload->display_errors();
            echo "<script>alert('Gagal upload: $error'); window.history.back();</script>";
            return;
        }

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

        try {
            $spreadsheet = IOFactory::load($file_path);
            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();
            $highestColumn = $sheet->getHighestColumn();

            // Mulai dari baris ke-5 (data pertama ada di baris 5)
            for ($row = 5; $row <= $highestRow; $row++) {
                $nip = trim($sheet->getCell("C$row")->getValue());
                if (empty($nip)) continue;

                $data = [
                    'nip' => $nip,
                    'nama_pegawai' => trim($sheet->getCell("B$row")->getValue()),
                    'eselon' => trim($sheet->getCell("X$row")->getValue()) ?: 'Non Eselon',
                    'jabatan' => trim($sheet->getCell("N$row")->getValue()),
                    'skpd' => trim($sheet->getCell("P$row")->getValue()),
                    'unitkerja' => trim($sheet->getCell("Q$row")->getValue()),
                    'gender' => substr(trim($sheet->getCell("R$row")->getValue()), 0, 1),
                    'role' => 'user',
                    'password' => password_hash($nip, PASSWORD_DEFAULT),
                    'tugas_tambahan' => trim($sheet->getCell("Y$row")->getValue())
                ];

                // Hindari duplikat
                $this->db->where('nip', $nip);
                if ($this->db->count_all_results('users') == 0) {
                    $this->db->insert('users', $data);
                }
            }

            unlink($file_path); // Hapus file setelah sukses
            echo "<script>alert('Import sukses!'); window.location='" . base_url('dashboard') . "';</script>";

        } catch (Exception $e) {
            echo "<script>alert('Error: " . $e->getMessage() . "'); window.history.back();</script>";
        }
    }
}