<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'name',
        'email',
        'password',
        'mobile',
        'address',
        'pin_code',
        'user_type',
        'role',
        'reliability_score',
        'seller_reliability_score',
        'renter_reliability_score',
        'is_blocked',
        'bgv_cleared',
        'otp',
        'otp_expires_at',
        'is_verified'
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation
    protected $validationRules = [
        'name'     => 'required|min_length[3]|max_length[255]',
        'email'    => 'required|valid_email|is_unique[users.email,id,{id}]',
        'mobile'   => 'required|min_length[10]|max_length[15]',
        'password' => 'required|min_length[6]|max_length[255]',
        'pin_code' => 'required|min_length[4]|max_length[10]',
        'user_type' => 'required|in_list[seller,buyer]',
    ];

    protected $validationMessages = [
        'email' => [
            'is_unique' => 'This email is already registered.',
        ],
    ];

    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    /**
     * Generate and save OTP for user
     */
    public function generateOTP($userId)
    {
        $otp = random_int(100000, 999999);
        $expiresAt = date('Y-m-d H:i:s', strtotime('+10 minutes'));

        return $this->update($userId, [
            'otp' => $otp,
            'otp_expires_at' => $expiresAt
        ]) ? $otp : false;
    }

    /**
     * Verify OTP
     */
    public function verifyOTP($email, $otp)
    {
        $user = $this->where('email', $email)->first();

        if (!$user) {
            return false;
        }

        // Check if OTP matches and not expired
        if ($user['otp'] == $otp && strtotime($user['otp_expires_at']) > time()) {
            // Mark as verified and clear OTP
            $this->update($user['id'], [
                'is_verified' => 1,
                'otp' => null,
                'otp_expires_at' => null
            ]);
            return $user;
        }

        return false;
    }

    /**
     * Get user by email
     */
    public function getUserByEmail($email)
    {
        return $this->where('email', $email)->first();
    }

    /**
     * Verify password login
     */
    public function verifyPassword($email, $password)
    {
        $user = $this->where('email', $email)->first();

        if (!$user) {
            return false;
        }

        if (! empty($user['password']) && password_verify($password, $user['password'])) {
            return $user;
        }

        return false;
    }
}
