<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class AlertController extends ResourceController
{
    protected $format = 'json';

    // Your existing logic integrated here
    private function saveOtpQueue($mobile, $otp) {
        // Adjust this path to ensure it points to your existing queue file
        $queueFile = FCPATH . '../prescription_app/otp_queue.json';
        
        $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));
    }

    /**
     * Triggered by Flutter when Panic is pressed
     * URL: https://safety.famee.in/api/trigger-alert
     */
    public function trigger()
    {
        $this->response->setHeader('Access-Control-Allow-Origin', '*');
        
        $phone = $this->request->getPost('phone');
        $message = "EMERGENCY! I need help. My location: " . $this->request->getPost('location');

        // Instead of an OTP, we send your Alert Message through the same queue
        // Assuming your 'prescription_app' logic reads this JSON to send SMS
        $this->saveOtpQueue($phone, $message);

        return $this->respond(['status' => 200, 'message' => 'Alert queued successfully']);
    }
}