<?php
/* 
----------------------------------------------------------
  PAGE : AUTORIZER/AUTHENTIFICATOR PAGE  
  V1.0 / 2018
  AUTHOR : SGHAIER MAHMOUD  
----------------------------------------------------------
*/
require_once('ssinclude/app-init.php');
session_start(); // start PHP session! 
// logout signal 
if (isset($_GET['logout'])) 
 {
    if (isset($_COOKIE['custom_session_id'])) {
        $sessionId = $_COOKIE['custom_session_id'];
        destroySession($sessionId);
        setcookie('custom_session_id', '', time() - 3600, '/', '', true, true);
    }
    js_redirect(page_login);
    exit();
 }
// try to login   
try
{
    $stmt = $db->prepare("SELECT * FROM users WHERE email = ? and active=1");
    $stmt->execute([verif_posted('user_login')]);
    $user = $stmt->fetch();
    if ($user && password_verify(verif_posted('user_password'), $user['password']))
        {
        // authorized    
        // ✅ Génère un ID et stocke les données
        $sessionId = generateSessionId();
        $sessionData = [
            'USER_AUTHORIZED' => true,
            'USER_ID' => $user["user_id"],
            'USER_FIRSTNAME' => $user["first_name"],
            'USER_LASTNAME' => $user["last_name"],
            'USER_EMAIL' => $user["email"],
            'USER_ADMIN' => $user["admin_level"],
            'USER_AGENT' => $user["agent_level"],
            'USER_SUPERVISOR' => $user["supervisor_level"],
            'USER_PARAM' => $user["param_level"],
            'USER_POWER' => $user["power"],
            'last_activity' => time()
        ];
        storeSession($sessionId, $sessionData);
        // Crée le cookie de session
      // Si tu as défini ces constantes PHP (app_domain_hostname et app_path)
        $cookie_domain = parse_url(app_domain_hostname, PHP_URL_HOST); // extrait le host
        $cookie_path   = app_path; // ex: "/preprod/" ou "/" en prod
        // Crée le cookie de session
        setcookie(
            'custom_session_id',
            $sessionId,
            time() + session_lifetime,
            $cookie_path,   // path dynamique
            $cookie_domain, // domaine dynamique
            isset($_SERVER['HTTPS']), // secure si HTTPS
            true                      // httponly
        );
         try
         {
            $sql = "UPDATE users SET last_logged_in = NOW() where user_id = ".$user["user_id"].";" ;
            $affectedrows  = $db->exec($sql);
            if(isset($affectedrows))
            { header("location:".page_home."?status=logged") ;  }          
         }
         catch (PDOException $e) 
          {  
           // echo "There is some problem in connection: " . $e->getMessage(); // logging 
             header("location:".page_login."?err=failed") ; 
          }
        } else {
            header("location:".page_login."?err=failed") ;
        }
    }
catch (PDOException $e)
{
    //notify_error  ( $e->getMessage());
    header("location:".page_login."?err=failed") ;
}
// close connection 
require_once('ssinclude/app-close.php');
?>