<?php
session_start();
require_once __DIR__.'/config/connexion.php';

$errors = [];
$userIdentifier = $userPass = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $userIdentifier = htmlspecialchars(trim($_POST['user_identifier']));
    $userPass = htmlspecialchars(trim($_POST['user_pass']));

    if (empty($userIdentifier)) {
        $errors['user_identifier'] = "L'email ou le numéro de téléphone est requis.";
    }

    if (empty($userPass)) {
        $errors['user_pass'] = "Le mot de passe est requis.";
    }

    if (empty($errors)) {
        try {
            // Rechercher l'utilisateur dans users_table
            $stmt = null;
            if (filter_var($userIdentifier, FILTER_VALIDATE_EMAIL)) {
                $stmt = $pdo->prepare('SELECT * FROM users_table WHERE user_email = ? LIMIT 1');
            } else {
                $stmt = $pdo->prepare('SELECT * FROM users_table WHERE phone_num = ? LIMIT 1');
            }
            
            $stmt->execute([$userIdentifier]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($userPass, $user['user_pass'])) {
                // Authentification réussie
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_email'] = $user['user_email'];
                $_SESSION['first_name'] = $user['first_name'];
                $_SESSION['last_name'] = $user['last_name'];
                $_SESSION['user_name'] = trim($user['first_name'] . ' ' . $user['last_name']);
                $_SESSION['phone_num'] = $user['phone_num'];
                $_SESSION['user_role'] = $user['user_role'] ?? 'Super admin';
                $_SESSION['status'] = $user['status'] ?? 1;
                $_SESSION['must_change_password'] = $user['must_change_password'] ?? 0;
                $_SESSION['compagnie_ref'] = '123456'; // Valeur par défaut
                
                // Créer le dossier journal si nécessaire
                $logDir = __DIR__ . '/data/' . $_SESSION['compagnie_ref'];
                $logFile = $logDir . '/journal.log';
                if (!is_dir($logDir)) {
                    @mkdir($logDir, 0755, true);
                }
                if (!file_exists($logFile)) {
                    $header = "# Journal des modifications - Créé le: " . date('Y-m-d H:i:s') . "\n\n";
                    @file_put_contents($logFile, $header);
                }

                // Redirection selon le rôle
                $roleRedirect = strtolower($_SESSION['user_role'] ?? '');
                if ($roleRedirect === 'agent' || $roleRedirect === 'user') {
                    header('Location: dashboard_agent.php');
                } else {
                    header('Location: dashboard.php');
                }
                exit;
            } else {
                $errors['login'] = "Identifiants ou mot de passe incorrects.";
            }
        } catch (Throwable $e) {
            $errors['login'] = 'Erreur de connexion : ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">

<?php include('includes/head_code.php');?>

<body class="bg-gradient-login">
  <div class="container-login">
    <div class="row justify-content-center">
      <div class="col-xl-6 col-lg-6 col-md-9">
        <div class="card shadow-sm my-5">
          <div class="card-body p-0">
            <div class="row">
              <div class="col-lg-12">
                <div class="login-form">
                  <div class="text-center">
                    <h1 class="h4 text-gray-900 mb-4">Connexion</h1>
                  </div>
                  <form method="POST" action="">
                    <div class="form-group">
                      <label>Email ou Numéro de téléphone</label>
                      <input type="text" class="form-control" name="user_identifier" value="<?= htmlspecialchars($userIdentifier) ?>" placeholder="Entrez votre email ou numéro de téléphone">
                      <?php if (isset($errors['user_identifier'])): ?>
                          <small class="text-danger"><?= $errors['user_identifier'] ?></small>
                      <?php endif; ?>
                    </div>
                    <div class="form-group">
                      <label>Mot de passe</label>
                      <input type="password" class="form-control" name="user_pass" placeholder="Mot de passe">
                      <?php if (isset($errors['user_pass'])): ?>
                          <small class="text-danger"><?= $errors['user_pass'] ?></small>
                      <?php endif; ?>
                    </div>
                    <?php if (isset($errors['login'])): ?>
                        <div class="text-danger text-center mb-3"><?= $errors['login'] ?></div>
                    <?php endif; ?>
                    <div class="form-group">
                      <button type="submit" class="btn btn-primary btn-block">Se connecter</button>
                    </div>
                  </form>
                  <hr>
                  <!-- Lien d'inscription supprimé: création réservée aux administrateurs via add_user.php -->
                  <div class="text-center">
                    <a class="font-weight-bold small" href="forgot-password.php">Mot de passe oublié ?</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>
</body>

</html>