<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\DriverLocationModel;
use App\Models\SettingModel;

class Dashboard extends BaseController
{
    public function index()
    {
        $db = \Config\Database::connect();
        $drivers = $db->table('users')->where('role', 'driver')->get()->getResult();
        $locModel = model(DriverLocationModel::class);
        $driverList = [];
        foreach ($drivers as $d) {
            $loc = $locModel->where('user_id', $d->id)->first();
            $driverList[] = (object) [
                'id' => $d->id,
                'phone' => $d->phone,
                'username' => $d->username,
                'online' => $loc !== null,
                'lat' => $loc ? $loc->latitude : null,
                'lng' => $loc ? $loc->longitude : null,
            ];
        }
        $settings = model(SettingModel::class);
        $serviceFee = $settings->getValue('service_fee') ?? '0';

        // Dashboard stats: orders
        $ordersCount = $db->table('orders')->countAllResults();
        $ordersPending = $db->table('orders')->whereIn('status', ['pending', 'paid'])->countAllResults();
        $ordersDispatched = $db->table('orders')->where('status', 'dispatched')->countAllResults();
        $ordersDelivered = $db->table('orders')->where('status', 'delivered')->countAllResults();
        $ordersCancelled = $db->table('orders')->where('status', 'cancelled')->countAllResults();

        // Earnings: sum of total_amount for paid, dispatched, delivered
        $earningsRow = $db->table('orders')
            ->selectSum('total_amount')
            ->whereIn('status', ['paid', 'dispatched', 'delivered'])
            ->get()
            ->getRow();
        $totalEarnings = $earningsRow && $earningsRow->total_amount !== null
            ? (float) $earningsRow->total_amount
            : 0.0;

        // Users & drivers counts
        $usersCount = $db->table('users')->where('role', 'user')->countAllResults();
        $driversCount = $db->table('users')->where('role', 'driver')->countAllResults();

        $recentOrders = $db->table('orders')->orderBy('created_at', 'DESC')->limit(5)->get()->getResult();

        $content = view('admin/dashboard', [
            'drivers'          => $driverList,
            'service_fee'      => $serviceFee,
            'orders_count'     => $ordersCount,
            'orders_pending'   => $ordersPending,
            'orders_dispatched'=> $ordersDispatched,
            'orders_delivered' => $ordersDelivered,
            'orders_cancelled' => $ordersCancelled,
            'total_earnings'   => $totalEarnings,
            'users_count'      => $usersCount,
            'drivers_count'    => $driversCount,
            'recent_orders'    => $recentOrders,
        ]);
        return view('admin/layout', ['title' => 'Dashboard', 'content' => $content]);
    }

    public function saveServiceFee()
    {
        $fee = $this->request->getPost('service_fee');
        if ($fee !== null && is_numeric($fee)) {
            model(SettingModel::class)->setValue('service_fee', (string) $fee);
        }
        return redirect()->to(base_url('admin'))->with('message', 'Service fee updated.');
    }
}
