<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

class Login extends BaseController
{
    public function index()
    {
        $session = session();
        if ($session->get('admin_user_id')) {
            $db  = \Config\Database::connect();
            $row = $db->table('users')->where('id', $session->get('admin_user_id'))->get()->getRow();
            if ($row && ($row->role ?? '') === 'admin') {
                return redirect()->to(base_url('admin'));
            }
        }
        return view('admin/login');
    }

    public function attempt()
    {
        $phone = $this->request->getPost('phone');
        $pin   = $this->request->getPost('pin');
        if (empty($phone) || empty($pin)) {
            return redirect()->back()->withInput()->with('error', 'Phone and PIN required');
        }
        $phone = preg_replace('/\D/', '', $phone);
        if (strlen($phone) === 9 && str_starts_with($phone, '7')) {
            $phone = '256' . $phone;
        } elseif (strlen($phone) !== 12 || ! str_starts_with($phone, '256')) {
            return redirect()->back()->withInput()->with('error', 'Invalid phone format');
        }
        $db  = \Config\Database::connect();
        $row = $db->table('users')->where('phone', $phone)->get()->getRow();
        if (! $row || ! password_verify($pin, $row->pin_hash)) {
            return redirect()->back()->withInput()->with('error', 'Invalid phone or PIN');
        }
        if (($row->role ?? '') !== 'admin') {
            return redirect()->back()->withInput()->with('error', 'Access denied');
        }
        session()->set('admin_user_id', $row->id);
        return redirect()->to(base_url('admin'));
    }

    public function logout()
    {
        session()->remove('admin_user_id');
        return redirect()->to(base_url('admin/login'));
    }
}
