<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\UserModel;
use App\Models\AuthModel;
use App\Models\ContactModel;
use CodeIgniter\API\ResponseTrait;

class Auth extends BaseController
{
    use ResponseTrait;

    // STEP 1: Check if user exists
    public function checkUser()
    {
        $phone = trim($this->request->getVar('phone')); // works for POST, GET, JSON

        //log_message('error', 'PHONE RECEIVED: ' . ($phone ?? 'NULL'));

        if (empty($phone)) {
            return $this->respond(['exists' => false]);
        }

        $model = new UserModel();

        $count = $model->where('phone', $phone)->countAllResults();

        //log_message('error', 'PHONE Database count: ' . $count);

        return $this->respond([
            'exists' => $count > 0 ? true : false
        ]);
    }

    // STEP 2: Send OTP (Login or Register)
    public function handleAuth()
    {
        $phone = trim($this->request->getVar('phone'));
        $isExisting = $this->request->getVar('is_existing') === 'true';

        if (empty($phone)) {
            return $this->fail('Phone required');
        }
        
        // Special test number shortcut
        if ($phone == '9999999999') {
            return $this->respond([
                'status' => '200',
                'message' => 'Test OTP sent',
                'debug_otp' => '123456'
            ]);
            
        }

        $otp = rand(100000, 999999);
        $this->saveOtpQueue($phone, $otp);
        
        $emailOtp = $otp;
        $expiry = date("Y-m-d H:i:s", strtotime("+5 minutes"));

        $authModel = new AuthModel();
        $authModel->saveOtp($phone, $otp, $emailOtp, $expiry);

        return $this->respond([
            'status' => 200,
            'message' => 'OTP sent successfully',
            'debug_otp' => $otp // remove in production
        ]);
    }

    // STEP 3: Verify OTP and finalize registration/login
    public function verifyOtpAndFinalize()
    {
        $phone = trim($this->request->getVar('phone'));
        $otp = trim($this->request->getVar('otp'));
        $name = trim($this->request->getVar('name'));
        $pin = trim($this->request->getVar('user_pin'));
        $panic = trim($this->request->getVar('panic_pin'));
    
        $model = new UserModel();
        $contactmodel = new ContactModel();
    
        // 1. Initial lookup
        $user = $model->where('phone', $phone)->first();
    
        // 2. OTP Verification (Check this BEFORE doing heavy data processing)
        if ($phone !== '9999999999') { // Skip OTP for test number
            if (!$this->verifyOtpQueue($phone, $otp)) {
                return $this->fail('Invalid or expired OTP');
            }
        }
    
        // 3. If User doesn't exist, Create them first
        if (!$user) {
            // Generate a permanent QR identity token for new users
            $newQrToken = "QR_" . time();
    
            $model->insert([
                'phone'             => $phone,
                'name'              => $name,
                'user_pin'          => $pin,
                'panic_pin'         => $panic,
                'wallet_balance'    => 5,
                'active_qr_token'   => $newQrToken,
                'is_setup_complete' => 1
            ]);
    
            // Fetch the newly created user to get their ID and fields
            $user = $model->where('phone', $phone)->first();
        }
    
        // 4. Now that we definitely have a $user, fetch contacts
        $contacts = $contactmodel->where('user_id', $user['id'])
                         ->select('contact_name, contact_phone') // Select both
                         ->get()
                         ->getResultArray();

        // REMOVE THIS LINE: $contactList = array_column($contacts, 'contact_phone');
        
        // Directly assign the result array (it will be like [{"contact_name": "Mom", "contact_phone": "..."}])
        $user['emergency_contacts'] = $contacts;
        
        return $this->respond([
            'status' => 200,
            'user_data' => $user
        ]);

    }

    // ================= OTP QUEUE ==================

    private function saveOtpQueue($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));
        
    }

    private function verifyOtpQueue($mobile, $otp)
    {
        $authModel = new AuthModel();
    
        $result = $authModel->verifyOtp($mobile, $otp);
        log_message('debug', ' Line 120 of verifyOtpQueue  : ' . $otp);
    
        if (!$result) {
            return false;
        }
    
        // OTP verified successfully → delete it after use (important)
        $authModel->where('mobile', $mobile)->delete();
    
        return true;
    }

    public function logout()
    {
        return $this->response->setJSON([
            'status' => true,
            'message' => 'Logged out successfully'
        ]);
    }

    public function options()
    {
        return $this->response->setStatusCode(200);
    }
}
