<?php

namespace App\Controllers;

use App\Models\BiodataModel;
use App\Models\PendidikanModel;
use App\Models\AktivitasModel;

class Admin extends BaseController
{
    protected $biodataModel;
    protected $pendidikanModel;
    protected $aktivitasModel;
    protected $session;
    protected $adminUsername;
    protected $adminPasswordHash;

    public function __construct()
    {
        $this->biodataModel = new BiodataModel();
        $this->pendidikanModel = new PendidikanModel();
        $this->aktivitasModel = new AktivitasModel();
        $this->session = \Config\Services::session();
        
        // Ambil kredensial admin dari .env (dukung format dot/underscore)
        $this->adminUsername = env('admin.username', getenv('ADMIN_USERNAME') ?: 'niellapp');
        $adminPasswordHash   = env('admin.password_hash', getenv('ADMIN_PASSWORD_HASH'));
        
        // Hash default untuk password: Niell123 (hash statis, gunakan .env untuk override)
        $this->adminPasswordHash = $adminPasswordHash ?: '$2y$10$Sv1kffLBC59Q0Q0tOj1yfO2dhoDtJKn2X9xvqZkI5lKAMUxdr.JmG';
    }

    // Check if user is logged in
    protected function checkLogin()
    {
        $isLoggedIn = $this->session->get('admin_logged_in');
        if (!$isLoggedIn) {
            return redirect()->to(base_url('admin/login'));
        }
        return null;
    }

    // Login
    public function login()
    {
        $method = strtolower($this->request->getMethod());
        // Debug: log setiap request ke login
        log_message('debug', 'Login method called - Method: {method}', ['method' => $method]);
        
        // Jika sudah login, redirect ke dashboard
        if ($this->session->has('admin_logged_in') && $this->session->get('admin_logged_in')) {
            log_message('debug', 'Already logged in, redirecting to admin');
            return redirect()->to(base_url('admin'));
        }

        // Pastikan case-insensitive (ada konfigurasi yang mengembalikan 'POST')
        if ($method === 'post') {
            log_message('debug', 'POST request received to login');
            $username = trim((string) $this->request->getPost('username'));
            $password = (string) $this->request->getPost('password');
            // Throttle brute-force attempts (5 tries -> 5 minute lock)
            $lockedUntil = (int) $this->session->get('admin_lock_until');
            $now = time();
            $isLocked = $lockedUntil && $lockedUntil > $now;

            // Debug: cek username dan password (buat username case-insensitive, dan izinkan alias 'nielapp')
            $validUsernames = array_filter([
                strtolower((string) $this->adminUsername),
                'nielapp', // alias typo umum
                'niellapp', // alias double-l dari layar user
            ]);
            $usernameMatch = in_array(strtolower($username), $validUsernames, true);
            $passwordMatch = password_verify($password, $this->adminPasswordHash);
            $isValid = $usernameMatch && $passwordMatch;
            
            log_message('info', 'Admin login attempt user={user} username_match={umatch} password_match={pmatch} valid={valid}', [
                'user'  => $username,
                'umatch' => $usernameMatch ? 'yes' : 'no',
                'pmatch' => $passwordMatch ? 'yes' : 'no',
                'valid' => $isValid ? 'yes' : 'no',
            ]);

            // Jika ter-lock tapi kredensial benar, tetap izinkan login dan reset lock
            if ($isLocked && !$isValid) {
                log_message('info', 'Login blocked: too many attempts (lock until {until})', ['until' => date('c', $lockedUntil)]);
                $data = [
                    'title' => 'Login Admin',
                    'error' => 'Terlalu banyak percobaan login. Coba lagi setelah beberapa menit.',
                    'login_success' => $this->session->getFlashdata('login_success'),
                    'old_username' => $username,
                ];
                return view('admin/login', $data);
            }

            if ($isValid) {
                log_message('info', 'Login credentials valid, setting session');
                
                // Set session
                $this->session->set('admin_logged_in', true);
                $this->session->remove('admin_attempts');
                $this->session->remove('admin_lock_until');
                $this->session->setFlashdata('login_success', 'Login berhasil!');
                
                // Verifikasi session sudah tersimpan
                $checkSession = $this->session->get('admin_logged_in');
                log_message('info', 'Login successful - Session set: {result}, redirecting to admin', ['result' => $checkSession ? 'true' : 'false']);
                
                // Redirect ke panel admin (dashboard) - gunakan header langsung untuk memastikan
                $redirectUrl = base_url('admin');
                log_message('debug', 'Redirect URL: {url}', ['url' => $redirectUrl]);
                
                return redirect()->to($redirectUrl);
            } else {
                log_message('info', 'Login failed - Invalid credentials');
                $attempts = (int) $this->session->get('admin_attempts');
                $attempts++;
                $this->session->set('admin_attempts', $attempts);

                if ($attempts >= 5) {
                    $this->session->set('admin_lock_until', time() + 300); // 5 menit
                }

                $data = [
                    'title' => 'Login Admin',
                    'error' => 'Username atau password salah!',
                    'login_success' => $this->session->getFlashdata('login_success'),
                    'old_username' => $username,
                ];
                return view('admin/login', $data);
            }
        }

        $data = [
            'title' => 'Login Admin',
            'error' => $this->session->getFlashdata('error'),
            'login_success' => $this->session->getFlashdata('login_success'),
            'old_username' => '',
        ];
        return view('admin/login', $data);
    }

    // Logout
    public function logout()
    {
        $this->session->destroy();
        return redirect()->to(base_url('admin/login'));
    }

    // Dashboard
    public function index()
    {
        log_message('debug', 'Admin index called - checking login');
        $check = $this->checkLogin();
        if ($check !== null) {
            log_message('debug', 'Not logged in, redirecting to login');
            return $check;
        }
        
        log_message('debug', 'Logged in, showing dashboard');
        $data = [
            'title' => 'Dashboard Admin',
            'biodata_count' => $this->biodataModel->countAllResults(),
            'pendidikan_count' => $this->pendidikanModel->countAllResults(),
            'aktivitas_count' => $this->aktivitasModel->countAllResults()
        ];
        return view('admin/dashboard', $data);
    }

    // Biodata CRUD
    public function biodata()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }

        $search = trim((string) $this->request->getGet('q'));
        $sort   = $this->request->getGet('sort') ?: 'nama';
        $dir    = strtolower($this->request->getGet('dir') ?: 'asc');

        $builder = $this->biodataModel;

        if ($search !== '') {
            $builder = $builder->groupStart()
                ->like('nama', $search)
                ->orLike('email', $search)
                ->groupEnd();
        }

        $allowedSorts = ['nama', 'email', 'id'];
        if (!in_array($sort, $allowedSorts, true)) {
            $sort = 'nama';
        }
        $dir = $dir === 'desc' ? 'desc' : 'asc';

        // Custom ordering for jenjang supaya runtut (SD -> SMP -> SMA -> S1 -> S2 -> S3)
        if ($sort === 'jenjang') {
            $caseJenjang = "CASE jenjang "
                . "WHEN 'PAUD' THEN 0 "
                . "WHEN 'TK' THEN 1 "
                . "WHEN 'SD' THEN 2 "
                . "WHEN 'SMP' THEN 3 "
                . "WHEN 'SMA' THEN 4 "
                . "WHEN 'SMK' THEN 4 "
                . "WHEN 'D3' THEN 5 "
                . "WHEN 'S1' THEN 6 "
                . "WHEN 'S2' THEN 7 "
                . "WHEN 'S3' THEN 8 "
                . "ELSE 99 END";

            $builder = $builder
                ->orderBy($caseJenjang, $dir)
                ->orderBy('tahun_mulai', $dir)
                ->orderBy('tahun_selesai', $dir)
                ->orderBy('id', 'asc');
        } else {
            $builder = $builder
                ->orderBy($sort, $dir)
                ->orderBy('tahun_mulai', $dir)
                ->orderBy('id', 'asc');
        }

        $perPage  = 10;
        $biodata  = $builder->paginate($perPage, 'biodata');
        $pager    = $this->biodataModel->pager;

        $data = [
            'title' => 'Kelola Biodata',
            'biodata' => $biodata,
            'pager'   => $pager,
            'search'  => $search,
            'sort'    => $sort,
            'dir'     => $dir,
        ];
        return view('admin/biodata/index', $data);
    }

    public function biodata_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $data = [
                'nama' => $this->request->getPost('nama'),
                'alamat' => $this->request->getPost('alamat'),
                'email' => $this->request->getPost('email'),
                'telepon' => $this->request->getPost('telepon'),
                'foto' => $this->request->getPost('foto'),
                'tentang' => $this->request->getPost('tentang'),
                'keahlian' => $this->request->getPost('keahlian'),
                'pengalaman' => $this->request->getPost('pengalaman')
            ];
            
            $this->biodataModel->insert($data);
            return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil ditambahkan!');
        }

        $data['title'] = 'Tambah Biodata';
        return view('admin/biodata/create', $data);
    }

    public function biodata_edit($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $data = [
                'nama' => $this->request->getPost('nama'),
                'alamat' => $this->request->getPost('alamat'),
                'email' => $this->request->getPost('email'),
                'telepon' => $this->request->getPost('telepon'),
                'foto' => $this->request->getPost('foto'),
                'tentang' => $this->request->getPost('tentang'),
                'keahlian' => $this->request->getPost('keahlian'),
                'pengalaman' => $this->request->getPost('pengalaman')
            ];
            
            $this->biodataModel->update($id, $data);
            return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil diupdate!');
        }

        $data = [
            'title' => 'Edit Biodata',
            'biodata' => $this->biodataModel->find($id)
        ];
        return view('admin/biodata/edit', $data);
    }

    public function biodata_delete($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        if (!$this->request->is('post')) {
            return redirect()->back()->with('error', 'Metode tidak diizinkan.');
        }
        
        $this->biodataModel->delete($id);
        return redirect()->to(base_url('admin/biodata'))->with('success', 'Biodata berhasil dihapus!');
    }

    // Pendidikan CRUD
    public function pendidikan()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }

        $search  = trim((string) $this->request->getGet('q'));
        $jenjang = $this->request->getGet('jenjang');
        $sort    = $this->request->getGet('sort') ?: 'tahun_selesai';
        $dir     = strtolower($this->request->getGet('dir') ?: 'desc');

        $builder = $this->pendidikanModel;

        if ($search !== '') {
            $builder = $builder->like('institusi', $search);
        }

        if (!empty($jenjang)) {
            $builder = $builder->where('jenjang', $jenjang);
        }

        $allowedSorts = ['tahun_selesai', 'tahun_mulai', 'jenjang', 'institusi'];
        if (!in_array($sort, $allowedSorts, true)) {
            $sort = 'tahun_selesai';
        }
        $dir = $dir === 'asc' ? 'asc' : 'desc';

        $builder = $builder->orderBy($sort, $dir);

        $perPage     = 10;
        $pendidikan  = $builder->paginate($perPage, 'pendidikan');
        $pager       = $this->pendidikanModel->pager;

        $data = [
            'title' => 'Kelola Pendidikan',
            'pendidikan' => $pendidikan,
            'pager'      => $pager,
            'search'     => $search,
            'filter_jenjang' => $jenjang,
            'sort'       => $sort,
            'dir'        => $dir,
        ];
        return view('admin/pendidikan/index', $data);
    }

    public function pendidikan_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $filePath = null;
            $file = $this->request->getFile('foto');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $targetDir = FCPATH . 'images/pendidikan';
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0755, true);
                }
                if ($file->move($targetDir, $newName)) {
                    $filePath = 'images/pendidikan/' . $newName;
                }
            }

            $data = [
                'jenjang' => $this->request->getPost('jenjang'),
                'institusi' => $this->request->getPost('institusi'),
                'jurusan' => $this->request->getPost('jurusan'),
                'tahun_mulai' => $this->request->getPost('tahun_mulai'),
                'tahun_selesai' => $this->request->getPost('tahun_selesai'),
                'deskripsi' => $this->request->getPost('deskripsi'),
                'foto' => $filePath,
            ];
            
            $this->pendidikanModel->insert($data);
            return redirect()->to(base_url('admin/pendidikan'))->with('success', 'Pendidikan berhasil ditambahkan!');
        }

        $data['title'] = 'Tambah Pendidikan';
        return view('admin/pendidikan/create', $data);
    }

    public function pendidikan_edit($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $existing = $this->pendidikanModel->find($id);
            $filePath = $existing['foto'] ?? null;

            $file = $this->request->getFile('foto');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $targetDir = FCPATH . 'images/pendidikan';
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0755, true);
                }
                if ($file->move($targetDir, $newName)) {
                    $filePath = 'images/pendidikan/' . $newName;
                }
            }

            $data = [
                'jenjang' => $this->request->getPost('jenjang'),
                'institusi' => $this->request->getPost('institusi'),
                'jurusan' => $this->request->getPost('jurusan'),
                'tahun_mulai' => $this->request->getPost('tahun_mulai'),
                'tahun_selesai' => $this->request->getPost('tahun_selesai'),
                'deskripsi' => $this->request->getPost('deskripsi'),
                'foto' => $filePath,
            ];
            
            $this->pendidikanModel->update($id, $data);
            return redirect()->to(base_url('admin/pendidikan'))->with('success', 'Pendidikan berhasil diupdate!');
        }

        $data = [
            'title' => 'Edit Pendidikan',
            'pendidikan' => $this->pendidikanModel->find($id)
        ];
        return view('admin/pendidikan/edit', $data);
    }

    public function pendidikan_delete($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        if (!$this->request->is('post')) {
            return redirect()->back()->with('error', 'Metode tidak diizinkan.');
        }
        
        $this->pendidikanModel->delete($id);
        return redirect()->to(base_url('admin/pendidikan'))->with('success', 'Pendidikan berhasil dihapus!');
    }

    // Aktivitas CRUD
    public function aktivitas()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }

        $search = trim((string) $this->request->getGet('q'));
        $jenis  = $this->request->getGet('jenis');
        $date   = $this->request->getGet('tanggal');
        $sort   = $this->request->getGet('sort') ?: 'tanggal';
        $dir    = strtolower($this->request->getGet('dir') ?: 'desc');

        $builder = $this->aktivitasModel;

        if ($search !== '') {
            $builder = $builder->like('nama_aktivitas', $search);
        }

        if (!empty($jenis)) {
            $builder = $builder->where('jenis', $jenis);
        }

        if (!empty($date)) {
            $builder = $builder->where('tanggal', $date);
        }

        $allowedSorts = ['tanggal', 'jam', 'nama_aktivitas', 'id'];
        if (!in_array($sort, $allowedSorts, true)) {
            $sort = 'tanggal';
        }
        $dir = $dir === 'asc' ? 'asc' : 'desc';

        // For equal dates sort by time as secondary
        $builder = $builder->orderBy($sort, $dir);
        if ($sort !== 'jam') {
            $builder = $builder->orderBy('jam', $dir);
        }

        $perPage    = 10;
        $aktivitas  = $builder->paginate($perPage, 'aktivitas');
        $pager      = $this->aktivitasModel->pager;

        $data = [
            'title' => 'Kelola Aktivitas',
            'aktivitas' => $aktivitas,
            'pager'     => $pager,
            'search'    => $search,
            'filter_jenis' => $jenis,
            'filter_tanggal' => $date,
            'sort'      => $sort,
            'dir'       => $dir,
        ];
        return view('admin/aktivitas/index', $data);
    }

    public function aktivitas_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $filePath = null;
            $file = $this->request->getFile('file_aktivitas');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $targetDir = FCPATH . 'images';
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0755, true);
                }
                if ($file->move($targetDir, $newName)) {
                    $filePath = 'images/' . $newName;
                }
            }

            $data = [
                'tanggal' => $this->request->getPost('tanggal'),
                'jam' => $this->request->getPost('jam'),
                'nama_aktivitas' => $this->request->getPost('nama_aktivitas'),
                'deskripsi' => $this->request->getPost('deskripsi'),
                'jenis' => $this->request->getPost('jenis'),
                'file_path' => $filePath,
            ];
            
            $this->aktivitasModel->insert($data);
            return redirect()->to(base_url('admin/aktivitas'))->with('success', 'Aktivitas berhasil ditambahkan!');
        }

        $data['title'] = 'Tambah Aktivitas';
        return view('admin/aktivitas/create', $data);
    }

    public function aktivitas_edit($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        
        if (strtolower($this->request->getMethod()) === 'post') {
            $existing = $this->aktivitasModel->find($id);
            $filePath = $existing['file_path'] ?? null;

            $file = $this->request->getFile('file_aktivitas');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $newName = $file->getRandomName();
                $targetDir = FCPATH . 'images';
                if (!is_dir($targetDir)) {
                    mkdir($targetDir, 0755, true);
                }
                if ($file->move($targetDir, $newName)) {
                    $filePath = 'images/' . $newName;
                }
            }

            $data = [
                'tanggal' => $this->request->getPost('tanggal'),
                'jam' => $this->request->getPost('jam'),
                'nama_aktivitas' => $this->request->getPost('nama_aktivitas'),
                'deskripsi' => $this->request->getPost('deskripsi'),
                'jenis' => $this->request->getPost('jenis'),
                'file_path' => $filePath,
            ];
            
            $this->aktivitasModel->update($id, $data);
            return redirect()->to(base_url('admin/aktivitas'))->with('success', 'Aktivitas berhasil diupdate!');
        }

        $data = [
            'title' => 'Edit Aktivitas',
            'aktivitas' => $this->aktivitasModel->find($id)
        ];
        return view('admin/aktivitas/edit', $data);
    }

    public function aktivitas_delete($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        if (!$this->request->is('post')) {
            return redirect()->back()->with('error', 'Metode tidak diizinkan.');
        }
        
        $this->aktivitasModel->delete($id);
        return redirect()->to(base_url('admin/aktivitas'))->with('success', 'Aktivitas berhasil dihapus!');
    }
}
