<?php

namespace App\Models;

use CodeIgniter\Model;

class UserAuthOtpModel extends Model
{
    protected $table = 'user_auth_otp';
    protected $primaryKey = 'id';

    protected $allowedFields = ['otp', 'user_id', 'browser', 'ip_address'];

    
    
    protected $useTimestamps  = true;
    protected $useSoftDeletes = true;
    
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    public function saveOtp($userId, $otp, $browser, $ip)
    {
        $data = [
            'user_id' => $userId,
            'otp' => $otp,
            'browser' => $browser,
            'ip_address' => $ip,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->db->table('user_auth_otp')->insert($data);
    }

    public function hasOtpForToday($userId, $browser, $ip)
    {
        $today = date('Y-m-d');
        $otp = $this->db->table('user_auth_otp')
                        ->where('user_id', $userId)
                        ->where('DATE(created_at)', $today)
                        ->where('browser', $browser)
                        ->where('ip_address', $ip)
                        ->get()
                        ->getRow();

        return $otp ? true : false;
    }

    public function checkOtp($userId, $enteredOtp, int $ttlMinutes = 10)
    {
        // Only consider OTPs created within the TTL window
        $threshold = date('Y-m-d H:i:s', strtotime("-{$ttlMinutes} minutes"));

        $otp = $this->db->table('user_auth_otp')
                        ->where('user_id', $userId)
                        ->where('created_at >=', $threshold)
                        ->orderBy('created_at', 'DESC')
                        ->get()
                        ->getRow();

        if ($otp && $otp->otp === $enteredOtp) {
            // Invalidate OTP (soft delete)
            $this->db->table('user_auth_otp')
                     ->where('id', $otp->id)
                     ->update(['deleted_at' => date('Y-m-d H:i:s')]);
            return true;
        }

        return false;
    }


   

}
