<?php
require __DIR__.'/lib.php';
$err='';
if($_SERVER['REQUEST_METHOD']==='POST'){
  check_csrf(); $email=strtolower(trim($_POST['email']??'')); $pass=$_POST['pass']??'';
  $db=pdo();
  $s=$db->prepare("SELECT COUNT(*) FROM login_attempts WHERE ok=0 AND created_at>NOW()-INTERVAL 15 MINUTE AND (ip=? OR email=?)"); $s->execute([ip(),$email]);
  if($s->fetchColumn()>=5){ $err='Trop de tentatives. Réessayez dans 15 minutes.'; }
  else {
    $s=$db->prepare('SELECT * FROM users WHERE email=?'); $s->execute([$email]); $u=$s->fetch();
    $ok=$u && password_verify($pass,$u['pass_hash']);
    if(!$u) password_verify($pass,'$2y$10$abcdefghijklmnopqrstuuYb7q9m6y3m0g1Q1m2cY6Zl8y4mR1b2S'); // temps constant
    $db->prepare('INSERT INTO login_attempts(email,ip,ok) VALUES(?,?,?)')->execute([$email,ip(),(int)$ok]);
    if($ok){ if(password_needs_rehash($u['pass_hash'],PASSWORD_DEFAULT)) $db->prepare('UPDATE users SET pass_hash=? WHERE id=?')->execute([password_hash($pass,PASSWORD_DEFAULT),$u['id']]);
      login_user((int)$u['id']); header('Location: '.($u['role']==='admin'?'/admin/':'/client/')); exit; }
    $err='Identifiants incorrects.';
  }
}
ob_start(); ?>
<div class="c" style="max-width:380px;margin:40px auto"><h2>Connexion</h2><?php if($err):?><p class="err"><?=h($err)?></p><?php endif?>
<form method="post"><?=csrf_field()?><label>E-mail</label><input type="email" name="email" required autocomplete="username"><label>Mot de passe</label><input type="password" name="pass" required autocomplete="current-password"><br><br><button>Se connecter</button></form>
<p><a href="/shop.php">Pas encore client ? Commander des cartes</a></p></div>
<?php layout('Connexion',ob_get_clean());
