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

class Token_model extends CI_Model
{

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

    // Get all tokens
    public function get_all_tokens()
    {
        $this->db->order_by('GENERATE_TIME', 'DESC');
        return $this->db->get('tbl_token')->result();
    }

    // Get active tokens
    public function get_active_tokens()
    {
        $this->db->where('EXPIRED', '0');
        $this->db->order_by('GENERATE_TIME', 'DESC');
        return $this->db->get('tbl_token')->result();
    }

    // Get token by value
    public function get_token($token)
    {
        $this->db->where('TOKEN', $token);
        return $this->db->get('tbl_token')->row();
    }

    // Check if token is valid (not expired)
    public function is_token_valid($token)
    {
        $this->db->where('TOKEN', $token);
        $this->db->where('EXPIRED', '0');
        return $this->db->get('tbl_token')->num_rows() > 0;
    }

    // Generate new token
    public function generate_token()
    {
        $token = strtoupper(substr(md5(uniqid(rand(), true)), 0, 5));

        $data = array(
            'TOKEN' => $token,
            'GENERATE_TIME' => date('Y-m-d H:i:s'),
            'EXPIRED' => '0'
        );

        if ($this->db->insert('tbl_token', $data)) {
            return $token;
        }
        return false;
    }

    // Expire a token
    public function expire_token($id)
    {
        $this->db->where('ID_TOKEN', $id);
        return $this->db->update('tbl_token', array('EXPIRED' => '1'));
    }

    // Delete token
    public function delete_token($id)
    {
        $this->db->where('ID_TOKEN', $id);
        return $this->db->delete('tbl_token');
    }
}
