<?php
require_once "../magic/session_config.php";
bdr_start_session();
ob_start();
      $timezone = "Asia/Riyadh";
      date_default_timezone_set($timezone);
    unset($_SESSION["user_id"]);
    unset($_SESSION["realName"]);
    unset($_SESSION["branch"]);

require_once "../magic/auth.php";
require_once "../magic/DataBase.php";
require_once "../auth/token.php";
$database = new DataBase();

$conn = $database->getConnection();

$user_name =  $_POST['user_name'] ?? '';
$pass      =  $_POST['pass'] ?? '';
$token     =  $_POST['tokenn'] ?? '';

if(empty($user_name) ||empty($pass)){
  echo "
        <div class='alert alert-warning'>
        <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;' >&times;</a>
        <b>من فضلك  سجل بياناتك كاملة  ...!</b></div>";
  exit();
}else{
if(!empty($user_name)){  $user_name = htmlspecialchars(strip_tags($user_name)) ;}
if(!empty($pass)){  $pass = htmlspecialchars(strip_tags($pass)) ;}

// existing user_name or pass number in your database
$sql =$conn->prepare("SELECT pass , user_id , realName , branch , phone1 , role FROM users WHERE user_name =? AND active = 1 LIMIT 1");
$sql->bindParam(1,$user_name);
$sql->execute();
if($sql->rowCount()>0){{$row = $sql->fetch(PDO::FETCH_ASSOC);
      $user_id   = $row["user_id"];
      $realName  = $row["realName"];
      $branch    = $row["branch"];
      $phone     = $row["phone1"];
      $connpass    = $row["pass"];
      $role      = $row["role"];
    }
  if(password_verify($pass, $connpass)){
      if(empty($token)){
        echo "
        <div class='alert alert-danger'>
        <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
        <b>This device cannot login because it has no registered security token.</b></div>";
        exit();
      }

      $mkToken = new TokenMaster($conn,$token);
      if(!$mkToken->checkPC()){
        if(!$mkToken->saveToken($user_id,$branch,$token)){
          $deviceError = htmlspecialchars($mkToken->getLastError(), ENT_QUOTES, 'UTF-8');
          echo "
          <div class='alert alert-danger'>
          <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
          <b>Device record was not saved. Check loginhistory table columns and database permissions.</b><br>
          <small>$deviceError</small></div>";
          exit();
        }
        echo "
        <div class='alert alert-warning'>
        <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
        <b>This device is not active yet. Ask the system manager to activate it from device permissions.</b></div>";
        exit();
      }

      if(!$mkToken->isStaffDevice()){
        echo "
        <div class='alert alert-danger'>
        <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
        <b>This device is inactive and cannot login.</b></div>";
        exit();
      }

      if(!$mkToken->checkBranch($branch)){
        $mkToken->updateBranch($branch);
      }
      if(!$mkToken->checkUser($user_id)){
        $mkToken->updateUser($user_id);
      }
      $mkToken->updateLastLogin();

      $_SESSION['user_id']  = $user_id;
      $_SESSION['realName'] = $realName;
      $_SESSION['branch']   = $branch;
      $_SESSION['role']     = $role;
      $_SESSION['exp']      = time()+ 1900 ;
      setcookie(session_name(), session_id(), 0, '/', '', (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'), true);

      require_once "../op/car_history.php";
      mk_history();
      $master = bdr_user_has_privilege($conn, $user_id, [20, 30, 36]) ? 1 : 0;
          // echo $_SESSION['realName'];
        session_write_close();
        echo $master;
        exit();
    }else {
      echo "
      <div class='alert alert-danger'>
      <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
      <b>يوجد خطأ في كلمة السر او اسم المستخدم حاول ثانية ....!</b></div>";
        exit();
          }
  }else {
    echo "
    <div class='alert alert-danger'>
    <a href='#' class='close' data-dismiss='alert' aria-label='close'style='float:left;'>&times;</a>
    <b>أخي الكريم لا تحاول الدخول في ما لا يعنيك الله يخليك .....</b></div>";
      exit();
        }
}
?>
