<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class SessionController extends ResourceController
{
    protected $format = 'json';
    protected $db;

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


    public function get_wallet()
    {
        //$data = $this->request->getJSON(true);(int)($data['duration_minutes'] ?? 10);
        $userId = (int)($this->request->getVar('user_id'));
        //log_message('error', 'get_wallet Line 22 : ' . $userId);
        if (!$userId) {
            return $this->response->setJSON([
                'status' => 0,
                'message' => 'User ID missing'
            ]);
        }
    
        $user = $this->db->table('users')->where('id', $userId)->get()->getRowArray();
    //log_message('error', 'get_wallet Line 31 : ' . $userId);
        if (!$user) {
            return $this->response->setJSON([
                'status' => 0,
                'message' => 'User not found'
            ]);
        }
    
        return $this->response->setJSON([
            'status' => 1,
            'user' => $user
        ]);
    }


    // 1️⃣ Start Session (Direct or QR)
    public function startSession()
    {
        $userId   = $this->request->getVar('user_id');
        $vaultNote = $this->request->getVar('vault_note') ?? '';
        $duration = $this->request->getVar('duration');
        $token     = $this->request->getVar('token');
        $type      = $this->request->getVar('type');
log_message('error', 'startSession Line 54 : ' . $userId);
        if (!$userId) return $this->respond(['status'=>0,'message'=>'User required']);

        $user = $this->db->table('users')->where('id', $userId)->get()->getRowArray();
        if (!$user) return $this->respond(['status'=>0,'message'=>'User not found']);

        /*if ($user['wallet_balance'] <= 0) {
            return $this->respond(['status'=>0,'message'=>'Insufficient balance']);
        }*/
//log_message('error', 'startSession Line 72 : ' . $userId);

        $this->db->table('active_sessions')->insert([
            'token' => $token,
            'user_id' => $userId,
            'duration_minutes' => $duration,
            'vault_note' => $vaultNote,
            'type' => $type,
            'status' => 'ACTIVE',
            'started_at' => date('Y-m-d H:i:s'),
            'expires_at' => date('Y-m-d H:i:s', time() + ($duration * 60)),
            'last_heartbeat' => date('Y-m-d H:i:s'),
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $this->respond([
            'status' => 1,
            'token' => $token,
            'message' => 'Session started'
        ]);
    }

    public function update_wallet()
    {
        //$data = $this->request->getJSON(true);
        log_message('error', 'update_wallet Line 103 : ');
        $userId = $this->request->getVar('user_id');
    
        $user = $this->db->table('users')->where('id',$userId)->get()->getRowArray();
        if (!$user) return $this->respond(['status'=>0,'message'=>'User not found']);
    
        $newBalance = $this->request->getVar('wallet_balance');
        $active_qr_token = $this->request->getVar('active_qr_token');
    log_message('error', 'update_wallet Line 109 : ' . $newBalance);
        $this->db->table('users')->where('id',$userId)->update([
            'wallet_balance' => $newBalance,
            'active_qr_token' => $active_qr_token
        ]);
    
        return $this->respond([
            'status'=>1,
            'wallet_balance'=>$newBalance
        ]);
    }

    
    // 2️⃣ Heartbeat
    /*public function heartbeat()
    {
        //$data = $this->request->getJSON(true);
        //(int)($this->request->getVar('user_id'));
        //log_message('error', 'heartbeat Line 126 : ');
        $token = $this->request->getVar('token');
        $location = $this->request->getVar('location');

        if (!$token) return $this->respond(['status'=>0,'message'=>'Token required']);
//log_message('error', 'heartbeat Line 131 : TOKEN '.$token);
        $session = $this->db->table('active_sessions')
            ->where('token', $token)
            ->get()->getRowArray();

        if (!$session) {
            return $this->respond(['status'=>0,'message'=>'Session not found']);
        }

        $this->db->table('active_sessions')
            ->where('token', $token)
            ->update([
                'last_location' => $location,
                'last_heartbeat' => date('Y-m-d H:i:s')
            ]);

        return $this->respond(['status'=>1,'message'=>'Heartbeat updated']);
    }*/
    
    /*public function heartbeat()
    {
        $token = $this->request->getPost('token');
        $location = $this->request->getPost('location');
    
        $session = $this->db->table('active_sessions')->where('token', $token)->get()->getRowArray();
    
        if ($session) {
            // 1. UPDATE the current status for the live map
            $this->db->table('active_sessions')
                ->where('token', $token)
                ->update(['last_location' => $location, 'last_heartbeat' => date('Y-m-d H:i:s')]);
    
            // 2. INSERT into history for the trail/route
            $this->db->table('location_history')->insert([
                'token' => $token,
                'user_id' => $session['user_id'],
                'location_url' => $location
            ]);
    
            return $this->response->setJSON(['status' => 1]);
        }
        return $this->response->setJSON(['status' => 0]);
    }*/

    public function heartbeat()
    {
        $token    = $this->request->getPost('token');
        $location = $this->request->getPost('location'); // The map link
        $lat      = $this->request->getPost('lat');
        $lng      = $this->request->getPost('lng');
        $speed    = $this->request->getPost('speed');
        $battery  = $this->request->getPost('battery');
    
        $session = $this->db->table('active_sessions')->where('token', $token)->get()->getRowArray();
    
        if ($session) {
            // Prepare data for update/insert
            $data = [
                'last_location'  => $location,
                'lat'            => (!empty($lat)) ? $lat : null,
                'lng'            => (!empty($lng)) ? $lng : null,
                'speed'          => (!empty($speed)) ? $speed : 0,
                'battery'        => (!empty($battery)) ? $battery : 0,
                'last_heartbeat' => date('Y-m-d H:i:s')
            ];
    
            // 1. UPDATE current live status
            $this->db->table('active_sessions')
                ->where('token', $token)
                ->update($data);
    
            // 2. INSERT into history for the trail
            $this->db->table('location_history')->insert([
                'token'        => $token,
                'user_id'      => $session['user_id'],
                'location_url' => $location, // Keeping for backup
                'lat'          => $data['lat'],
                'lng'          => $data['lng'],
                'speed'        => $data['speed'],
                'battery'      => $data['battery'],
                'created_at'   => date('Y-m-d H:i:s')
            ]);
    
            return $this->response->setJSON(['status' => 1]);
        }
        return $this->response->setJSON(['status' => 0]);
    }

    public function status()
    {
        $user_id = $this->request->getVar('user_id');
log_message('error', 'status Line 141 : ' . $user_id);
        if (!$user_id) {
            return $this->respond([
                'status' => 0,
                'message' => 'User ID required'
            ]);
        }

        $db = \Config\Database::connect();
log_message('error', 'status Line 150 : Checking DB');
        // adjust table name & fields to your DB
        $builder = $db->table('active_sessions');
        $builder->where('user_id', $user_id);
        $builder->where('status', 'active');
        $builder->orderBy('id', 'DESC');
        $builder->limit(1);
        $session = $builder->get()->getRowArray();
log_message('error', 'status Line 157 : Builder done' );

        if (!$session) {
            return $this->respond([
                'status' => 1,
                'active' => false
            ]);
        }

        $startTime = strtotime($session['started_at']); // DB datetime
        $duration = (int)$session['duration_minutes']*60; // example: 600
        $now = time();
log_message('error', 'status Line 170 : Time don' . $duration);
        $elapsed = $now - $startTime;
        $remaining = $duration - $elapsed;

        if ($remaining <= 0) {
            // auto expire session
            $builder->where('id', $session['id'])
                    ->update(['status' => 'ENDED']);

            return $this->respond([
                'status' => 1,
                'active' => false
            ]);
        }

        return $this->respond([
            'status' => 1,
            'active' => true,
            'token' => $session['active_qr_token'],
            'start_time' => $startTime, // epoch seconds
            'duration' => $duration,
            'remaining' => $remaining
        ]);
    }

    public function triggerEmergency()
    {
        $token = $this->request->getVar('token');
        $location = $this->request->getVar('location');
    
        $session = $this->db->table('active_sessions')->where('token', $token)->get()->getRowArray();
        if (!$session) return $this->fail("Invalid token");
    
        // Use the Service
        $safety = new \App\Libraries\SafetyService();
        $success = $safety->triggerEmergency($session['user_id'], $location, $token);
    
        return $this->respond(['status' => 1, 'message' => 'Alerts sent']);
    }

    public function testSms (){
        log_message('error', 'TEST SMS Alert sent to Contacts : ' );
        $message = " needs immediate help. Last known location: " ;
        
        $this->sendSMS('9026239435', $message);
        log_message('error', 'TEST SMS Alert sent to Contacts : ' );
        //echo "Sms sent message " . $message;
    }
    
    private function sendSMS($mobile, $otp)
    {
        $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' => $otp,
            'timestamp' => time()
        ];

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

    // 4️⃣ Stop Session (Safe or Panic)
    public function stopSession()
    {
        //$data = $this->request->getJSON(true);
        $token = $this->request->getVar('token');
        $status = $this->request->getVar('status');

        if (!$token) return $this->fail("Token required");
        
        if ($status == 'PANIC') {
            log_message('error', 'stopSession Line 232 : EMERGENCY PANIC');
            //CALL EMERGENCY
            return $this->respond(['status'=>1,'message'=>'Emergency Alert!']);
        }

        $this->db->table('active_sessions')
            ->where('token',$token)
            ->update([
                'status' => $status,
                'ended_at' => date('Y-m-d H:i:s')
                //'stopped_at' => date('Y-m-d H:i:s')
            ]);

        return $this->respond(['status'=>1,'message'=>'Session stopped']);
    }

    // 5️⃣ Validate QR Scan
    public function validateQr()
    {
        $token = $this->request->getVar('token');
        $userId = $this->request->getVar('user_id');

        if (!$userId || !$token) return $this->fail("Invalid data");

        $user = $this->db->table('users')->where('id',$userId)->get()->getRowArray();

        if (!$user) return $this->fail("User not found");
log_message('error', 'validateQr Line 259 : Validate success' . $userId);
        if ($user['wallet_balance'] <= 0) {
            return $this->respond(['status'=>0,'message'=>'Low balance']);
        }

        if ($user['active_qr_token'] !== $token) {
            return $this->respond(['status'=>0,'message'=>'Invalid QR']);
        }
log_message('error', 'validateQr Line 267 : Validate success' . $token);
        /*$newToken = "QR_" . time();

        $this->db->table('users')->where('id',$userId)->update([
            'wallet_balance' => $user['wallet_balance'] - 1,
            'active_qr_token' => $newToken
        ]);*/

        return $this->respond([
            'status'=>200,
            'new_token'=>$user['active_qr_token'],
            'wallet_balance'=>$user['wallet_balance'],
            'message'=>'QR validated'
        ]);
    }


    // 6️⃣ Get My QR
    public function myQr()
    {
        $userId = $this->request->getGet('user_id');

        $user = $this->db->table('users')->where('id',$userId)->get()->getRowArray();
        if (!$user) return $this->fail("User not found");

        return $this->respond([
            'status'=>1,
            'wallet_balance'=>$user['wallet_balance'],
            'token'=>$user['active_qr_token']
        ]);
    }
}
