<?php

namespace App\Controllers\Api;

use App\Libraries\JwtAuth;
use App\Models\DriverLocationModel;

class DriverController extends BaseApiController
{
    /**
     * GET api/driver/status - whether this driver is currently online (has a location row).
     */
    public function status()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $db  = \Config\Database::connect();
        $row = $db->table('users')->where('id', $user->id)->get()->getRow();
        if (! $row || ($row->role ?? '') !== 'driver') {
            return $this->error('Only drivers have status', 403);
        }

        $locModel = model(DriverLocationModel::class);
        $loc      = $locModel->where('user_id', $user->id)->first();
        return $this->success(['online' => $loc !== null]);
    }

    /**
     * POST api/driver/offline - remove driver from available pool (delete location row).
     */
    public function offline()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $db  = \Config\Database::connect();
        $row = $db->table('users')->where('id', $user->id)->get()->getRow();
        if (! $row || ($row->role ?? '') !== 'driver') {
            return $this->error('Only drivers can go offline', 403);
        }

        $locModel = model(DriverLocationModel::class);
        $locModel->where('user_id', $user->id)->delete();
        return $this->success(['online' => false]);
    }

    /**
     * POST api/driver/location - upsert driver's current location (ping every 120s when online).
     * Body: { "latitude": 0.0, "longitude": 0.0 }
     */
    public function location()
    {
        $user = JwtAuth::user();
        if (! $user) {
            return $this->error('Unauthorized', 401);
        }
        $db   = \Config\Database::connect();
        $row  = $db->table('users')->where('id', $user->id)->get()->getRow();
        if (! $row || ($row->role ?? '') !== 'driver') {
            return $this->error('Only drivers can update location', 403);
        }

        $json = $this->request->getJSON(true) ?: [];
        $lat  = (float) ($json['latitude'] ?? 0);
        $lng  = (float) ($json['longitude'] ?? 0);
        if ($lat === 0.0 && $lng === 0.0) {
            return $this->error('latitude and longitude required', 400);
        }

        $model = model(DriverLocationModel::class);
        $model->upsertLocation($user->id, $lat, $lng);
        return $this->success(['updated' => true]);
    }
}
