<?php
require_once __DIR__."/../../../config/db.php";

$user_id = (int)$_POST['utilisateur_id'];
$caisses = $_POST['caisses'] ?? [];

$conn->beginTransaction();

$conn->prepare("DELETE FROM utilisateurs_caisses WHERE utilisateur_id = ?")
     ->execute([$user_id]);

$stmt = $conn->prepare("
  INSERT INTO utilisateurs_caisses (utilisateur_id, caisse_id)
  VALUES (?, ?)
");

foreach ($caisses as $cid) {
  $stmt->execute([$user_id, (int)$cid]);
}

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

if ($pos_pin !== '') {

    if (!preg_match('/^[0-9]{4,6}$/', $pos_pin)) {
        throw new Exception("PIN invalide");
    }

    $stmt = $conn->prepare("
        UPDATE utilisateurs
        SET pos_pin = ?,
            pos_pin_tentatives = 0,
            pos_pin_blocage = NULL
        WHERE id = ?
    ");

    $stmt->execute([
        password_hash($pos_pin, PASSWORD_BCRYPT),
        $user_id
    ]);
}

$conn->commit();


header("Location: ../../index.php?page=affectations");
