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

class Forgot_password_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    // Cari super admin berdasarkan email
    public function get_by_email($email)
    {
        return $this->db->get_where('super_admin', ['email' => $email])->row();
    }

    // Simpan OTP (versi sederhana)
    public function save_otp($email, $otp)
    {
        $expires = date('Y-m-d H:i:s', strtotime('+10 minutes'));

        $data = [
            'otp_code' => $otp,
            'otp_expires' => $expires
        ];

        return $this->db->where('email', $email)->update('super_admin', $data);
    }

    // Validasi OTP
    public function validate_otp($email, $otp)
    {
        $this->db->where('email', $email);
        $this->db->where('otp_code', $otp);
        $this->db->where('otp_expires >=', date('Y-m-d H:i:s'));
        return $this->db->get('super_admin')->row();
    }

    // Reset password
    public function reset_password($email, $password)
    {
        $data = [
            'password' => password_hash($password, PASSWORD_BCRYPT),
            'otp_code' => NULL,
            'otp_expires' => NULL
        ];

        return $this->db->where('email', $email)->update('super_admin', $data);
    }

    // Hapus OTP yang expired
    public function cleanup_expired()
    {
        $now = date('Y-m-d H:i:s');
        $this->db->set('otp_code', NULL);
        $this->db->set('otp_expires', NULL);
        $this->db->where('otp_expires <', $now);
        $this->db->where('otp_expires IS NOT NULL');
        return $this->db->update('super_admin');
    }
}
