<?php

namespace App\Controllers;

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

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

    public function __construct()
    {
        $this->biodataModel = new BiodataModel();
        $this->pendidikanModel = new PendidikanModel();
        $this->aktivitasModel = new AktivitasModel();
        $this->galleryModel = new GalleryModel();
        $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';
    }

    /**
     * Ambil waktu created_at terbaru dari model (format raw).
     */
    protected function getLatestCreatedAt($model): ?string
    {
        $row = $model->select('created_at')->orderBy('created_at', 'DESC')->first();
        return $row['created_at'] ?? null;
    }

    // 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 (only in development)
        if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
            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')) {
            if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
                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') {
            if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
                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',
                    'hideNav' => true,
                    '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');
                if (defined('ENVIRONMENT') && ENVIRONMENT === 'development') {
                    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',
                    'hideNav' => true,
                    'error' => 'Username atau password salah!',
                    'login_success' => $this->session->getFlashdata('login_success'),
                    'old_username' => $username,
                ];
                return view('admin/login', $data);
            }
        }

        $data = [
            'title' => 'Login Admin',
            'hideNav' => true,
            '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');

        // Siapkan waktu upload terakhir per entitas
        $formatTime = static function (?string $ts): string {
            if (!$ts) {
                return '-';
            }
            $time = is_numeric($ts) ? (int) $ts : strtotime($ts);
            return $time ? date('d M Y H:i', $time) : '-';
        };

        $data = [
            'title' => 'Dashboard Admin',
            'biodata_count' => $this->biodataModel->countAllResults(),
            'pendidikan_count' => $this->pendidikanModel->countAllResults(),
            'aktivitas_count' => $this->aktivitasModel->countAllResults(),
            'latest_times' => [
                'biodata' => $formatTime($this->getLatestCreatedAt($this->biodataModel)),
                'pendidikan' => $formatTime($this->getLatestCreatedAt($this->pendidikanModel)),
                'aktivitas' => $formatTime($this->getLatestCreatedAt($this->aktivitasModel)),
            ],
            'gallery' => $this->galleryModel->orderBy('created_at', 'DESC')->findAll(6),
        ];
        return view('admin/dashboard', $data);
    }

    // Biodata CRUD
    public function biodata()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $search = $this->request->getGet('q');
        $jk     = $this->request->getGet('jk');
        $status = $this->request->getGet('status');
        // Default ke data terbaru agar sinkron dengan tampilan publik
        $sort   = $this->request->getGet('sort') ?? 'id_desc';
        $builder = $this->biodataModel;
        if ($search) {
            $builder = $builder->groupStart()
                ->like('nama', $search)
                ->orLike('email', $search)
                ->orLike('alamat', $search)
                ->groupEnd();
        }
        if ($jk) {
            $builder = $builder->where('jenis_kelamin', $jk);
        }
        if ($status) {
            $builder = $builder->where('status', $status);
        }
        [$sortField, $sortDir] = explode('_', $sort . '_');
        $sortField = $sortField === 'id' ? 'id' : 'nama';
        $sortDir   = strtolower($sortDir) === 'desc' ? 'DESC' : 'ASC';
        $builder   = $builder->orderBy($sortField, $sortDir);

        $biodata = $builder->paginate(10);

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

    public function biodata_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            $fotoPath = null;
            $file = $this->request->getFile('foto_file');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $fotoPath = 'uploads/' . $newName;
            }

            $data = [
                'nama' => $this->request->getPost('nama'),
                'email' => $this->request->getPost('email'),
                'telepon' => $this->request->getPost('telepon'),
                'alamat' => $this->request->getPost('alamat'),
                'tempat_lahir' => $this->request->getPost('tempat_lahir'),
                'tanggal_lahir' => $this->request->getPost('tanggal_lahir'),
                'agama' => $this->request->getPost('agama'),
                'kewarganegaraan' => $this->request->getPost('kewarganegaraan'),
                'status_pernikahan' => $this->request->getPost('status_pernikahan'),
                'golongan_darah' => $this->request->getPost('golongan_darah'),
                'linkedin' => $this->request->getPost('linkedin'),
                'github' => $this->request->getPost('github'),
                'foto' => $fotoPath,
                'jenis_kelamin' => $this->request->getPost('jenis_kelamin'),
                'status' => $this->request->getPost('status'),
                '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;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            $existing = $this->biodataModel->find($id);
            $fotoPath = $existing['foto'] ?? null;
            $file = $this->request->getFile('foto_file');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $fotoPath = 'uploads/' . $newName;
            }

            $data = [
                'nama' => $this->request->getPost('nama'),
                'email' => $this->request->getPost('email'),
                'telepon' => $this->request->getPost('telepon'),
                'alamat' => $this->request->getPost('alamat'),
                'tempat_lahir' => $this->request->getPost('tempat_lahir'),
                'tanggal_lahir' => $this->request->getPost('tanggal_lahir'),
                'agama' => $this->request->getPost('agama'),
                'kewarganegaraan' => $this->request->getPost('kewarganegaraan'),
                'status_pernikahan' => $this->request->getPost('status_pernikahan'),
                'golongan_darah' => $this->request->getPost('golongan_darah'),
                'linkedin' => $this->request->getPost('linkedin'),
                'github' => $this->request->getPost('github'),
                'foto' => $fotoPath,
                'jenis_kelamin' => $this->request->getPost('jenis_kelamin'),
                'status' => $this->request->getPost('status'),
                '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;
        }
        $method = strtolower($this->request->getMethod());
        if ($method !== '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!');
    }

    public function biodata_detail($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }

        $item = $this->biodataModel->find($id);
        if (!$item) {
            return redirect()->to(base_url('admin/biodata'))->with('error', 'Biodata tidak ditemukan.');
        }

        return view('admin/biodata/detail', [
            'title'   => 'Detail Biodata',
            'biodata' => $item,
        ]);
    }

    // Pendidikan CRUD
    public function pendidikan()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $search = $this->request->getGet('q');
        $jenjang = $this->request->getGet('jenjang');
        $sort = $this->request->getGet('sort') ?? 'lulus_desc';

        $builder = $this->pendidikanModel;
        if ($search) {
            $builder = $builder->groupStart()
                ->like('institusi', $search)
                ->orLike('jurusan', $search)
                ->groupEnd();
        }
        if ($jenjang) {
            $builder = $builder->where('jenjang', $jenjang);
        }
        switch ($sort) {
            case 'masuk_asc':
                $builder = $builder->orderBy('tahun_mulai', 'ASC');
                break;
            case 'masuk_desc':
                $builder = $builder->orderBy('tahun_mulai', 'DESC');
                break;
            case 'lulus_asc':
                $builder = $builder->orderBy('tahun_selesai', 'ASC');
                break;
            case 'lulus_desc':
            default:
                $builder = $builder->orderBy('tahun_selesai', 'DESC');
                break;
        }

        $pendidikan = $builder->paginate(10);

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

    public function pendidikan_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            $file = $this->request->getFile('image');
            $imagePath = null;
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $imagePath = 'uploads/' . $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'),
                'image_path' => $imagePath,
            ];
            
            $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;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            $existing = $this->pendidikanModel->find($id);
            $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'),
                'image_path' => $existing['image_path'] ?? null,
            ];

            $file = $this->request->getFile('image');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $data['image_path'] = 'uploads/' . $newName;
            }
            
            $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;
        }
        $method = strtolower($this->request->getMethod());
        if ($method !== '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 = $this->request->getGet('q');
        $jenis  = $this->request->getGet('jenis');
        $tanggalFilter = $this->request->getGet('tanggal');
        $sort   = $this->request->getGet('sort') ?? 'tanggal_desc';

        $builder = $this->aktivitasModel;
        if ($search) {
            $builder = $builder->like('nama_aktivitas', $search);
        }
        if ($tanggalFilter) {
            $builder = $builder->where('tanggal', $tanggalFilter);
        }
        if ($jenis) {
            $builder = $builder->where('jenis', $jenis);
        }
        if ($sort === 'tanggal_asc') {
            $builder = $builder->orderBy('tanggal', 'ASC')->orderBy('jam', 'ASC');
        } else {
            $builder = $builder->orderBy('tanggal', 'DESC')->orderBy('jam', 'DESC');
        }

        $aktivitas = $builder->paginate(10);

        $data = [
            'title' => 'Kelola Aktivitas',
            'aktivitas' => $aktivitas,
            'pager' => $this->aktivitasModel->pager,
            'search' => $search,
            'jenis' => $jenis,
            'tanggal' => $tanggalFilter,
            'sort' => $sort,
        ];
        return view('admin/aktivitas/index', $data);
    }

    public function aktivitas_create()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            // handle upload
            $file = $this->request->getFile('media');
            $filePath = null;
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $filePath = 'uploads/' . $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;
        }
        $method = strtolower($this->request->getMethod());
        
        if ($method === 'post') {
            $existing = $this->aktivitasModel->find($id);
            $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' => $existing['file_path'] ?? null,
            ];

            $file = $this->request->getFile('media');
            if ($file && $file->isValid() && !$file->hasMoved()) {
                $uploadDir = FCPATH . 'uploads';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0775, true);
                }
                $newName = $file->getRandomName();
                $file->move($uploadDir, $newName);
                $data['file_path'] = 'uploads/' . $newName;
            }
            
            $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;
        }
        $method = strtolower($this->request->getMethod());
        if ($method !== '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!');
    }

    // Gallery
    public function gallery()
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }

        $method = strtolower($this->request->getMethod());
        if ($method === 'post') {
            $title = trim((string) $this->request->getPost('title'));
            $description = trim((string) $this->request->getPost('description'));
            $file = $this->request->getFile('image');

            if (!$file || !$file->isValid()) {
                return redirect()->back()->with('error', 'File foto tidak valid.');
            }

            $uploadDir = FCPATH . 'uploads';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0775, true);
            }
            $newName = $file->getRandomName();
            $file->move($uploadDir, $newName);
            $imagePath = 'uploads/' . $newName;

            $this->galleryModel->insert([
                'title' => $title ?: 'Foto',
                'description' => $description ?: null,
                'image_path' => $imagePath,
            ]);

            return redirect()->to(base_url('admin/gallery'))->with('success', 'Foto berhasil ditambahkan.');
        }

        $data = [
            'title' => 'Kelola Gallery',
            'items' => $this->galleryModel->orderBy('created_at', 'DESC')->findAll(),
        ];
        return view('admin/gallery/index', $data);
    }

    public function gallery_delete($id)
    {
        $check = $this->checkLogin();
        if ($check !== null) {
            return $check;
        }
        $item = $this->galleryModel->find($id);
        if ($item) {
            $path = FCPATH . $item['image_path'];
            if (is_file($path)) {
                @unlink($path);
            }
            $this->galleryModel->delete($id);
        }
        return redirect()->to(base_url('admin/gallery'))->with('success', 'Foto dihapus.');
    }
}
