<?php

/**

 * Fichier  : login.php

 * Auteur   : KREMER Régis

 * Version  : 2.3.0

 * Date     : 2026-03-03

 * Description : Page de connexion avec rate limiting et session sécurisée

 *

 * Changelog :

 *   v2.1.0 (2026-02-21) — Version initiale auditée et sécurisée

 *   v2.1.1 (2026-02-21) — Corrections sécurité (CSRF, MIME, session, migrateSuppliers)

 *   v2.2.0 (2026-02-21) — Permissions magasins, bons de commande, rapport d'écart,

 *   v2.3.0 (2026-03-03) — Refonte UI page de connexion (MageStock), fond vectoriel, bouton thème corrigé

 *                      import CSV, historique prix, bon de livraison multi-lignes

 */

require_once __DIR__.'/config.php';

startSession();



// If already logged → redirect

if(isLoggedIn()) { header('Location: dashboard'); exit; }



// Handle POST login

$error = '';

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

    $username = trim($_POST['username']??'');

    $password = $_POST['password']??'';

    // Rate limiting: max 5 tentatives par IP sur 5 minutes
    $rateLimitKey = 'login_'.md5($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    if (!checkRateLimit($rateLimitKey, 5, 300)) {
        $error = 'Trop de tentatives de connexion. Veuillez patienter 5 minutes.';
    } else {

    $users    = loadData('users');

    $found    = null;

    foreach($users as $u){

        if(($u['username']??'')===$username && ($u['active']??true)){

            $found = $u; break;

        }

    }

    if($found && password_verify($password, $found['password']??'')){

        // Prevent session fixation attacks

        session_regenerate_id(true);

        $_SESSION['user_id'] = $found['id'];

        $_SESSION['user_role']= $found['role'];

        header('Location: dashboard'); exit;

    } else {

        $error = 'Identifiants incorrects ou compte désactivé.';

    }
    } // end rate limiting

}

$settings = getSettings();

$company  = $settings['companyName'] ?? 'StockMaster';

?>

<!DOCTYPE html>

<html lang="fr" data-theme="dark">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover">

<meta name="theme-color" content="#0a0e14">

<title>Connexion — <?= htmlspecialchars($company) ?></title>

<link rel="preconnect" href="https://fonts.googleapis.com">

<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;0,9..40,700&display=swap" rel="stylesheet">

<link rel="stylesheet" href="assets/css/app.css">

<link rel="stylesheet" href="assets/css/enhancements.css">

<style>
/* ============================================================
   LOGIN UI (MageStock) — modern 2026, no layout regression
   ============================================================ */

:root{
  --login-max: 420px;
  --login-radius: 22px;
}

/* page */
body{
  margin:0;
  padding:0;
  min-height:100vh;
  min-height:100dvh;
  overflow:hidden;
  font-family:"DM Sans", system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
}

.login-screen{
  position:fixed;
  inset:0;
  display:flex;
  flex-direction:column;
  align-items:center;
  justify-content:center;
  padding: max(env(safe-area-inset-top), 18px) 18px max(env(safe-area-inset-bottom), 18px);
  background:
    radial-gradient(1200px 700px at 20% 10%, rgba(0, 180, 216, .14), transparent 60%),
    radial-gradient(900px 600px at 90% 30%, rgba(0, 212, 170, .10), transparent 55%),
    radial-gradient(800px 500px at 50% 95%, rgba(52, 120, 246, .12), transparent 60%),
    linear-gradient(180deg, var(--bg-deep), #070b12 65%, #060911 100%);
}

/* vector "warehouse / stock" pattern */
.login-screen::before{
  content:"";
  position:absolute;
  inset:-120px;
  pointer-events:none;
  opacity:.55;
  background-repeat:no-repeat;
  background-position:center;
  background-size:1200px 800px;
  filter: blur(.0px);
  /* Inline SVG (very light outlines), themable via currentColor-like stroke */
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='1200' height='800' viewBox='0 0 1200 800'%3E%3Cg fill='none' stroke='%23ffffff' stroke-opacity='0.06' stroke-width='2'%3E%3Cpath d='M140 520 L360 390 L580 520 L360 650 Z'/%3E%3Cpath d='M360 390 L360 650'/%3E%3Cpath d='M260 470 L260 610'/%3E%3Cpath d='M460 470 L460 610'/%3E%3Cpath d='M680 560 L900 430 L1120 560 L900 690 Z'/%3E%3Cpath d='M900 430 L900 690'/%3E%3Cpath d='M800 510 L800 650'/%3E%3Cpath d='M1000 510 L1000 650'/%3E%3Cpath d='M120 250 L260 170 L400 250 L260 330 Z'/%3E%3Cpath d='M260 170 L260 330'/%3E%3Cpath d='M720 240 L860 160 L1000 240 L860 320 Z'/%3E%3Cpath d='M860 160 L860 320'/%3E%3Cpath d='M520 210 h160'/%3E%3Cpath d='M540 190 v40'/%3E%3Cpath d='M660 190 v40'/%3E%3C/g%3E%3Cg fill='none' stroke='%23ffffff' stroke-opacity='0.05'%3E%3Cpath d='M80 720 H1120'/%3E%3Cpath d='M80 80 H1120'/%3E%3C/g%3E%3C/svg%3E");
}

/* glass container */
.login-box{
  position:relative;
  z-index:1;
  width:100%;
  max-width: var(--login-max);
  border-radius: var(--login-radius);
  padding: 34px 28px 26px;
  background: color-mix(in srgb, var(--bg-card) 82%, transparent);
  border: 1px solid color-mix(in srgb, var(--border) 88%, transparent);
  box-shadow:
    0 20px 70px rgba(0,0,0,.55),
    inset 0 1px 0 rgba(255,255,255,.04);
  backdrop-filter: blur(10px);
}

/* header / brand */
.login-logo{
  text-align:center;
  margin-bottom: 22px;
}

.login-brand{
  display:flex;
  flex-direction:column;
  align-items:center;
  gap:10px;
}

.login-brand img{
  width: 76px;
  height: 76px;
  object-fit: contain;
  border-radius: 18px;
  box-shadow: 0 10px 30px rgba(0,0,0,.35);
}

.login-logo-icon{
  width:76px;
  height:76px;
  border-radius:18px;
  background: linear-gradient(135deg, var(--blue), var(--green));
  display:flex;
  align-items:center;
  justify-content:center;
  box-shadow: 0 10px 30px rgba(0,0,0,.35);
}

.login-logo-icon svg{
  width:38px;
  height:38px;
  fill:none;
  stroke:#fff;
  stroke-width:2;
  stroke-linecap:round;
  stroke-linejoin:round;
}

.login-logo h1{
  margin: 0;
  font-size: 22px;
  font-weight: 850;
  color: var(--text-primary);
  letter-spacing: .2px;
}

.login-logo .tagline{
  margin-top: 4px;
  font-size: 12px;
  color: var(--text-muted);
  letter-spacing: .9px;
  text-transform: uppercase;
}

/* error */
.login-error{
  background: var(--red-pale);
  border: 1px solid rgba(255,71,87,0.30);
  color: var(--red);
  border-radius: 12px;
  padding: 12px 14px;
  margin: 14px 0 16px;
  font-size: 13px;
  display:flex;
  align-items:flex-start;
  gap:10px;
}
.login-error svg{
  width: 18px;
  height: 18px;
  margin-top: 1px;
  fill:none;
  stroke: currentColor;
  stroke-width: 2.2;
  flex-shrink:0;
}

/* fields */
.login-group{ margin-bottom: 14px; }
.login-label{
  font-size: 11px;
  font-weight: 800;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: .9px;
  margin-bottom: 6px;
  display:block;
}
.login-input{
  width: 100%;
  padding: 13px 14px;
  border-radius: 12px;
  border: 1px solid var(--border);
  background: var(--bg-input);
  color: var(--text-primary);
  font-size: 15px;
  outline: none;
  transition: border-color .18s, box-shadow .18s, transform .06s;
}
.login-input:focus{
  border-color: var(--blue);
  box-shadow: 0 0 0 4px var(--blue-pale);
}
.login-input::placeholder{ color: var(--text-muted); }

/* submit */
.login-btn{
  width: 100%;
  padding: 14px 14px;
  margin-top: 10px;
  border: none;
  border-radius: 12px;
  cursor:pointer;
  font-family:inherit;
  font-size: 15px;
  font-weight: 800;
  color: #fff;
  background: linear-gradient(135deg, var(--blue), var(--blue-dim));
  transition: transform .08s, opacity .18s, box-shadow .18s;
  display:flex;
  align-items:center;
  justify-content:center;
  gap:10px;
  box-shadow: 0 16px 30px rgba(52,120,246,.18);
}
.login-btn:hover{ opacity: .92; }
.login-btn:active{ transform: scale(.985); }
.login-btn svg{
  width: 18px;
  height: 18px;
  fill:none;
  stroke:#fff;
  stroke-width:2.5;
  stroke-linecap:round;
  stroke-linejoin:round;
}

/* theme toggle (fixed, correct sizing, safe area) */
.login-theme-toggle{
  position: fixed;
  top: max(env(safe-area-inset-top), 14px);
  right: max(env(safe-area-inset-right), 14px);
  z-index: 3;

  width: 44px;
  height: 44px;
  border-radius: 14px;
  border: 1px solid var(--border);
  background: color-mix(in srgb, var(--bg-card) 80%, transparent);
  backdrop-filter: blur(10px);

  display:flex;
  align-items:center;
  justify-content:center;

  cursor:pointer;
  color: var(--text-muted);
  transition: border-color .18s, color .18s, transform .08s;
}
.login-theme-toggle:hover{
  border-color: var(--border-light);
  color: var(--text-primary);
}
.login-theme-toggle:active{ transform: scale(.98); }
.login-theme-toggle svg{
  width: 20px;
  height: 20px;
  fill:none;
  stroke: currentColor;
  stroke-width: 2.2;
  stroke-linecap: round;
  stroke-linejoin: round;
}

/* footer micro */
.login-foot{
  margin-top: 14px;
  text-align:center;
  font-size: 12px;
  color: var(--text-muted);
  opacity: .9;
}
</style>

</head>

<body>



<button class="login-theme-toggle" id="btnThemeTog" title="Basculer thème">

    <svg id="themeIcon" viewBox="0 0 24 24" aria-hidden="true"></svg>

</button>



<div class="login-screen">

    <div class="login-box">

        <div class="login-logo">
            <div class="login-brand">
                <?php
                    $logoPath = __DIR__ . '/assets/img/sm.png';
                    $logoUrl  = 'assets/img/sm.png';
                ?>
                <?php if (is_file($logoPath)): ?>
                    <img src="<?= htmlspecialchars($logoUrl) ?>" alt="<?= htmlspecialchars($company) ?> — logo">
                <?php else: ?>
                    <div class="login-logo-icon" aria-hidden="true">
                        <svg viewBox="0 0 24 24">
                            <path d="M20 7l-.8 12a2 2 0 01-2 1.6H6.8a2 2 0 01-2-1.6L4 7"/>
                            <path d="M1 7h22"/>
                            <path d="M9 7V4a1 1 0 011-1h4a1 1 0 011 1v3"/>
                        </svg>
                    </div>
                <?php endif; ?>
            </div>
            <h1><?= htmlspecialchars($company) ?></h1>

            <div class="tagline">Gestion de stock • MageStock</div>

        </div>



        <?php if($error): ?>

        <div class="login-error">

            <svg viewBox="0 0 24 24"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>

            <?= htmlspecialchars($error) ?>

        </div>

        <?php endif; ?>



        <form method="POST" action="login.php" autocomplete="off">

            <div class="login-group">

                <label class="login-label">Nom d'utilisateur</label>

                <input type="text" name="username" class="login-input" placeholder="admin" required autocomplete="username">

            </div>

            <div class="login-group">

                <label class="login-label">Mot de passe</label>

                <input type="password" name="password" class="login-input" placeholder="••••••••" required autocomplete="current-password">

            </div>

            <button type="submit" class="login-btn">

                <svg viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>

                Se connecter

            </button>

        </form>

        <div class="login-foot">© <?= date('Y') ?> <?= htmlspecialchars($company) ?> — by KREMER Régis</div>

    </div>

</div>



<script>
// Theme toggle (login page)
(function(){
  var btn = document.getElementById('btnThemeTog');
  var icon = document.getElementById('themeIcon');

  function getCookie(name){
    var m = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return m ? decodeURIComponent(m[1]) : '';
  }
  function setCookie(name, value){
    document.cookie = name + '=' + encodeURIComponent(value) + ';path=/;max-age=31536000;SameSite=Lax';
  }

  function svgSun(){
    return '' +
      '<circle cx="12" cy="12" r="4"></circle>' +
      '<path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"></path>';
  }
  function svgMoon(){
    return '' +
      '<path d="M21 12.4A7.5 7.5 0 0 1 11.6 3a6.8 6.8 0 1 0 9.4 9.4Z"></path>';
  }

  function applyTheme(theme){
    document.documentElement.setAttribute('data-theme', theme);
    var meta = document.querySelector('meta[name="theme-color"]');
    if(meta){
      meta.setAttribute('content', theme === 'light' ? '#f7f9fc' : '#0a0e14');
    }
    if(icon){
      icon.innerHTML = (theme === 'light') ? svgMoon() : svgSun();
    }
    btn.setAttribute('aria-label', theme === 'light' ? 'Passer en thème sombre' : 'Passer en thème clair');
    btn.title = btn.getAttribute('aria-label');
  }

  var theme = getCookie('sm_theme') || 'dark';
  applyTheme(theme);

  btn.addEventListener('click', function(){
    theme = (theme === 'dark') ? 'light' : 'dark';
    setCookie('sm_theme', theme);
    applyTheme(theme);
  });
})();
</script>



<script src="assets/js/i18n.js?v=3"></script>

</body>

</html>

