<?php
namespace App\Models;

use CodeIgniter\Model;

class userAccess extends baseModel
{
   // protected $db;

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

    public function startUserLogin($in)
    {
        //  $sqlQ =
        //      'SELECT m.id as member_id, m.*,mp.* FROM members m LEFT JOIN members_profile mp ON m.id=mp.member_id WHERE m.id =12';

        $username = trim($in['username']);
        $password = trim($in['password']);
        $sqlQ = "SELECT m.id as mid, m.*,mp.* 
            FROM members m LEFT 
            JOIN members_profile mp ON m.id=mp.member_id 
            WHERE LOWER(m.username) = LOWER('$username') 
            AND m.password=md5('$password') ";

        $query = $this->db->query($sqlQ);
        $data['profile_data'] = $query->getResultArray();

        if (count($data['profile_data']) == 1) {
            $data['profile_data'][0]['password'] = '**REMOVED**';
            $member_id = $data['profile_data'][0]['mid'];
            $member_uid = $data['profile_data'][0]['uuid'];
            $data['profile_data'][0]['member_id'] = $member_id; // fixing issue of member id used in profile
            $possibeLayout =['33010','33015','33020','33025','33030','33035','33040'];
            $computedDash = $possibeLayout[rand(0,6)];// 33010; // Recomendation engine points 
            $sessionToken = $this->generateSession($member_id);
            return $inx = [
                'session_token' => $sessionToken,
                'member_id' => $member_id,
                'member_uuid' => $member_uid,
                'guid' => $member_uid,
                'profile' => $data['profile_data'][0],
                'settings' => [],
                'layout'=> ['dash'=>$computedDash],
                'preferences' => [],
                'measurement_units' => [
                    'weight' => [
                        ['name' => 'Kilogram', 'code' => 'KG', 'text' => 'Kg.'],
                        ['name' => 'Pound', 'code' => 'LB', 'text' => 'Lbs.'],
                    ],
                ],
                'status' => 0,
                'status' => 1,
                'raw_data' => $in,
            ];
        }

            return $inx = [
                'session_token' => '',
                'settings' => [],
                'preferences' => [],
                'measurement_units' => [
                    'weight' => [
                        ['name' => 'Kilogram', 'code' => 'KG', 'text' => 'Kg.'],
                        ['name' => 'Pound', 'code' => 'LB', 'text' => 'Lbs.'],
                    ],
                ],
                'status' => 0,
                'raw_data' => $in,
                'error_msg' => 'Invalid username or password',
            ];
    }

    public function startFleetLogin($in)
    {
        //  $sqlQ =
        //      'SELECT m.id as member_id, m.*,mp.* FROM members m LEFT JOIN members_profile mp ON m.id=mp.member_id WHERE m.id =12';

        $username = trim($in['username']);
        $password = trim($in['password']);
        $sqlQ = "SELECT m.id as mid, m.*,mp.* 
            FROM members m LEFT 
            JOIN members_profile mp ON m.id=mp.member_id 
            WHERE LOWER(m.username) = LOWER('$username') 
            AND m.password=md5('$password') ";

        $query = $this->db->query($sqlQ);
        $data['profile_data'] = $query->getResultArray();

        if (count($data['profile_data']) == 1) {
            $data['profile_data'][0]['password'] = '**REMOVED**';
            $member_id = $data['profile_data'][0]['mid'];
            $member_uid = $data['profile_data'][0]['uuid'];
            $data['profile_data'][0]['member_id'] = $member_id; // fixing issue of member id used in profile
            $possibeLayout =['33010','33015','33020','33025','33030','33035','33040'];
            $computedDash = $possibeLayout[rand(0,6)];// 33010; // Recomendation engine points
            $sessionToken = $this->generateSession($member_id);
            return $inx = [
                'session_token' => $sessionToken,
                'member_id' => $member_id,
                'member_uuid' => $member_uid,
                'guid' => $member_uid,
                'profile' => $data['profile_data'][0],
                'settings' => [],
                'layout'=> ['dash'=>$computedDash],
                'preferences' => [],
                'measurement_units' => [
                    'weight' => [
                        ['name' => 'Kilogram', 'code' => 'KG', 'text' => 'Kg.'],
                        ['name' => 'Pound', 'code' => 'LB', 'text' => 'Lbs.'],
                    ],
                ],
                'status' => 0,
                'status' => 1,
                'raw_data' => $in,
            ];
        }

        return $inx = [
            'session_token' => '',
            'settings' => [],
            'preferences' => [],
            'measurement_units' => [
                'weight' => [
                    ['name' => 'Kilogram', 'code' => 'KG', 'text' => 'Kg.'],
                    ['name' => 'Pound', 'code' => 'LB', 'text' => 'Lbs.'],
                ],
            ],
            'status' => 0,
            'raw_data' => $in,
            'error_msg' => 'Invalid username or password',
        ];
    }

    private function generateSession($member_id)
    {
        $loc = $this->getIPAddress();

        // do the seesion stuffs here - set up all permissions
        $tk = '';
        for ($i = 1; $i < 20; $i++) {
            $tk .= rand(11111, 99999);
        }

        $sqlQ = "DELETE FROM members_session WHERE member_id = $member_id ";
        $query = $this->db->query($sqlQ);

        $sqlQ =
            "INSERT INTO members_session (session,member_id,loc) VALUES('" .
            $tk .
            "'," .
            $member_id .
            ",'" .
            $loc .
            "') ";
        $query = $this->db->query($sqlQ);

        // Create HX
        $sqlQ =
            "INSERT INTO members_login_hx (member_id,channel,loc) VALUES ($member_id,'Desktop','" .
            $loc .
            "')";
        $this->db->query($sqlQ);
        return $tk;
    }

}

/*
CREATE TABLE members_login_hx (
	id SERIAL,
	member_id INT REFERENCES members(id) NOT NULL,	
	channel VARCHAR(15), 
	added timestamp without time zone DEFAULT now(),
	loc INET
	);
ALTER TABLE ONLY members_login_hx
    ADD CONSTRAINT members_login_hx_id_key UNIQUE (id);*/
