<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\OrderModel;
use App\Models\NotificationModel;

class Orders extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $builder = $db->table('orders')
            ->select('orders.*, u.phone as user_phone, u.display_name as user_name, u.username as user_username, d.phone as driver_phone, d.display_name as driver_name, d.username as driver_username')
            ->join('users u', 'u.id = orders.user_id', 'left')
            ->join('users d', 'd.id = orders.driver_id', 'left')
            ->orderBy('orders.created_at', 'DESC');
        $q = $this->request->getGet('q');
        if ($q !== null && $q !== '') {
            $q = trim($q);
            $builder->groupStart()
                ->like('u.phone', $q)
                ->orLike('u.display_name', $q)
                ->orLike('u.username', $q)
                ->orLike('d.phone', $q)
                ->orLike('d.display_name', $q)
                ->orLike('d.username', $q)
                ->groupEnd();
        }
        $dateFrom = $this->request->getGet('date_from');
        if ($dateFrom !== null && $dateFrom !== '') {
            $from = date('Y-m-d', strtotime($dateFrom));
            if ($from) {
                $builder->where('orders.created_at >=', $from . ' 00:00:00');
            }
        }
        $dateTo = $this->request->getGet('date_to');
        if ($dateTo !== null && $dateTo !== '') {
            $to = date('Y-m-d', strtotime($dateTo));
            if ($to) {
                $builder->where('orders.created_at <=', $to . ' 23:59:59');
            }
        }
        $status = $this->request->getGet('status');
        if ($status !== null && $status !== '') {
            $allowed = ['pending', 'paid', 'dispatched', 'delivered', 'cancelled'];
            if (in_array($status, $allowed, true)) {
                $builder->where('orders.status', $status);
            } elseif ($status === 'pending_group') {
                $builder->whereIn('orders.status', ['pending', 'paid', 'dispatched']);
            }
        }
        $orders = $builder->get()->getResult();
        $content = view('admin/orders_list', [
            'orders' => $orders,
            'filter_q' => $q ?? '',
            'filter_date_from' => $dateFrom ?? '',
            'filter_date_to' => $dateTo ?? '',
            'filter_status' => $status ?? '',
        ]);
        return view('admin/layout', ['title' => 'Orders', 'content' => $content]);
    }

    public function detail(int $id)
    {
        $db    = \Config\Database::connect();
        $order = $db->table('orders')->where('id', $id)->get()->getRow();
        if (! $order) {
            return redirect()->to(base_url('admin/orders'))->with('error', 'Order not found');
        }
        $user   = $db->table('users')->where('id', $order->user_id)->get()->getRow();
        $driver = $order->driver_id ? $db->table('users')->where('id', $order->driver_id)->get()->getRow() : null;
        $location = $order->location_id ? $db->table('locations')->where('id', $order->location_id)->get()->getRow() : null;
        $content = view('admin/order_detail', [
            'order' => $order,
            'user' => $user,
            'driver' => $driver,
            'location' => $location,
        ]);
        return view('admin/layout', ['title' => 'Order #' . $id, 'content' => $content]);
    }

    public function assignDriver(int $id)
    {
        $driverId = (int) $this->request->getPost('driver_id');
        $orderModel = model(OrderModel::class);
        $order = $orderModel->find($id);
        if (! $order) {
            return redirect()->to(base_url('admin/orders'))->with('error', 'Order not found');
        }
        $orderModel->update($id, ['driver_id' => $driverId ?: null, 'status' => $driverId ? 'dispatched' : $order->status]);
        if ($driverId && $order->user_id !== null && (int) $order->user_id > 0) {
            NotificationModel::logOrderStatus((int) $order->user_id, $id, 'dispatched');
        }
        return redirect()->to(base_url('admin/orders/' . $id))->with('message', 'Driver assigned.');
    }
}
