<?php
$appName = 'mondialisa';
session_name($appName);
session_start();
require_once 'config.inc.php'; // connexion à la base $dbh

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $login = trim($_POST['login'] ?? '');
    $password = trim($_POST['password'] ?? '');

    if (empty($login) || empty($password)) {
        addMsg ('info',trad("Please fill in all the fields"));
        header("Location: index.php?p=login&error=required");
        exit;
    }

    try {
        // Vérifier si le login est un email ou un numéro de téléphone
        if (filter_var($login, FILTER_VALIDATE_EMAIL)) {
            $sql = "SELECT * FROM mondialisa_users WHERE email = :login AND pass = PASSWORD(:mdp) LIMIT 1";
        } else {
            $sql = "SELECT * FROM mondialisa_users WHERE tel = :login AND pass = PASSWORD(:mdp) LIMIT 1";
        }

        $stmt = $dbh->prepare($sql);
        $stmt->bindParam(':login', $login);
        $stmt->bindParam(':mdp', $password);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

     //   if ($user && password_verify($password, $user['pass'])) {
        if ($user &&  ($user['statut'] == 1)) {
            // Authentification réussie
            $_SESSION['user'] = $user;          
            $_SESSION['user']['connected'] = true;

            header("Location: index.php?p=dashboard");
            exit;
        } else {
               addMsg ('error',trad("Incorrect credentials"));
            header("Location: index.php?p=login&error=login_infos");
            exit;
        }

    } catch (PDOException $e) {
      catcherror($e,trad("Connection error"));
        header("Location: index.php?p=login&error=db");
        exit;
    }
} else {
    header("Location: index.php?p=login&error=request");
    exit;
}
?>
