<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\JobModel;
use App\Models\WorkerProfileModel; // Need to create this
use App\Models\UserModel;

class Jobs extends ResourceController
{
    protected $modelName = 'App\Models\JobModel';
    protected $format    = 'json';

    // Post a new job (Customer)
    public function create()
    {
        // TODO: Get customer_id from JWT token
        // For now, assume it's passed in body or hardcoded for testing
        
        $rules = [
            'service_id' => 'required|integer',
            'location_lat' => 'required|decimal',
            'location_lng' => 'required|decimal',
            'scheduled_time' => 'required',
        ];

        if (!$this->validate($rules)) {
            return $this->failValidationErrors($this->validator->getErrors());
        }

        $data = $this->request->getPost();
        // $data['customer_id'] = $this->request->user->uid; // From AuthFilter
        $data['status'] = 'pending';
        $data['otp_start'] = rand(100000, 999999);
        $data['otp_end'] = rand(100000, 999999);

        if ($this->model->save($data)) {
            $jobId = $this->model->getInsertID();
            
            // Trigger Matching Engine
            $this->findWorkers($jobId, $data['location_lat'], $data['location_lng']);

            return $this->respondCreated(['id' => $jobId, 'message' => 'Job posted successfully']);
        }

        return $this->failServerError('Failed to create job');
    }

    // List jobs (Worker: available/assigned, Customer: history)
    public function index()
    {
        // TODO: Filter based on role and user ID
        $jobs = $this->model->findAll();
        return $this->respond($jobs);
    }

    // Matching Engine Logic
    private function findWorkers($jobId, $lat, $lng)
    {
        $workerModel = new WorkerProfileModel();
        
        // Haversine Formula to find workers within 50km
        // 6371 is Earth radius in km
        $radius = 50;
        
        $sql = "SELECT user_id, ( 6371 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) ) AS distance 
                FROM worker_profiles 
                HAVING distance < ? 
                ORDER BY distance 
                LIMIT 5";
        
        $query = $workerModel->db->query($sql, [$lat, $lng, $lat, $radius]);
        $workers = $query->getResultArray();

        foreach ($workers as $worker) {
            // TODO: Send FCM Notification
            log_message('info', "Found worker {$worker['user_id']} at {$worker['distance']} km for Job $jobId");
            
            // Create notification record
            // $notificationModel->save([...]);
        }
    }
}
