<?php
defined('BASEPATH') OR exit('No direct script access allowed');

require_once APPPATH . 'core/MY_Controller.php';

/**
 * OTP Controller
 * Handles OTP generation and verification via AJAX
 */
class Otp extends Auth_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('Otp_model');
        $this->load->library('mailer');
    }
    
    /**
     * Send OTP to user's email
     */
    public function send() {
        if (!$this->input->is_ajax_request()) {
            $this->error('Invalid request', [], 400);
            return;
        }
        
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        $purpose = $input['purpose'] ?? 'transaction';
        $metadata = $input['metadata'] ?? [];
        
        $result = $this->send_transaction_otp($purpose, $metadata);
        
        if ($result['success']) {
            $this->success($result['message'], [
                'masked_email' => $result['masked_email'] ?? '',
                'expires_in' => $result['expires_in'] ?? 300
            ]);
        } else {
            $this->error($result['message'], [
                'cooldown' => $result['cooldown'] ?? 0
            ]);
        }
    }
    
    /**
     * Verify OTP
     */
    public function verify() {
        if (!$this->input->is_ajax_request()) {
            $this->error('Invalid request', [], 400);
            return;
        }
        
        // Get JSON input
        $input = json_decode(file_get_contents('php://input'), true);
        $otp_code = $input['otp'] ?? '';
        $purpose = $input['purpose'] ?? 'transaction';
        
        if (empty($otp_code) || strlen($otp_code) !== 6) {
            $this->error('Please enter a valid 6-digit OTP');
            return;
        }
        
        $result = $this->verify_transaction_otp($otp_code, $purpose);
        
        if ($result['success']) {
            // Store verification in session for the current request
            $this->session->set_userdata('otp_verified_' . $purpose, time());
            $this->success($result['message']);
        } else {
            $this->error($result['message']);
        }
    }
    
    /**
     * Check if OTP was recently verified (within 5 minutes)
     */
    public function status() {
        if (!$this->input->is_ajax_request()) {
            $this->error('Invalid request', [], 400);
            return;
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        $purpose = $input['purpose'] ?? 'transaction';
        
        $verified_at = $this->session->userdata('otp_verified_' . $purpose);
        $is_valid = $verified_at && (time() - $verified_at) < 300; // 5 minutes
        
        $this->success('OK', ['verified' => $is_valid]);
    }
}
