<?php
/* doc-project | pointages/enregistrer_livreur.php | Enregistre un livreur, génère un lien magique vers la nouvelle interface livreur multi-store et déclenche l’envoi d’un SMS d’accès. | Expose: aucun | Dépend de: config.php, pos_ip_authorizations, pos_livreurs, std_sms | Impacte: session PHP, accès JSON API, insertions en BDD, envoi SMS avec URL new/store/ml | Tables: pos_ip_authorizations(ip_address, authorized_until), pos_livreurs(phone_e164, magic_link, point_vente, created_at), std_sms(phoneNumber, message, status, timestamp) */
session_start();
date_default_timezone_set('Europe/Paris');

header('Content-Type: application/json; charset=utf-8');

// Connexion DB
require_once "config.php";
global $pdo;

// Sécurité: autorisation comme index.php (session ou IP autorisée)
$ip_address = $_SERVER['REMOTE_ADDR'];
$isAuthorized = false;

if (isset($_SESSION['authorized']) && $_SESSION['authorized'] === true) {
  $isAuthorized = true;
} else {
  try {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM pos_ip_authorizations WHERE ip_address = :ip_address AND authorized_until > NOW()");
    $stmt->execute([':ip_address' => $ip_address]);
    $count = $stmt->fetchColumn();
    if ($count > 0) {
      $_SESSION['authorized'] = true;
      $isAuthorized = true;
    }
  } catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => "Erreur DB (auth)."]);
    exit;
  }
}

if (!$isAuthorized) {
  http_response_code(403);
  echo json_encode(['ok' => false, 'error' => "Accès refusé."]);
  exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['ok' => false, 'error' => "Méthode non autorisée."]);
  exit;
}

function normalize_phone_e164_fr($raw) {
  $v = is_string($raw) ? trim($raw) : '';
  if ($v === '') return '';

  // Garder uniquement les chiffres
  $digits = preg_replace('/\D+/', '', $v);
  if ($digits === null) $digits = '';

  // 0033XXXXXXXXX => 33XXXXXXXXX
  if (strpos($digits, '0033') === 0) {
    $digits = '33' . substr($digits, 4);
  }

  // 0XXXXXXXXX (10 chiffres) => 33XXXXXXXXX
  if (strlen($digits) === 10 && $digits[0] === '0') {
    $digits = '33' . substr($digits, 1);
  }

  // Validation minimale FR: 33 + 9 chiffres
  if (!preg_match('/^33\d{9}$/', $digits)) {
    return '';
  }

  return $digits;
}

function point_vente_to_store_code($pointVente) {
  $normalized = is_string($pointVente) ? strtolower(trim($pointVente)) : '';
  if ($normalized === 'pelissanne') {
    return 'pel';
  }
  return 'lan';
}

$phoneRaw = isset($_POST['phone']) ? $_POST['phone'] : '';
$phone = normalize_phone_e164_fr($phoneRaw);
if ($phone === '') {
  http_response_code(400);
  echo json_encode(['ok' => false, 'error' => "Numéro invalide. Exemple: 0618529375 (=> 33618529375)."]);
  exit;
}

 $pointVenteRaw = isset($_POST['point_vente']) ? $_POST['point_vente'] : 'lancon';
 $pointVente = is_string($pointVenteRaw) ? strtolower(trim($pointVenteRaw)) : 'lancon';
 if ($pointVente !== 'lancon' && $pointVente !== 'pelissanne') {
   http_response_code(400);
   echo json_encode(['ok' => false, 'error' => "Point de vente invalide."]);
   exit;
 }
 
// Magic link (token)
try {
  $magic = bin2hex(random_bytes(16));
} catch (Exception $e) {
  // fallback ultra-simple
  $magic = bin2hex(openssl_random_pseudo_bytes(16));
}

$tz = new DateTimeZone('Europe/Paris');
$now = (new DateTime('now', $tz))->format('Y-m-d H:i:s');
$todayStart = (new DateTime('today', $tz))->format('Y-m-d 00:00:00');

try {
  $pdo->beginTransaction();

  // Supprimer toutes les entrées des jours précédents (on garde uniquement "aujourd'hui")
  $del = $pdo->prepare("DELETE FROM pos_livreurs WHERE created_at < :todayStart");
  $del->execute([':todayStart' => $todayStart]);

  // Insérer la nouvelle entrée
  $ins = $pdo->prepare("
    INSERT INTO pos_livreurs (phone_e164, magic_link, point_vente, created_at)
    VALUES (:phone, :magic, :point_vente, :created_at)
  ");
  $ins->execute([
    ':phone' => $phone,
    ':magic' => $magic,
    ':point_vente' => $pointVente,
    ':created_at' => $now
  ]);

  $storeCode = point_vente_to_store_code($pointVente);
  $url = "https://livreur.aquoipizza.fr?store=" . rawurlencode($storeCode) . "&ml=" . rawurlencode($magic);
  $smsMessage = "Voilà le lien pour accéder à l'interface de livraison\n" . $url;

  // Insérer le SMS dans std_sms (colonnes minimales demandées)
  $sms = $pdo->prepare("
    INSERT INTO std_sms (phoneNumber, message, status, timestamp)
    VALUES (:phoneNumber, :message, :status, :timestamp)
  ");
  $sms->execute([
    ':phoneNumber' => $phone,
    ':message' => $smsMessage,
    ':status' => 'waiting',
    ':timestamp' => $now
  ]);

  $pdo->commit();

  echo json_encode([
    'ok' => true,
    'phone' => $phone,
    'point_vente' => $pointVente,
    'store' => $storeCode,
    'magic_link' => $magic,
    'sms_status' => 'waiting',
    'url' => $url
  ]);
  exit;
} catch (PDOException $e) {
  if ($pdo && $pdo->inTransaction()) {
    try { $pdo->rollBack(); } catch (Exception $ex) {}
  }
  http_response_code(500);
  echo json_encode(['ok' => false, 'error' => "Erreur DB lors de l'enregistrement."]);
  exit;
}

?>
