<?php

namespace App\Controllers\Auth;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\ActivityLogModel;
use App\Models\CompanySettingModel;

class Login extends BaseController
{
    /**
     * Menampilkan halaman login portal
     */
    public function index()
    {
        // Jika user sudah login, atur redirect sesuai role
        if (session()->get('logged_in')) {
            return $this->_redirectByRole(session()->get('id_role'));
        }

        // Ambil data perusahaan / setting dari DB agar logo dan nama perusahaan tampil di view
        $data['company'] = $this->_getCompanyData();

        return view('auth/login', $data);
    }

    /**
     * Memproses autentikasi user
     */
    public function auth()
    {
        $userModel = new UserModel();
        $db        = \Config\Database::connect();

        $username = trim((string)$this->request->getPost('username'));
        $password = (string)$this->request->getPost('password');

        // Cari data user berdasarkan username
        $user = $userModel->where('username', $username)->first();

        if (!$user) {
            return redirect()->back()->withInput()
                ->with('error', 'Username tidak ditemukan.');
        }

        if (!password_verify($password, $user['password'])) {
            return redirect()->back()->withInput()
                ->with('error', 'Password salah.');
        }

        if ((int)$user['is_active'] !== 1) {
            return redirect()->back()->withInput()
                ->with('error', 'Akun tidak aktif.');
        }

        // Simpan data user ke Session
        session()->set([
            'id_user'      => $user['id_user'],
            'username'     => $user['username'],
            'id_role'      => $user['id_role'],
            'nama_lengkap' => $user['nama_lengkap'],
            'logged_in'    => true,
        ]);

        // Catat riwayat login ke login_logs
        if ($db->tableExists('login_logs')) {
            $db->table('login_logs')->insert([
                'id_user'    => $user['id_user'],
                'ip_address' => $this->request->getIPAddress(),
                'browser'    => $this->request->getUserAgent()->getAgentString(),
            ]);
        }

        // Catat ke Activity Log jika model tersedia
        if (class_exists('App\Models\ActivityLogModel')) {
            (new ActivityLogModel())->logActivity(
                $user['id_user'],
                'User berhasil login ke sistem.'
            );
        }

        return $this->_redirectByRole($user['id_role']);
    }

    /**
     * Redirect pengguna berdasarkan id_role
     */
    private function _redirectByRole($id_role)
    {
        switch ((int)$id_role) {
            case 1:
                return redirect()->to('/superadmin/dashboard');
            case 2:
                return redirect()->to('/owner/dashboard');
            case 3:
                return redirect()->to('/admin/dashboard');
            default:
                session()->destroy();
                return redirect()->to('/login')
                    ->with('error', 'Role tidak dikenali.');
        }
    }

    /**
     * Helper privat untuk mengambil data setting/perusahaan dengan deteksi otomatis tabel
     */
    private function _getCompanyData()
    {
        $db = \Config\Database::connect();
        $companyData = [];

        try {
            // Utamakan CompanySettingModel atau tabel company_settings
            if (class_exists('App\Models\CompanySettingModel')) {
                $companySettingModel = new CompanySettingModel();
                $companyData = $companySettingModel->first() ?? [];
            } elseif ($db->tableExists('company_settings')) {
                $companyData = $db->table('company_settings')->get()->getFirstRow('array') ?? [];
            } elseif ($db->tableExists('company')) {
                $companyData = $db->table('company')->get()->getFirstRow('array') ?? [];
            } elseif ($db->tableExists('settings')) {
                $companyData = $db->table('settings')->get()->getFirstRow('array') ?? [];
            } elseif ($db->tableExists('company_info')) {
                $companyData = $db->table('company_info')->get()->getFirstRow('array') ?? [];
            }

            // Jika tabel dalam format Key-Value (id, key, value)
            if (($db->tableExists('company_settings') || $db->tableExists('settings')) && empty($companyData['company_name'])) {
                $tableName = $db->tableExists('company_settings') ? 'company_settings' : 'settings';
                $rows = $db->table($tableName)->get()->getResultArray();
                foreach ($rows as $r) {
                    if (isset($r['setting_key']) && isset($r['setting_value'])) {
                        $companyData[$r['setting_key']] = $r['setting_value'];
                    } elseif (isset($r['key']) && isset($r['value'])) {
                        $companyData[$r['key']] = $r['value'];
                    }
                }
            }

            // Pemetaan alias logo_url ke logo untuk kompatibilitas tampilan Login View
            if (empty($companyData['logo']) && !empty($companyData['logo_url'])) {
                $companyData['logo'] = $companyData['logo_url'];
            }
        } catch (\Exception $e) {
            log_message('error', 'Gagal mengambil data profil perusahaan pada Login Controller: ' . $e->getMessage());
        }

        return $companyData;
    }
}