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

class Import_unor extends CI_Controller {

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

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

    public function process() {
        $config['upload_path']   = FCPATH . 'assets/uploads/';
        $config['allowed_types'] = 'xlsx';
        $config['file_name']     = 'referensi_unor';
        $config['overwrite']     = TRUE;

        if (!is_dir($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, TRUE);
        }

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

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

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

        try {
            if (!file_exists(FCPATH . 'vendor/autoload.php')) {
                throw new Exception("PhpSpreadsheet belum diinstal.");
            }
            require_once FCPATH . 'vendor/autoload.php';

            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file_path);
            $sheet = $spreadsheet->getActiveSheet();
            $highestRow = $sheet->getHighestRow();

            $this->db->trans_start();
            $this->db->truncate('unor'); // Hapus data lama
            $inserted = 0;

            // 🔥 Mulai dari baris 2 (data pertama), karena file Excel TIDAK punya kolom "No"
            for ($row = 2; $row <= $highestRow; $row++) {
                // Ambil nilai "unor_id" dari kolom A
                $unor_id = $sheet->getCell("A{$row}")->getValue();

                // Hentikan jika baris kosong di kolom A (unor_id)
                if (is_null($unor_id) || trim($unor_id) === '') {
                    continue;
                }

                // ✅ Sesuaikan dengan struktur file Excel asli
                $data = [
                    'unor_id' => $unor_id,
                    'jenis' => $sheet->getCell("B{$row}")->getValue(),
                    'nama' => $sheet->getCell("C{$row}")->getValue(),
                    'unor_mandiri' => (int) ($sheet->getCell("D{$row}")->getValue() == 1 ? 1 : 0),
                    'unor_atasan_id' => $sheet->getCell("E{$row}")->getValue(),
                    'unor_atasan_nama' => $sheet->getCell("F{$row}")->getValue(),
                    'unor_induk_id' => $sheet->getCell("G{$row}")->getValue(),
                    'unor_induk_nama' => $sheet->getCell("H{$row}")->getValue()
                ];

                if (!empty($data['unor_id']) && !empty($data['nama'])) {
                    $this->db->insert('unor', $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 UNOR.");
            redirect('unor');

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