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

class Password_reset_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    /**
     * Create reset password token
     */
    public function create_reset_token($email, $token, $expires_at) {
        $data = [
            'email' => $email,
            'token' => $token,
            'created_at' => date('Y-m-d H:i:s'),
            'expires_at' => $expires_at,
            'used' => 0
        ];

        $this->db->insert('password_resets', $data);
        return $this->db->insert_id();
    }

    /**
     * Get valid token
     */
    public function get_valid_token($token) {
        $this->db->where('token', $token);
        $this->db->where('expires_at >', date('Y-m-d H:i:s'));
        $this->db->where('used', 0);
        return $this->db->get('password_resets')->row();
    }

    /**
     * Mark token as used
     */
    public function mark_token_used($token) {
        $this->db->where('token', $token);
        $this->db->update('password_resets', ['used' => 1]);
        return $this->db->affected_rows() > 0;
    }

    /**
     * Clean expired tokens
     */
    public function clean_expired_tokens() {
        $this->db->where('expires_at <', date('Y-m-d H:i:s'));
        $this->db->delete('password_resets');
        return $this->db->affected_rows();
    }

    /**
     * Delete token by email
     */
    public function delete_token_by_email($email) {
        $this->db->where('email', $email);
        $this->db->delete('password_resets');
        return $this->db->affected_rows();
    }
}
