<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class VolunteerApi extends ResourceController
{
    protected $db;

    public function __construct() {
        $this->db = \Config\Database::connect();
    }

    // This updates the volunteer's location every 10 seconds
    public function updateLocation()
    {
        $v_id   = $this->request->getPost('volunteer_id');
        $lat    = $this->request->getPost('lat');
        $lng    = $this->request->getPost('lng');
        $status = $this->request->getPost('status');

        // Manual SQL because CI4 Query Builder doesn't support POINT easily
        $sql = "INSERT INTO volunteer_live_status (volunteer_id, location, is_available) 
                VALUES (?, ST_GeomFromText('POINT($lng $lat)'), ?)
                ON DUPLICATE KEY UPDATE 
                location = ST_GeomFromText('POINT($lng $lat)'), 
                is_available = ?";

        if ($this->db->query($sql, [$v_id, $status, $status])) {
            return $this->respond(['status' => 'success', 'message' => 'Location Updated']);
        }

        return $this->fail('Update failed');
    }

    // This is called when someone is in danger to find nearest warriors
    public function alertVolunteers()
    {
        $danger_lat = $this->request->getPost('lat');
        $danger_lng = $this->request->getPost('lng');
        $radius_km  = 5; // Search within 5km

        // Haversine formula for distance calculation in MySQL
        $sql = "SELECT v.phone, v.name, 
                (6371 * acos(cos(radians(?)) * cos(radians(ST_Y(s.location))) * cos(radians(ST_X(s.location)) - radians(?)) + sin(radians(?)) * sin(radians(ST_Y(s.location))))) AS distance 
                FROM volunteers v
                JOIN volunteer_live_status s ON v.id = s.volunteer_id
                WHERE s.is_available = 1
                HAVING distance <= ?
                ORDER BY distance ASC";

        $query = $this->db->query($sql, [$danger_lat, $danger_lng, $danger_lat, $radius_km]);
        $volunteers = $query->getResultArray();

        // HERE: Trigger your SMS logic for each volunteer found
        foreach ($volunteers as $v) {
            // $this->sendSMS($v['phone'], "Emergency help needed at...");
        }

        return $this->respond($volunteers);
    }
    
    public function registerVolunteer()
    {
        $vModel = new \App\Models\VolunteerModel(); // You'll need to create this model
    
        $data = [
            'name'   => $this->request->getPost('name'),
            'phone'  => $this->request->getPost('phone'),
            'age'    => $this->request->getPost('age'),
            'skills' => $this->request->getPost('skills'),
        ];
    
        if ($vModel->insert($data)) {
            $newId = $vModel->insertID();
            return $this->respond([
                'status' => 'success',
                'volunteer_id' => $newId,
                'message' => 'Volunteer registered'
            ]);
        }
    
        return $this->fail('Registration failed');
    }

}