<?php

namespace App\Http\Controllers;

use Firebase\JWT\JWT;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
class LoginController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        
    }
    

        protected function jwt($user, $token)
    {
        $privateKey = <<<EOD
-----BEGIN RSA PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDeJP//iZZW3EdS
DGO4863U0UHElV4dZnLhmNq/3TcO0P0orI21F+wG0QGr4lCwbj0QbM2xx2/MZ0Wh
wkg8ibFJlf/aVHvhR5qMP8Is+omUBkdbbz3EArbmeIg+m45XVvUAa4aKjStq74OS
CbYDcq5GkWwwsrlZQYRkE9SbqDsW/4ELm9stN4GNTfhKG2sKA9oEyZKbJpRsZ8uA
Aa3+pHxQZH02OFOjRHBhNC1/HrcZJvSBiO0TVXf8f9w7QMrwlwN3aeuTr33vS3A9
9vsYUuCBfIrwgw1fgmFnUvdnvpDZm9blTnhmwxRRraqUMEcfq7jASobtqwaOxeN8
nOq9rqsdAgMBAAECggEAIdIUxpkyMh293wRDX3p8DfFg97a8+jFpjqa4sSrTEdao
IFvrBDX06ZHDFSHy4nWaJujFxUoFn6NectLzMAJPo1IqvpkLtj/yS+V+IN5w+UAe
d5F/YBsAsSSLK6r/uBTlXq/AL1JwWIrIJ4ECfNJmLZjA1cY0GV5z80+gmCU7/9NU
ZLRIrG4LuRoOe06+qJRMMzIarDbFO8AZzAjVSm3ZFDdnYGRAFKD3FtB+TZk2diX+
0DNMLbqJYQPO0TJ57VBufJGptm5+1pyk37BqUAQWbVIrGCoMYzgskB3/CxeCNfi9
aQB24HEIXyiUeV+RV8d8BX7Dd1GVP4B188KQ/QABsQKBgQDi/P3sZME1yft7Qv8R
S3+/3IycrgsSbnprLgr/xzfv0oYQGHZ3PPulN/wq2tFyk/8h6WGDj6Q6ppszBLlI
lAkjJScZr0XStYPamjcUY+l6PbKzq7RqREEOBBc1u+e1coiENy1JlQ5HcyVv/752
ghZYNk+JJflnd+B7OK9ZhIU1cQKBgQD6iYXMica1LyU23ZQ1YTpc6sZykQt8fOiO
05sDIn2d8XlFUiia/w7sw74uWKbIoCkmwEDNjqErSNDtt6DWA/N6HcaOLkYw5XiM
WYKEPbLtf83o4vxh5GEnC3I475rPyxaLxHX+2WfcBXLimLPdECwn9Y9Iq8VwmLwg
T5AhcKiKbQKBgCbW/2QJwX3AuAVZa2e8MXnU9UKCDWbz/IKGeF9X6Vxh+4qZhPvW
NYEJ2V5D3v7qEAfvdT4bwBBBHeFW95VRr1aSLuSYNyxc3tjy9mXIytSd5gwUX2Sn
lTIexRHuuzEzDeUBxAAJP04+h7NoYWDJ1aT2dhmTo99uhbzP8EEzCdAhAoGBAK3l
oLJM+1ithaYkfIfkma7+4omI9bENvhnM9K5jVU+42RTtpvOWkBR09V+T9wgQax/T
l+dV1baGj0ZBC+kgyvH7EuODaQLtdBPu2THS5YwGBrVcQBPugiSoxDqSzSDn9RlE
XyZqXrWQLqLrnQSXAh8mSbMGT0ANM581unQLj2CtAoGBAILSkGto0pTEMzKL7u9C
CfiyrmVDv44L1d8Ur4JuLMrrm3M3pBKc5xeND/33dQ9wp43+tizAVcTzT8wY63Iz
6Oe6Btv1RqEVfwE2ph6cTPdLDD8r9O53rLv+91OGJ3w8i1eu/O7cOGfdOnGAYJ9R
HzZBMAD45yLzAR43uRMImaWF
-----END RSA PRIVATE KEY-----
EOD;
        $payload = [
            'iss' => "e-medicalgroup.com",  
            'sub' => $user,  
            'iat' => time(),  
            'token' => $token,
            'exp' => time() +  60*60*24, 
        ];

        return JWT::encode($payload,  $privateKey, 'RS256');
    }
   

    public function loginApp(Request $request)
    {
        if (!$request->has('user') || !$request->has('password'))
        {
            $res['success']=false;
            $res['message']= "Përdoruesi ose fjalëkalimi është i zbrazët";
            return response($res, 422);
        }

        if ($request->user == "" || is_null($request->user) || $request->password == "" || is_null($request->password))
        {
            $res['success']=false;
            $res['message']= "Përdoruesi ose fjalëkalimi është i zbrazët";
            return response($res, 422);
        }
      
        $user = $request->user;
        $password = $request->password;
        $statusi=DB::select("SELECT statusi  FROM perdoruesit   WHERE
      perdoruesi = ? AND fjalekalimi = SHA2( ? ,256)", [$user, $password]);
         $selid = json_decode(json_encode($statusi), true);
         if(isset($selid[0]['statusi'])){
         if ($selid[0]['statusi']==0)
         {
             $res['success']=false;
             $res['message']= "Përdoruesi nuk është aktiv";
             return response($res, 422);
         }
        }
        
        try {
            $login = DB::select("SELECT m.perdoruesi  FROM perdoruesit m WHERE m.perdoruesi = ?", [$user]);
            if ($login) {
                if (count($login) > 0) {
                    $hash = DB::select("SELECT u1.*, u2.*,u1.id as idp  FROM perdoruesit u1,  permmissions u2         WHERE
                  u1.id=u2.perdoruesi_id and perdoruesi = ? AND fjalekalimi = SHA2( ? ,256)", [$user, $password]);
                    if (count($hash) > 0) {
                        try {
                            
                            $tmc = hash('sha256', $user . time());
                            $token = $this->jwt($user, $tmc);
                            $create_token = DB::update("UPDATE perdoruesit SET perdoruesit.api_token = ? WHERE perdoruesit.perdoruesi = ?", [$tmc, $user]);
                            $res['success'] = true;
                            $res['message'] = 'Successfull login';
                            $res['data'] = $hash[0];
                            $res['token'] = $token;
                            
                            return response($res, 200);
                        } catch (\Illuminate\Database\QueryException $ex) {
                            $res['success'] = false;
                            $res['message'] = "Error";
                            return response($res, 500);
                        }
                    } else {
                        $res['success'] = false;
                        $res['message'] = 'Përdoruesi ose fjalëkalimi nuk u gjet';
                        return response($res, 400);
                    }
                } else {
                    $res['success'] = false;
                    $res['message'] = 'Përdoruesi ose fjalëkalimi nuk u gjet!';
                    return response($res, 400);
                }
            } else {
                $res['success'] = false;
                $res['message'] = 'Përdoruesi nuk ekziston';
                return response($res, 400);
            }
        } catch (\Illuminate\Database\QueryException $ex) {
            $res['success'] = false;
            $res['message'] = "Error";
            return response($res, 500);
        }
    }
}