<?php

namespace App\Models;

use CodeIgniter\Model;

class Auth_model extends Model
{
    public function userLogin($username, $password) {
        $mysql = "SELECT  id AS member_id, * FROM members 
                           WHERE username  = '".$username."' 
                             AND password = md5('$password') ";
       // echo $mysql;
      //  log_message('critical', "***** ***** QUERY = ".$mysql );
      //  exit;
        $db = db_connect();
        $query = $db->query($mysql);

        $row = $query->getRowArray();
        if (isset($row)) {
            $sqlDel = "DELETE FROM members_session WHERE member_id = ". $row["member_id"];
            $db->query($sqlDel);
            $pQuery = $db->prepare(static function ($db) {
                return $db->table('members_session')->insert([
                    'member_id'    => '0',
                    'session_id'   => '',
                ]);
            });
            // Collect the Data
            $member_id    = $row["member_id"];
            $session_id   = $this->getRandomString(25).$this->getRandomString(25);
            $results = $pQuery->execute($member_id, $session_id);

            $mysql = "SELECT  * FROM members_session WHERE member_id = ". $row["member_id"];
            $db = db_connect();
            $query = $db->query($mysql);
            $row_session = $query->getRowArray();
            return ["member"=> $row,"session"=> $row_session];
        }
        return [];
    }

 private   function getRandomString($n) {
        return bin2hex(random_bytes($n / 2));
    }
}