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

class Auth extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model(['User_model','Siswa_model']);
        $this->load->library(['upload','session','form_validation','email']);
        $this->load->helper(['form','url','cookie']);
        $this->load->config('email'); // pakai config/email.php
    }

    /* ===========================
     * LOGIN SISWA
     * =========================== */
    public function login_siswa() {
        if ($this->input->post()) {
            $identity = $this->input->post('identity');
            $password = $this->input->post('password');
            $remember = $this->input->post('remember');

            $user = $this->User_model->login($identity, $password, 'Siswa');

            if ($user) {
                $siswa = $this->db->get_where('siswa', ['UserID' => $user->UserID])->row();
                $this->session->set_userdata([
                    'UserID'    => $user->UserID,
                    'SiswaID'   => $siswa ? $siswa->SiswaID : null,
                    'username'  => $user->Username,
                    'role'      => $user->RoleName,
                    'role_id'   => $user->RoleID,
                    'logged_in' => true
                ]);

                if ($remember) set_cookie("remember_me", $user->UserID, 3600*24*30);
                redirect('dashboard');
            } else {
                $this->session->set_flashdata('error', 'Login gagal. Cek kembali email/HP dan password.');
                redirect('login_siswa');
            }
        } else {
            $this->load->view('auth/login_siswa');
        }
    }

    /* ===========================
     * LOGIN ADMIN
     * =========================== */
    public function login_admin() {
        if ($this->input->post()) {
            $identity = $this->input->post('identity');
            $password = $this->input->post('password');
            $remember = $this->input->post('remember');

            $user = $this->User_model->login_admin($identity, $password);

            if ($user) {
                $this->session->set_userdata([
                    'user_id'   => $user->UserID,
                    'username'  => $user->Username,
                    'role'      => $user->RoleName,
                    'role_id'   => $user->RoleID,
                    'logged_in' => true
                ]);

                if ($remember) set_cookie("remember_me", $user->UserID, 3600*24*30);
                redirect('dashboard');
            } else {
                $this->session->set_flashdata('error', 'Login gagal. Cek kembali email dan password.');
                redirect('login_admin');
            }
        } else {
            $this->load->view('auth/login_admin');
        }
    }

    /* ===========================
     * LUPA PASSWORD / OTP / RESET
     * =========================== */
    public function forgot_password() {
        if ($this->input->post()) {
            $email = $this->input->post('email', true);
            $phone = $this->input->post('phone', true);

            $user = $this->db->where('Email', $email)
                             ->where('Phone', $phone)
                             ->get('users')->row();

            if ($user) {
                $otp     = rand(100000, 999999);
                $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));

                $this->db->where('UserID', $user->UserID)
                         ->update('users', ['ResetToken'=>$otp, 'ResetExpires'=>$expires]);

                $this->_send_email(
                    $user->Email,
                    "Kode OTP Reset Password",
                    "Kode OTP Anda adalah <b>$otp</b>. Berlaku 10 menit."
                );

                $this->session->set_flashdata('success', 'OTP sudah dikirim ke email Anda.');
                redirect('verify_otp');
            } else {
                $this->session->set_flashdata('error', 'Email dan No HP tidak cocok dengan data kami.');
                redirect('forgot_password');
            }
        } else {
            $this->load->view('auth/forgot_password');
        }
    }

    public function verify_otp() {
        if ($this->input->post()) {
            $otp = $this->input->post('otp', true);

            $user = $this->db->where('ResetToken', $otp)
                             ->where('ResetExpires >=', date('Y-m-d H:i:s'))
                             ->get('users')->row();

            if ($user) {
                $this->session->set_userdata('reset_user_id', $user->UserID);
                redirect('reset_password');
            } else {
                $this->session->set_flashdata('error', 'OTP salah atau sudah kadaluarsa.');
                redirect('verify_otp');
            }
        } else {
            $this->load->view('auth/verify_otp');
        }
    }

    public function reset_password() {
        if ($this->input->post()) {
            $password         = $this->input->post('password', true);
            $confirm_password = $this->input->post('confirm_password', true);
            $user_id          = $this->session->userdata('reset_user_id');

            if (!$user_id) {
                $this->session->set_flashdata('error', 'Sesi reset password tidak valid.');
                redirect('forgot_password');
            }

            if ($password !== $confirm_password) {
                $this->session->set_flashdata('error', 'Password dan konfirmasi password tidak sama.');
                redirect('reset_password');
            }

            $this->db->where('UserID', $user_id)
                     ->update('users', [
                         'PasswordHash' => password_hash($password, PASSWORD_DEFAULT),
                         'Password'     => $password,
                         'ResetToken'   => null,
                         'ResetExpires' => null
                     ]);

            $this->session->unset_userdata('reset_user_id');
            $this->session->set_flashdata('success', 'Password berhasil direset. Silakan login.');
            redirect('login_siswa');
        } else {
            $this->load->view('auth/reset_password');
        }
    }

    /* ===========================
     * REGISTER SISWA
     * =========================== */
    public function register() {
        if ($this->input->post()) {
            $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
            $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.Email]');
            $this->form_validation->set_rules('tanggal_lahir', 'Tanggal Lahir', 'required');
            $this->form_validation->set_rules('phone', 'No HP', 'required|is_unique[users.Phone]');
            $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
            $this->form_validation->set_rules('rekomendasi_lpk', 'Rekomendasi LPK', 'trim');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('auth/register'); return;
            }

            $this->db->trans_begin();

            try {
                // --- Data user --- //
                $nama_lengkap = $this->input->post('nama_lengkap', true);
                $email        = $this->input->post('email', true);
                $phone        = $this->input->post('phone', true);
                $password     = $this->input->post('password', true);

                $user_id = $this->User_model->create_user([
                    'Username'      => $nama_lengkap,
                    'Email'         => $email,
                    'Phone'         => $phone,
                    'PasswordPlain' => $password,
                    'RoleID'        => 3, // siswa
                    'CreatedAt'     => date('Y-m-d H:i:s')
                ]);
                if (!$user_id) {
                    $err = $this->db->error();
                    log_message('error','Register gagal insert users: '.$err['code'].' '.$err['message']);
                    throw new Exception('Gagal membuat user.');
                }

                // --- Data siswa --- //
                $siswa_data = [
                    'UserID'          => $user_id,
                    'NamaLengkap'     => $nama_lengkap,
                    'TanggalLahir'    => $this->input->post('tanggal_lahir', true),
                    'Usia'            => $this->input->post('usia', true),
                    'TinggiBadan'     => $this->input->post('tinggi_badan', true),
                    'BeratBadan'      => $this->input->post('berat_badan', true),
                    'JenisKelamin'    => $this->input->post('jenis_kelamin', true),
                    'Domisili'        => $this->input->post('domisili', true),
                    'Pendidikan'      => $this->input->post('pendidikan', true),
                    'NamaSekolah'     => $this->input->post('nama_sekolah', true),
                    'Jurusan'         => $this->input->post('jurusan', true),
                    'Tato'            => $this->input->post('tato', true),
                    'Penglihatan'     => $this->input->post('penglihatan', true),
                    'InfoPendaftaran' => $this->input->post('info_pendaftaran', true),
                    'RekomendasiLPK'  => $this->input->post('rekomendasi_lpk', true),
                    'LPKID'           => $this->input->post('lpk_id') ?: 1, // default HSI
                    'Email'           => $email,
                    'NoHP'            => $phone,
                    'StatusID'        => 1, // Calon
                    'CreatedAt'       => date('Y-m-d H:i:s')
                ];
                $this->db->insert('siswa', $siswa_data);

                // --- Upload dokumen --- //
                $required_files = ['pas_foto','ktp','kk','akta'];
                $optional_files = ['pasport','ijazah'];
                $uploaded_data  = [];

                $upload_path = './uploads/siswa/' . $user_id . '/';
                if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);

                // validasi minimal (wajib)
                foreach ($required_files as $f) {
                    if (empty($_FILES[$f]['name'])) {
                        throw new Exception(ucfirst(str_replace('_',' ',$f))." wajib diupload!");
                    }
                }

                $all_files = array_merge($required_files, $optional_files);
                foreach ($all_files as $f) {
                    if (!empty($_FILES[$f]['name'])) {
                        $config = [
                            'upload_path'   => $upload_path,
                            'allowed_types' => 'jpg|jpeg|png|pdf',
                            'max_size'      => 2048,
                            'file_name'     => $f.'_'.time()
                        ];
                        $this->upload->initialize($config);
                        if ($this->upload->do_upload($f)) {
                            $uploaded_data[$f] = $this->upload->data('file_name');
                        } else {
                            throw new Exception("Upload gagal untuk {$f}: ".$this->upload->display_errors('',''));
                        }
                    }
                }

                foreach ($uploaded_data as $jenis => $filename) {
                    $this->db->insert('dokumensiswa', [
                        'SiswaID'      => NULL,          // sementara NULL
                        'UserID'       => $user_id,      // relasi via UserID
                        'JenisDokumen' => $jenis,
                        'FilePath'     => $filename,
                        'UploadedAt'   => date('Y-m-d H:i:s')
                    ]);
                }

                // Commit dulu, lalu kirim email invoice
                $this->db->trans_commit();

                // === Email invoice ===
                $this->load->model('Biaya_model');
                $biaya = method_exists($this->Biaya_model, 'get_current')
                       ? $this->Biaya_model->get_current('pelatihan')
                       : null;
                $total = $biaya ? (float)$biaya->Nominal : 7500000;
                $linkUpload = site_url('calon/pembayaran'); // pastikan route ada

                $this->email->from($this->config->item('smtp_user') ?: 'fakethis889@gmail.com', 'HSI Academy Jepang');
                $this->email->to($email);
                $this->email->subject('[HSI] Invoice Pendaftaran Siswa');
                $this->email->set_mailtype('html');
                $this->email->message($this->_invoice_email_body($nama_lengkap, $total, $linkUpload));
                if (!$this->email->send()) {
                    log_message('error', 'Email invoice gagal: '.$this->email->print_debugger());
                }

                $this->session->set_flashdata('success', 'Registrasi berhasil. Invoice sudah dikirim ke email Anda.');
                redirect('login_siswa');

            } catch (Exception $e) {
                $this->db->trans_rollback();
                $this->session->set_flashdata('error', $e->getMessage());
                redirect('register');
            }
        } else {
            $data['lpk_list'] = $this->db->get('lpk')->result();
            $this->load->view('auth/register', $data);
        }
    }

    /* ===========================
     * UTIL
     * =========================== */

    /** Template email invoice */
    private function _invoice_email_body($nama, $nominal, $url) {
        $rupiah = 'Rp '.number_format((float)$nominal, 0, ',', '.');
        return "
        <div style='font-family:Arial,Helvetica,sans-serif;line-height:1.6'>
            <h3 style='margin:0 0 12px'>Invoice Pendaftaran – HSI Academy Jepang</h3>
            <p>Halo <b>{$nama}</b>,</p>
            <p>Terima kasih sudah registrasi. Total biaya pendaftaran Anda:</p>
            <p style='font-size:18px;margin:6px 0'><b>{$rupiah}</b></p>
            <p>Silakan login dan lakukan pembayaran lalu upload bukti pada website HSI Academy:</p>
            <hr>
            <p style='color:#666;font-size:12px'>Email ini dikirim otomatis. Mohon tidak membalas.</p>
        </div>";
    }

    /** Kirim email umum (dipakai OTP/dll) */
    private function _send_email($to, $subject, $message) {
        $this->email->from($this->config->item('smtp_user') ?: 'fakethis889@gmail.com', 'HSI Academy Jepang');
        $this->email->to($to);
        $this->email->subject($subject);
        $this->email->set_mailtype('html');
        $this->email->message($message);
        if (!$this->email->send()) {
            log_message('error', 'Email gagal dikirim: '.$this->email->print_debugger());
        }
    }

    public function add_lpk() {
        if ($this->input->is_ajax_request()) {
            $nama   = $this->input->post('nama_lpk', true);
            $alamat = $this->input->post('alamat', true);
            $kontak = $this->input->post('kontak', true);

            if (empty($nama)) {
                echo json_encode(['success'=>false,'message'=>'Nama LPK wajib diisi']); return;
            }

            $this->db->insert('lpk', [
                'NamaLPK'   => $nama,
                'Alamat'    => $alamat,
                'Kontak'    => $kontak,
                'CreatedAt' => date('Y-m-d H:i:s')
            ]);
            $lpk_id = $this->db->insert_id();

            echo json_encode(['success'=>true,'lpk_id'=>$lpk_id,'nama_lpk'=>$nama]);
        }
    }

    public function logout() {
        $this->session->sess_destroy();
        delete_cookie('remember_me');
        redirect('login_siswa');
    }
}
