<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

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

    public function show(int $id)
    {
        $db = \Config\Database::connect();
        $user = $db->table('users')->where('id', $id)->where('role !=', 'admin')->get()->getRow();
        if (! $user) {
            return redirect()->to(base_url('admin/users'))->with('error', 'User not found');
        }
        $builder = $db->table('orders')->where('user_id', $id)->orderBy('created_at', 'DESC');
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $builder->groupStart()
                ->like('id', $q)
                ->orLike('total_amount', $q)
                ->orLike('created_at', $q)
                ->orLike('order_type', $q)
                ->orLike('status', $q)
                ->groupEnd();
        }
        $status = $this->request->getGet('status');
        if ($status !== null && $status !== '' && in_array($status, ['pending', 'paid', 'dispatched', 'delivered', 'cancelled'], true)) {
            $builder->where('status', $status);
        }
        $orders = $builder->get()->getResult();
        $content = view('admin/user_detail', [
            'user' => $user,
            'orders' => $orders,
            'filter_q' => $q ?? '',
            'filter_status' => $status ?? '',
        ]);
        return view('admin/layout', ['title' => 'User #' . $id, 'content' => $content]);
    }

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