<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

class Drivers extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('users')->where('role', 'driver');
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $builder->groupStart()
                ->like('phone', $q)
                ->orLike('display_name', $q)
                ->orLike('username', $q)
                ->groupEnd();
        }
        $status = $this->request->getGet('status');
        if ($status !== null && $status !== '' && in_array($status, ['active', 'inactive'], true)) {
            $builder->where('jambo_status', $status);
        }
        $drivers = $builder->get()->getResult();
        $content = view('admin/drivers_list', [
            'drivers' => $drivers,
            'filter_q' => $q ?? '',
            'filter_status' => $status ?? '',
        ]);
        return view('admin/layout', ['title' => 'Drivers', 'content' => $content]);
    }

    public function add()
    {
        $name  = trim((string) $this->request->getPost('name'));
        $phone = $this->request->getPost('phone');
        $pin   = $this->request->getPost('pin');
        if (empty($phone) || empty($pin)) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Phone and PIN required');
        }
        if (empty($name)) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Driver name required (shown to customers)');
        }
        $phone = preg_replace('/\D/', '', $phone);
        if (strlen($phone) === 9 && str_starts_with($phone, '7')) {
            $phone = '256' . $phone;
        }
        if (strlen($pin) !== 6 || ! ctype_digit($pin)) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'PIN must be 6 digits');
        }
        $db = \Config\Database::connect();
        if ($db->table('users')->where('phone', $phone)->countAllResults() > 0) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Phone already registered');
        }
        $db->table('users')->insert([
            'username'     => 'driver_' . $phone,
            'display_name' => $name,
            'phone'        => $phone,
            'pin_hash'     => password_hash($pin, PASSWORD_DEFAULT),
            'role'         => 'driver',
            'jambo_status' => 'active',
            'active'       => 1,
            'created_at'   => date('Y-m-d H:i:s'),
            'updated_at'   => date('Y-m-d H:i:s'),
        ]);
        return redirect()->to(base_url('admin/drivers'))->with('message', 'Driver added. Share phone and PIN with driver.');
    }

    public function edit(int $id)
    {
        $db    = \Config\Database::connect();
        $driver = $db->table('users')->where('id', $id)->where('role', 'driver')->get()->getRow();
        if (! $driver) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Driver not found');
        }
        $content = view('admin/driver_edit', ['driver' => $driver]);
        return view('admin/layout', ['title' => 'Edit driver', 'content' => $content]);
    }

    public function update(int $id)
    {
        $db     = \Config\Database::connect();
        $driver = $db->table('users')->where('id', $id)->where('role', 'driver')->get()->getRow();
        if (! $driver) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Driver not found');
        }
        $name = trim((string) $this->request->getPost('display_name'));
        if ($name === '') {
            return redirect()->back()->with('error', 'Name required');
        }
        $db->table('users')->where('id', $id)->update([
            'display_name' => $name,
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);
        return redirect()->to(base_url('admin/drivers'))->with('message', 'Driver name updated.');
    }

    public function toggleStatus(int $id)
    {
        $db  = \Config\Database::connect();
        $row = $db->table('users')->where('id', $id)->where('role', 'driver')->get()->getRow();
        if (! $row) {
            return redirect()->to(base_url('admin/drivers'))->with('error', 'Driver not found');
        }
        $newStatus = ($row->jambo_status ?? 'active') === 'active' ? 'inactive' : 'active';
        $db->table('users')->where('id', $id)->update(['jambo_status' => $newStatus]);
        $db->table('auth_identities')->where('user_id', $id)->like('type', 'access_token')->delete();
        return redirect()->to(base_url('admin/drivers'))->with('message', 'Driver ' . $newStatus . '.');
    }
}
