<?php

namespace App\Controllers;

use CodeIgniter\Controller;

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

    /**
     * Fetch the live location for a specific secure token
     * Verification: Requires the contact's mobile number
     */
     
     public function getLiveLocation()
    {
        $token = $this->request->getVar('token');
        $rawPhone = $this->request->getVar('contact_phone');
    
        if (!$token || !$rawPhone) {
            return $this->response->setJSON(['status' => 0, 'message' => 'Missing parameters']);
        }
    
        // --- Phone Number Normalization ---
        // Remove spaces, dashes, or brackets
        $cleanPhone = preg_replace('/[^0-9]/', '', $rawPhone);
        
        // If it's exactly 10 digits, prepend +91
        if (strlen($cleanPhone) == 10) {
            $contactPhone = "+91" . $cleanPhone;
        } elseif (strlen($cleanPhone) == 12 && str_starts_with($cleanPhone, '91')) {
            $contactPhone = "+" . $cleanPhone;
        } else {
            $contactPhone = $rawPhone; // Fallback to what user entered
        }
    
        // 1. Find the session
        $session = $this->db->table('active_sessions')
            ->where('token', $token)
            ->get()->getRow();
    
        if (!$session) {
            return $this->response->setJSON(['status' => 0, 'message' => 'Session not found']);
        }
    
        // 2. Validate Authorization
        $isAuthorized = $this->db->table('emergency_contacts')
            ->where('user_id', $session->user_id)
            ->where('contact_phone', $contactPhone)
            ->countAllResults();
    
        if ($isAuthorized == 0) {
            return $this->response->setJSON([
                'status' => 0, 
                'message' => 'Unauthorized contact number: ' . $contactPhone
            ]);
        }
    
        // 3. Extract Lat/Lng from the Google Maps URL
        // URL format: http://google.com/maps?q=28.1234,77.5678
        $lat = 0; $lng = 0;
        if (preg_match('/q=([-\d.]+),([-\d.]+)/', $session->last_location, $matches)) {
            $lat = (float)$matches[1];
            $lng = (float)$matches[2];
        }
    
        $user = $this->db->table('users')->where('id', $session->user_id)->get()->getRow();
    
        return $this->response->setJSON([
            'status' => 1,
            'user_name' => $user->name ?? 'User',
            'lat' => $lat,
            'lng' => $lng,
            'updated_at' => $session->last_heartbeat,
            'is_emergency' => ($session->status === 'EMERGENCY_TRIGGERED')
        ]);
    }

    
    /*public function getRouteHistory($token = null)
    {
        // If $token is not in the URL segment, check the Query Parameter (?token=)
        if ($token === null) {
            $token = $this->request->getVar('token');
        }
    
        if (!$token) {
            return $this->response->setJSON(['status' => 0, 'message' => 'Token is required']);
        }
    
        $history = $this->db->table('location_history')
            ->where('token', $token)
            ->orderBy('created_at', 'ASC')
            ->get()
            ->getResultArray();
    
        $points = [];
        foreach ($history as $row) {
            // Regex to pull coordinates from the Google URL stored in DB
            if (preg_match('/q=([-\d.]+),([-\d.]+)/', $row['location_url'], $matches)) {
                $points[] = [
                    'lat' => (float)$matches[1],
                    'lng' => (float)$matches[2],
                    'time' => $row['created_at']
                ];
            }
        }
    
        return $this->response->setJSON(['status' => 1, 'route' => $points]);
    }*/
    
    public function getRouteHistory()
    {
        $token = $this->request->getVar('token');
        $history = $this->db->table('location_history')
            ->where('token', $token)
            ->orderBy('created_at', 'ASC')
            ->get()->getResultArray();
    
        $points = [];
        $totalDistance = 0;
        $prevLat = null;
        $prevLng = null;
        
        for ($i = 0; $i < count($history); $i++) {
            // 1. Initialize local variables for this iteration
            $lat = 0;
            $lng = 0;
        
            // 2. Extraction Logic (New columns vs Regex Fallback)
            if (!empty($history[$i]['lat']) && !empty($history[$i]['lng'])) {
                $lat = (float)$history[$i]['lat'];
                $lng = (float)$history[$i]['lng'];
            } else if (!empty($history[$i]['location_url'])) {
                if (preg_match('/q=([-\d.]+),([-\d.]+)/', $history[$i]['location_url'], $matches)) {
                    $lat = (float)$matches[1];
                    $lng = (float)$matches[2];
                }
            }
        
            // Skip if we couldn't find coordinates for this specific point
            if ($lat == 0 || $lng == 0) continue;
        
            // 3. Distance Calculation
            // We check if $prevLat is NOT null, meaning this is at least the second valid point
            if ($prevLat !== null && $prevLng !== null) {
                $dist = $this->haversine($prevLat, $prevLng, $lat, $lng);
                if ($dist < 5) { // Only add distance if the jump is less than 5km (filters errors)
                    $totalDistance += $dist;
                }            }
        
            // 4. Update "Previous" variables for the NEXT iteration
            $prevLat = $lat;
            $prevLng = $lng;
        
            // 5. Build the data for the frontend
            $points[] = [
                'lat' => $lat,
                'lng' => $lng,
                'speed' => $history[$i]['speed'] ?? 0,
                'battery' => $history[$i]['battery'] ?? 0,
                'time' => $history[$i]['created_at']
            ];
        }

        return $this->response->setJSON([
            'status' => 1, 
            'route' => $points, 
            'total_km' => round($totalDistance, 2)
        ]);
    }
    
    private function haversine($lat1, $lon1, $lat2, $lon2) {
        $earthRadius = 6371; // Kilometers
        $dLat = deg2rad($lat2 - $lat1);
        $dLon = deg2rad($lon2 - $lon1);
        $a = sin($dLat/2) * sin($dLat/2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($dLon/2) * sin($dLon/2);
        return $earthRadius * (2 * atan2(sqrt($a), sqrt(1-$a)));
    }


}