<?php

namespace App\Libraries;

class SafetyService
{
    protected $db;

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

    public function triggerEmergency($userId, $location = 'Unknown', $token = null)
    {
        // 1. Update the session status
        $builder = $this->db->table('active_sessions');
        if ($token) {
            $builder->where('token', $token);
        } else {
            $builder->where('user_id', $userId)->where('status', 'active');
        }

        $builder->update([
            'status'        => 'EMERGENCY_TRIGGERED',
            'last_location' => $location,
            'triggered_at'  => date('Y-m-d H:i:s')
        ]);

        // 2. Fetch User Name
        $user = $this->db->table('users')->where('id', $userId)->get()->getRowArray();
        $name = $user['name'] ?? 'Your relative';

        // 3. Fetch Contacts
        $contacts = $this->db->table('emergency_contacts')->where('user_id', $userId)->get()->getResultArray();
        
        if (empty($contacts)) return false;

        $message = $name." needs immediate help. Last location: " .$location;

        // 4. Send SMS to each
        foreach ($contacts as $contact) {
            $mobile = preg_replace('/\s+/', '', $contact['contact_phone']);
            if (strpos($mobile, '+91') === 0) $mobile = substr($mobile, 3);
            
            //$this->sendSMS($mobile, $message);
            log_message('error', 'SAFETY SERVICE Alert SENDING to Contacts : ' .$name.' LOCATION: '. $location);
            //FOR MESSAGE BOT
            $emergency = new \App\Libraries\EmergencyService();
            $result = $emergency->triggerAlert($mobile, $message);
        
            if ($result->Status == "Success") {
                return $this->response->setJSON(['status' => 'Alerted!']);
            }
    
        }

        return true;
    }

    
    /*private function sendSMS($mobile, $message)
    {
        $queueFile = FCPATH . '../../prescription_app/otp_queue.json';
        //$queueFile = FCPATH . '../otp_queue.json';
        log_message('error', 'Resolved OTP Queue Path: ' . $queueFile);

        $queueData = [];

        if (file_exists($queueFile)) {
            $queueData = json_decode(file_get_contents($queueFile), true) ?? [];
        }

        $queueData[$mobile] = [
            'mobile' => $mobile,
            'otp' => $message,
            'timestamp' => time()
        ];

        file_put_contents($queueFile, json_encode($queueData, JSON_PRETTY_PRINT));
        log_message('error', 'OTP Queue Saved: ' . json_encode($queueData));
        
    }*/    
}