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

class Admin extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Admin_model');
        $this->load->model('Token_model');
        $this->load->model('HasilTKA_model');

        // Check if user is logged in
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
    }

    public function dashboard()
    {
        $data['title'] = 'Dashboard';
        $data['admin'] = $this->session->userdata('nama_lengkap');
        $data['total_results'] = $this->HasilTKA_model->get_all_results();
        $data['total_tokens'] = $this->Token_model->get_all_tokens();
        $data['active_tokens'] = $this->Token_model->get_active_tokens();

        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/dashboard', $data);
        $this->load->view('admin/templates/footer');
    }

    // Data Hasil TKA Management
    public function hasil_tka()
    {
        $data['title'] = 'Data Hasil TKA';
        $data['admin'] = $this->session->userdata('nama_lengkap');
        $data['results'] = $this->HasilTKA_model->get_all_results();

        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/hasil_tka/index', $data);
        $this->load->view('admin/templates/footer');
    }

    public function hasil_tka_delete($id)
    {

        // Check if result exists
        $result = $this->HasilTKA_model->get_result_by_id($id);
        if (!$result) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('admin/hasil_tka');
        }

        // Delete result
        if ($this->HasilTKA_model->delete_result($id)) {
            $this->session->set_flashdata('success', 'Data berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus data!');
        }

        redirect('admin/hasil_tka');
    }

    public function import_hasil_tka()
    {
        $data['title'] = 'Import Data Hasil TKA';
        $data['admin'] = $this->session->userdata('nama_lengkap');


        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/hasil_tka/import', $data);
        $this->load->view('admin/templates/footer');
    }

    public function proses_import()
    {
        $this->load->library('upload');

        // Buat folder uploads jika belum ada
        if (!is_dir('./uploads/')) {
            mkdir('./uploads/', 0777, TRUE);
        }

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'xls|xlsx|csv';
        $config['max_size'] = 5120; // 5MB
        $config['overwrite'] = FALSE;
        $config['encrypt_name'] = TRUE;

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

        if (!$this->upload->do_upload('file_excel')) {
            $error = $this->upload->display_errors();
            $this->session->set_flashdata('error', $error);
            redirect('admin/import_hasil_tka');
        } else {
            $upload_data = $this->upload->data();
            $file_path = $upload_data['full_path'];

            try {
                // Load library spreadsheet
                $this->load->library('spreadsheet');

                // Validasi file
                if (!$this->spreadsheet->validateFile($file_path)) {
                    $this->session->set_flashdata('error', 'Format file tidak valid! Gunakan file Excel (.xls, .xlsx) atau CSV.');
                    unlink($file_path);
                    redirect('admin/import_hasil_tka');
                }

                // Baca data dari Excel
                $import_data = $this->spreadsheet->readHasilTKAV2($file_path);

                if (empty($import_data)) {
                    $this->session->set_flashdata('error', 'Tidak ada data yang ditemukan dalam file Excel! Pastikan data dimulai dari baris ke-2.');
                    unlink($file_path);
                    redirect('admin/import_hasil_tka');
                }

                // Proses validasi data (tanpa validasi numerik)
                $valid_data = array();
                $errors = array();
                $success_count = 0;
                $error_count = 0;

                foreach ($import_data as $item) {
                    $row_number = $item['row_number'];

                    // Validasi dasar saja (tanpa validasi numerik)

                    // 1. Validasi NISN tidak kosong
                    if (empty($item['NISN'])) {
                        $errors[] = "Baris {$row_number}: NISN tidak boleh kosong";
                        $error_count++;
                        continue;
                    }

                    // 2. Validasi NISN panjang (optional, bisa dihapus jika tidak perlu)
                    if (strlen($item['NISN']) > 20) {
                        $errors[] = "Baris {$row_number}: NISN terlalu panjang (max 20 karakter)";
                        $error_count++;
                        continue;
                    }

                    // 3. Validasi nama tidak kosong
                    if (empty($item['NAMA_PESERTA'])) {
                        $errors[] = "Baris {$row_number}: Nama peserta tidak boleh kosong";
                        $error_count++;
                        continue;
                    }

                    // 4. Validasi nama terlalu panjang (optional)
                    if (strlen($item['NAMA_PESERTA']) > 200) {
                        $errors[] = "Baris {$row_number}: Nama peserta terlalu panjang (max 200 karakter)";
                        $error_count++;
                        continue;
                    }

                    // Data valid
                    unset($item['row_number']); // Hapus row_number sebelum disimpan
                    $valid_data[] = $item;
                    $success_count++;
                }

                // Import data ke database
                if (!empty($valid_data)) {
                    $import_result = $this->HasilTKA_model->import_excel($valid_data);

                    if (is_array($import_result)) {
                        $imported_count = $import_result['success'];
                        $failed_count = $import_result['error'];

                        if ($imported_count > 0) {
                            $message = "✅ Berhasil mengimport {$imported_count} data";

                            if ($failed_count > 0) {
                                $message .= "<br>❌ Gagal import {$failed_count} data";
                            }

                            if (!empty($errors)) {
                                $message .= "<br>⚠️ Terdapat " . count($errors) . " error validasi:<br>";
                                $message .= implode('<br>', array_slice($errors, 0, 5));
                                if (count($errors) > 5) {
                                    $message .= '<br>... dan ' . (count($errors) - 5) . ' error lainnya';
                                }
                            }

                            $this->session->set_flashdata('success', $message);
                        } else {
                            $error_message = "❌ Tidak ada data yang berhasil diimport";
                            if (!empty($errors)) {
                                $error_message .= "<br>Error ditemukan:<br>";
                                $error_message .= implode('<br>', array_slice($errors, 0, 10));
                            }
                            $this->session->set_flashdata('error', $error_message);
                        }
                    } else {
                        // Untuk backward compatibility
                        if ($import_result) {
                            $message = "✅ Berhasil mengimport {$success_count} data";

                            if (!empty($errors)) {
                                $message .= "<br>⚠️ Terdapat " . count($errors) . " error validasi:<br>";
                                $message .= implode('<br>', array_slice($errors, 0, 5));
                            }

                            $this->session->set_flashdata('success', $message);
                        } else {
                            $this->session->set_flashdata('error', 'Gagal menyimpan data ke database!');
                        }
                    }
                } else {
                    if (!empty($errors)) {
                        $error_message = "❌ Tidak ada data yang valid. Error ditemukan:<br>";
                        $error_message .= implode('<br>', array_slice($errors, 0, 10));
                        if (count($errors) > 10) {
                            $error_message .= '<br>... dan ' . (count($errors) - 10) . ' error lainnya';
                        }
                        $this->session->set_flashdata('error', $error_message);
                    } else {
                        $this->session->set_flashdata('error', 'Tidak ada data yang ditemukan dalam file!');
                    }
                }
            } catch (\Exception $e) {
                $this->session->set_flashdata('error', 'Error membaca file Excel: ' . $e->getMessage());
            }

            // Hapus file setelah diproses
            if (file_exists($file_path)) {
                unlink($file_path);
            }

            redirect('admin/hasil_tka');
        }
    }

    /**
     * Proses import tanpa validasi sama sekali
     */
    public function proses_import_simple()
    {
        $this->load->library('upload');

        // Buat folder uploads jika belum ada
        if (!is_dir('./uploads/')) {
            mkdir('./uploads/', 0777, TRUE);
        }

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'xls|xlsx|csv';
        $config['max_size'] = 10240; // 10MB
        $config['encrypt_name'] = TRUE;

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

        if (!$this->upload->do_upload('file_excel')) {
            $error = $this->upload->display_errors();
            $this->session->set_flashdata('error', $error);
            redirect('admin/import_hasil_tka');
        } else {
            $upload_data = $this->upload->data();
            $file_path = $upload_data['full_path'];

            try {
                // Load PhpSpreadsheet langsung
                require_once APPPATH . '../vendor/autoload.php';

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

                // Baca semua data
                $dataArray = $sheet->toArray(null, true, true, true);

                // Hilangkan header
                array_shift($dataArray);

                $import_data = array();

                foreach ($dataArray as $row) {
                    // Skip jika NISN kosong
                    if (empty($row['A'])) {
                        continue;
                    }

                    $import_data[] = array(
                        'NISN' => $this->clean_value($row['A']),
                        'NO_PESERTA' => $this->clean_value($row['B']),
                        'NAMA_PESERTA' => $this->clean_value($row['C']),
                        'TEMPAT_TGL_LAHIR' => $this->clean_value($row['D']),
                        'BHS_INDONESIA' => $this->clean_value($row['E']),
                        'MATEMATIKA' => $this->clean_value($row['F']),
                        'BHS_INGGRIS' => $this->clean_value($row['G']),
                        'NAMA_MATPEL_PIL_1' => $this->clean_value($row['H']),
                        'NILAI_MATPEL_PIL_1' => $this->clean_value($row['I']),
                        'NAMA_MATPEL_PIL_2' => $this->clean_value($row['J']),
                        'NILAI_MATPEL_PIL_2' => $this->clean_value($row['K']),
                        'LAMPIRAN' => $this->clean_value($row['L'])
                    );
                }

                if (!empty($import_data)) {
                    // Import ke database
                    $result = $this->HasilTKA_model->import_excel_batch($import_data);

                    if ($result > 0) {
                        $this->session->set_flashdata('success', "✅ Berhasil mengimport {$result} data hasil TKA!");
                    } else {
                        $this->session->set_flashdata('error', '❌ Gagal mengimport data. Silakan cek format file.');
                    }
                } else {
                    $this->session->set_flashdata('error', 'Tidak ada data yang ditemukan dalam file!');
                }
            } catch (\Exception $e) {
                $this->session->set_flashdata('error', 'Error: ' . $e->getMessage());
            }

            // Hapus file
            if (file_exists($file_path)) {
                unlink($file_path);
            }

            redirect('admin/hasil_tka');
        }
    }

    /**
     * Clean value helper
     */
    private function clean_value($value)
    {
        if (is_null($value) || $value === '') {
            return '';
        }

        // Handle RichText objects
        if (is_object($value) && method_exists($value, '__toString')) {
            $value = $value->__toString();
        }

        // Convert to string and trim
        return trim((string) $value);
    }

    public function download_template()
    {
        $this->load->library('spreadsheet');
        $this->spreadsheet->downloadTemplate();
    }

    public function export_hasil_tka()
    {
        // Ambil data dari database
        $data = $this->HasilTKA_model->get_all_results();

        // Format data untuk export
        $export_data = array();
        foreach ($data as $row) {
            $export_data[] = array(
                'NISN' => $row->NISN,
                'NO_PESERTA' => $row->NO_PESERTA,
                'NAMA_PESERTA' => $row->NAMA_PESERTA,
                'TEMPAT_TGL_LAHIR' => $row->TEMPAT_TGL_LAHIR,
                'BHS_INDONESIA' => $row->BHS_INDONESIA,
                'MATEMATIKA' => $row->MATEMATIKA,
                'BHS_INGGRIS' => $row->BHS_INGGRIS,
                'NAMA_MATPEL_PIL_1' => $row->NAMA_MATPEL_PIL_1,
                'NILAI_MATPEL_PIL_1' => $row->NILAI_MATPEL_PIL_1,
                'NAMA_MATPEL_PIL_2' => $row->NAMA_MATPEL_PIL_2,
                'NILAI_MATPEL_PIL_2' => $row->NILAI_MATPEL_PIL_2,
                'LAMPIRAN' => $row->LAMPIRAN
            );
        }

        $filename = 'data_hasil_tka_' . date('Ymd_His') . '.xlsx';
        $this->load->library('spreadsheet');
        $this->spreadsheet->exportHasilTKA($export_data, $filename);
    }

    // Token Management
    public function tokens()
    {
        $data['title'] = 'Manajemen Token';
        $data['admin'] = $this->session->userdata('nama_lengkap');

        $data['tokens'] = $this->Token_model->get_all_tokens();

        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/tokens/index', $data);
        $this->load->view('admin/templates/footer');
    }

    public function generate_token()
    {
        $token = $this->Token_model->generate_token();

        if ($token) {
            $this->session->set_flashdata('success', 'Token berhasil digenerate: ' . $token);
        } else {
            $this->session->set_flashdata('error', 'Gagal generate token!');
        }

        redirect('admin/tokens');
    }

    public function expire_token($id)
    {
        if ($this->Token_model->expire_token($id)) {
            $this->session->set_flashdata('success', 'Token berhasil di-expire!');
        } else {
            $this->session->set_flashdata('error', 'Gagal meng-expire token!');
        }

        redirect('admin/tokens');
    }

    public function delete_token($id)
    {
        if ($this->Token_model->delete_token($id)) {
            $this->session->set_flashdata('success', 'Token berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus token!');
        }

        redirect('admin/tokens');
    }

    // Admin Management
    public function admins()
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        $data['title'] = 'Manajemen Admin';
        $data['admin'] = $this->session->userdata('nama_lengkap');
        $data['admins'] = $this->Admin_model->get_all_admins();

        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/admins/index', $data);
        $this->load->view('admin/templates/footer');
    }

    public function tambah_admin()
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        $data['title'] = 'Tambah Admin';
        $data['admin'] = $this->session->userdata('nama_lengkap');


        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/admins/tambah', $data);
        $this->load->view('admin/templates/footer');
    }

    public function proses_tambah_admin()
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'required|trim|is_unique[tbl_admin.username]');
        $this->form_validation->set_rules('password', 'Password', 'required|trim|min_length[6]');
        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');

        if ($this->form_validation->run() == FALSE) {
            $this->tambah_admin();
        } else {
            $data = array(
                'username' => $this->input->post('username'),
                'password' => $this->input->post('password'),
                'nama_lengkap' => $this->input->post('nama_lengkap'),
                'email' => $this->input->post('email'),
                'level' => $this->input->post('level'),
                'is_active' => $this->input->post('is_active')
            );

            if ($this->Admin_model->add_admin($data)) {
                $this->session->set_flashdata('success', 'Admin berhasil ditambahkan!');
            } else {
                $this->session->set_flashdata('error', 'Gagal menambahkan admin!');
            }

            redirect('admin/admins');
        }
    }

    public function edit_admin($id)
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        $data['title'] = 'Edit Admin';
        $data['admin'] = $this->Admin_model->get_admin_by_id($id);

        $this->load->view('admin/templates/header', $data);
        $this->load->view('admin/admins/edit', $data);
        $this->load->view('admin/templates/footer');
    }

    public function proses_edit_admin($id)
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        $this->load->library('form_validation');

        $this->form_validation->set_rules('username', 'Username', 'required|trim');
        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required|trim');
        $this->form_validation->set_rules('email', 'Email', 'required|trim|valid_email');

        if ($this->form_validation->run() == FALSE) {
            $this->edit_admin($id);
        } else {
            $data = array(
                'username' => $this->input->post('username'),
                'nama_lengkap' => $this->input->post('nama_lengkap'),
                'email' => $this->input->post('email'),
                'level' => $this->input->post('level'),
                'is_active' => $this->input->post('is_active')
            );

            // Add password if provided
            if ($this->input->post('password')) {
                $data['password'] = $this->input->post('password');
            }

            // Check if username is unique (except for current admin)
            if ($this->Admin_model->username_exists($data['username'], $id)) {
                $this->session->set_flashdata('error', 'Username sudah digunakan!');
                redirect('admin/edit_admin/' . $id);
            }

            if ($this->Admin_model->update_admin($id, $data)) {
                $this->session->set_flashdata('success', 'Admin berhasil diupdate!');
            } else {
                $this->session->set_flashdata('error', 'Gagal mengupdate admin!');
            }

            redirect('admin/admins');
        }
    }

    public function delete_admin($id)
    {
        if ($this->session->userdata('level') != 'admin') {
            redirect('admin/dashboard');
        }

        // Prevent deleting self
        if ($id == $this->session->userdata('admin_id')) {
            $this->session->set_flashdata('error', 'Tidak dapat menghapus akun sendiri!');
            redirect('admin/admins');
        }

        if ($this->Admin_model->delete_admin($id)) {
            $this->session->set_flashdata('success', 'Admin berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus admin!');
        }

        redirect('admin/admins');
    }

    public function delete_result($id)
    {
        // Validate ID
        if (!is_numeric($id)) {
            $this->session->set_flashdata('error', 'ID tidak valid!');
            redirect('admin/hasil_tka');
        }

        // Check if result exists
        $result = $this->HasilTKA_model->get_result_by_id($id);
        if (!$result) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan!');
            redirect('admin/hasil_tka');
        }

        // Delete result
        if ($this->HasilTKA_model->delete_result($id)) {
            $this->session->set_flashdata('success', 'Data berhasil dihapus!');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus data!');
        }

        redirect('admin/hasil_tka');
    }
}
