<?php
// Assistant d'installation pour le module gestion_compagnies
// Objectif: créer la base centrale assurance_gestion (si vide) + tables depuis fichier externe
// et générer gestion_compagnies/config/connexion.php

@session_start();
@date_default_timezone_set('Africa/Casablanca');
$step = (int)($_POST['step'] ?? 1);
$messages=[]; $errors=[];
$configPath = __DIR__.'/../config/connexion.php';
// Fichier SQL externe contenant le schéma (utilisé uniquement pour recréer les tables)
$sqlExternal = 'C:/Users/YOUSSEF/Desktop/temp/assurance_gestion.sql';

if($step===1){
  if(file_exists($configPath)){
    $errors[] = "Le fichier connexion.php existe déjà. Supprimez-le pour installer à nouveau.";
  }
}

if($step===2){
  // Vérifs avant exécution
  $db_host = trim($_POST['db_host'] ?? 'localhost');
  $db_name = trim($_POST['db_name'] ?? 'assurance_gestion');
  $db_user = trim($_POST['db_user'] ?? '');
  $db_pass = $_POST['db_pass'] ?? '';
  $admin_first = trim($_POST['admin_first'] ?? 'Super');
  $admin_last = trim($_POST['admin_last'] ?? 'Admin');
  $admin_phone = trim($_POST['admin_phone'] ?? '');
  $admin_email = trim($_POST['admin_email'] ?? '');
  $admin_pass = $_POST['admin_pass'] ?? '';
  $admin_pass2 = $_POST['admin_pass2'] ?? '';
  $create_db = isset($_POST['create_db']);

  if($db_host==='') $errors[]='Host requis';
  if($db_name==='') $errors[]='Nom BD requis';
  if($db_user==='') $errors[]='Utilisateur BD requis';
  if(!filter_var($admin_email,FILTER_VALIDATE_EMAIL)) $errors[]='Email admin invalide';
  if(strlen($admin_pass)<6) $errors[]='Mot de passe admin min 6 caractères';
  if($admin_pass!==$admin_pass2) $errors[]='Confirmation mot de passe différente';
  if(file_exists($configPath)) $errors[]='connexion.php existe déjà';
  // Ne plus dépendre d'un fichier externe

  if(!$errors){
    try {
      $pdo = new PDO("mysql:host=$db_host;charset=utf8", $db_user, $db_pass, [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);
      if($create_db){ $pdo->exec("CREATE DATABASE IF NOT EXISTS `$db_name` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci"); }
      $pdo->exec("USE `$db_name`");
    // Lecture du fichier externe pour récupérer uniquement les CREATE TABLE
    $createStatements = [];
    if($sqlExternal && is_file($sqlExternal) && is_readable($sqlExternal)){
      $raw = file_get_contents($sqlExternal);
      if($raw!==false){
        // Normaliser sauts de ligne
        $rawNorm = str_replace(["\r\n","\r"],"\n",$raw);
        // Extraire les blocs CREATE TABLE ... ; (non greedy)
        if(preg_match_all('/CREATE\s+TABLE\s+[^;]+;/i',$rawNorm,$m)){
          foreach($m[0] as $stmt){
            // Nettoyer délimiteurs éventuels
            $stmtTrim = trim($stmt);
            // S'assurer que IF NOT EXISTS est présent (optionnel)
            if(stripos($stmtTrim,'IF NOT EXISTS')===false){
              $stmtTrim = preg_replace('/CREATE\s+TABLE/i','CREATE TABLE IF NOT EXISTS',$stmtTrim,1);
            }
            $createStatements[] = $stmtTrim;
          }
        }
      } else { $messages[]='Lecture schéma externe échouée (fallback interne).'; }
    } else {
      $messages[]='Fichier schéma externe indisponible (fallback interne).';
    }
    // Fallback si aucun create trouvé
    if(!$createStatements){
      $createStatements = [
      "CREATE TABLE IF NOT EXISTS `users_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `first_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
  `phone_num` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,
  `user_email` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
  `user_pass` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `user_role` enum('admin','user') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'user',
  `status` enum('active','disabled') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'active',
  `recup_pass` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `recup_expiry` datetime DEFAULT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `phone_num` (`phone_num`),
  UNIQUE KEY `user_email` (`user_email`),
  KEY `idx_email` (`user_email`),
  KEY `idx_phone` (`phone_num`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;",
      "CREATE TABLE IF NOT EXISTS `users_compagnie` (
  `id` int NOT NULL AUTO_INCREMENT,
  `compagnie_ref` varchar(50) NOT NULL,
  `first_name` varchar(60) NOT NULL,
  `last_name` varchar(60) NOT NULL,
  `phone_num` varchar(20) NOT NULL,
  `user_email` varchar(190) NOT NULL,
  `user_pass` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_phone_email` (`phone_num`,`user_email`),
  KEY `idx_compagnie_ref` (`compagnie_ref`),
  KEY `idx_user_email` (`user_email`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;",
      "CREATE TABLE IF NOT EXISTS `compagnies_table` (
  `id` int NOT NULL AUTO_INCREMENT,
  `compagnie_name` varchar(100) NOT NULL,
  `compagnie_ref` varchar(100) NOT NULL,
  `compagnie_db` varchar(100) NOT NULL,
  `compagnie_db_user` varchar(100) NOT NULL,
  `compagnie_db_pass` varchar(100) NOT NULL,
  `active` int NOT NULL,
  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  `adresse` varchar(250) DEFAULT NULL,
  `tel1` varchar(20) DEFAULT NULL,
  `tel2` varchar(20) DEFAULT NULL,
  `fax` varchar(20) DEFAULT NULL,
  `whatsapp` varchar(20) DEFAULT NULL,
  `mail_1` varchar(100) DEFAULT NULL,
  `mail_2` varchar(100) DEFAULT NULL,
  `mail_3` varchar(100) DEFAULT NULL,
  `footer` text,
  `validation` int NOT NULL,
  `logo_format` enum('wide','square') NOT NULL DEFAULT 'wide',
  `logo` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `compagnie_ref` (`compagnie_ref`),
  UNIQUE KEY `uq_compagnie_ref` (`compagnie_ref`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
"
      ];
    }
    foreach($createStatements as $sqlStmt){
      try { $pdo->exec($sqlStmt); }
      catch(Throwable $ie){ $errors[]='Schema: '.substr($ie->getMessage(),0,120); }
    }
      // Remplacer/forcer les trois schémas principaux avec les définitions exactes fournies
      $exactSchemas = [
        'compagnies_table' => "CREATE TABLE IF NOT EXISTS `compagnies_table` (\n  `id` int NOT NULL AUTO_INCREMENT,\n  `compagnie_name` varchar(100) NOT NULL,\n  `compagnie_ref` varchar(100) NOT NULL,\n  `compagnie_db` varchar(100) NOT NULL,\n  `compagnie_db_user` varchar(100) NOT NULL,\n  `compagnie_db_pass` varchar(100) NOT NULL,\n  `active` int NOT NULL,\n  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,\n  `adresse` varchar(250) DEFAULT NULL,\n  `tel1` varchar(20) DEFAULT NULL,\n  `tel2` varchar(20) DEFAULT NULL,\n  `fax` varchar(20) DEFAULT NULL,\n  `whatsapp` varchar(20) DEFAULT NULL,\n  `mail_1` varchar(100) DEFAULT NULL,\n  `mail_2` varchar(100) DEFAULT NULL,\n  `mail_3` varchar(100) DEFAULT NULL,\n  `footer` text,\n  `validation` int NOT NULL,\n  `logo_format` enum('wide','square') NOT NULL DEFAULT 'wide',\n  `logo` varchar(255) DEFAULT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `compagnie_ref` (`compagnie_ref`),\n  UNIQUE KEY `uq_compagnie_ref` (`compagnie_ref`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci",
        'users_compagnie' => "CREATE TABLE IF NOT EXISTS `users_compagnie` (\n  `id` int NOT NULL AUTO_INCREMENT,\n  `compagnie_ref` varchar(50) NOT NULL,\n  `first_name` varchar(60) NOT NULL,\n  `last_name` varchar(60) NOT NULL,\n  `phone_num` varchar(20) NOT NULL,\n  `user_email` varchar(190) NOT NULL,\n  `user_pass` varchar(255) NOT NULL,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `uq_phone_email` (`phone_num`,`user_email`),\n  KEY `idx_compagnie_ref` (`compagnie_ref`),\n  KEY `idx_user_email` (`user_email`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci",
  'users_table' => "CREATE TABLE IF NOT EXISTS `users_table` (\n  `id` int NOT NULL AUTO_INCREMENT,\n  `first_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,\n  `last_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,\n  `phone_num` varchar(30) COLLATE utf8mb4_unicode_ci NOT NULL,\n  `user_email` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,\n  `user_pass` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,\n  `user_role` enum('admin','user') COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'user',\n  `status` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'active',\n  `recup_pass` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,\n  `recup_expiry` datetime DEFAULT NULL,\n  `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\n  `updated_at` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,\n  PRIMARY KEY (`id`),\n  UNIQUE KEY `phone_num` (`phone_num`),\n  UNIQUE KEY `user_email` (`user_email`),\n  KEY `idx_email` (`user_email`),\n  KEY `idx_phone` (`phone_num`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci"
      ];
      foreach($exactSchemas as $tbl=>$ddl){
          try { $pdo->exec($ddl); } catch(Throwable $ie){ $errors[]="Schema exact ($tbl): ".substr($ie->getMessage(),0,120); }
      }
      // Vérifier users_table finale
      try { $pdo->query("SELECT 1 FROM users_table LIMIT 1"); } catch(Throwable $ie){ $errors[]='users_table inaccessible après création.'; }
    // S'assurer que la table users_table existe (sinon la créer)
    try { $pdo->query('SELECT 1 FROM users_table LIMIT 1'); }
    catch(Throwable $e){
      try { $pdo->exec("CREATE TABLE IF NOT EXISTS users_table ( id INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(60) NOT NULL, last_name VARCHAR(60) NOT NULL, phone_num VARCHAR(20) NOT NULL, user_email VARCHAR(190) NOT NULL, user_pass VARCHAR(255) NOT NULL, recup_pass VARCHAR(250) DEFAULT NULL, recup_expiry DATETIME DEFAULT NULL, user_role VARCHAR(30) NOT NULL DEFAULT 'admin', status VARCHAR(10) NOT NULL DEFAULT 'active', created_at DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY uq_phone_email (phone_num,user_email) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"); } catch(Throwable $e2){ $errors[]='Create users_table fallback: '.substr($e2->getMessage(),0,120); }
    }
      // Insérer Super Admin dans users_table
      $st = $pdo->prepare('SELECT COUNT(*) FROM users_table WHERE user_email=?');
      $st->execute([$admin_email]);
      if(!$st->fetchColumn()){
          $hash = password_hash($admin_pass,PASSWORD_BCRYPT);
          // Assurer unicité phone_num (si vide => générer placeholder unique)
          $phoneFinal = $admin_phone!=='' ? $admin_phone : ('NA'.substr(sha1(uniqid('',true)),0,8));
          try {
            $pdo->prepare('INSERT INTO users_table(first_name,last_name,phone_num,user_email,user_pass,user_role,status,created_at) VALUES(?,?,?,?,?,"admin","active",NOW())')->execute([$admin_first,$admin_last,$phoneFinal,$admin_email,$hash]);
            $messages[]='Utilisateur admin créé (users_table).';
          } catch(Throwable $ie){ $errors[]='Insertion admin: '.substr($ie->getMessage(),0,120); }
      } else { $messages[]='Utilisateur déjà existant dans users_table (aucune création).'; }
      // Générer fichier de connexion
        $tpl = <<<'PHP'
  <?php
  // Connexion dédiée module gestion_compagnies (auto-généré)
  $GC_DB_HOST='__HOST__';
  $GC_DB_NAME='__NAME__';
  $GC_DB_USER='__USER__';
  $GC_DB_PASS='__PASS__';
  try {
    $gc_pdo = new PDO("mysql:host=$GC_DB_HOST;dbname=$GC_DB_NAME;charset=utf8", $GC_DB_USER, $GC_DB_PASS,[
      PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
      PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'
    ]);
  } catch(Throwable $e){ die('GC DB Connexion échouée: '.$e->getMessage()); }
  PHP;
        $cfg = strtr($tpl,[
          '__HOST__'=>$db_host,
          '__NAME__'=>$db_name,
          '__USER__'=>$db_user,
          '__PASS__'=>$db_pass,
        ]);
      if(false===file_put_contents($configPath,$cfg)) throw new Exception('Écriture connexion.php impossible');
      $messages[]='Fichier connexion.php créé.';
      if(!$errors){ $step=3; }
    } catch(Throwable $e){ $errors[]='Installation: '.$e->getMessage(); }
  }
}
?>
<!DOCTYPE html><html lang="fr"><head><meta charset="utf-8"><title>Installation gestion_compagnies</title><link rel="stylesheet" href="../../vendor/bootstrap/css/bootstrap.min.css"><link rel="stylesheet" href="../../vendor/fontawesome-free/css/all.min.css"><style>body{background:#f4f6f9}.card{box-shadow:0 2px 4px rgba(0,0,0,.05)}</style></head><body>
<div class="container py-4">
  <div class="row justify-content-center">
    <div class="col-lg-8">
      <div class="card mb-4">
        <div class="card-header bg-primary text-white"><strong><i class="fas fa-tools"></i> Installation Module Gestion Compagnies</strong></div>
        <div class="card-body">
          <?php foreach($messages as $m): ?><div class="alert alert-success py-2"><?=htmlspecialchars($m)?></div><?php endforeach; ?>
          <?php foreach($errors as $er): ?><div class="alert alert-danger py-2"><?=htmlspecialchars($er)?></div><?php endforeach; ?>
          <?php if($step===1): ?>
            <p class="text-muted">Cet assistant créera la base centrale et l'utilisateur Super Admin.</p>
            <form method="post">
              <input type="hidden" name="step" value="2">
              <div class="form-row">
                <div class="form-group col-md-6"><label>Host DB</label><input name="db_host" class="form-control" value="localhost" required></div>
                <div class="form-group col-md-6"><label>Nom Base</label><input name="db_name" class="form-control" value="assurance_gestion" required></div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-6"><label>User DB</label><input name="db_user" class="form-control" required></div>
                <div class="form-group col-md-6"><label>Mot de passe DB</label><input name="db_pass" type="password" class="form-control"></div>
              </div>
              <div class="form-group form-check"><input type="checkbox" class="form-check-input" id="createdb" name="create_db" checked><label class="form-check-label" for="createdb">Créer la base si inexistante</label></div>
              <hr>
              <h6>Super Admin</h6>
              <div class="form-row">
                <div class="form-group col-md-6"><label>Prénom</label><input name="admin_first" class="form-control" value="Super" required></div>
                <div class="form-group col-md-6"><label>Nom</label><input name="admin_last" class="form-control" value="Admin" required></div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-6"><label>Téléphone</label><input name="admin_phone" class="form-control"></div>
                <div class="form-group col-md-6"><label>Email</label><input name="admin_email" type="email" class="form-control" required></div>
              </div>
              <div class="form-row">
                <div class="form-group col-md-6"><label>Mot de passe</label><input name="admin_pass" type="password" class="form-control" required></div>
                <div class="form-group col-md-6"><label>Confirmer</label><input name="admin_pass2" type="password" class="form-control" required></div>
              </div>
              <button class="btn btn-primary"><i class="fas fa-play"></i> Lancer l'installation</button>
            </form>
          <?php elseif($step===2): ?>
            <p class="text-muted">Traitement en cours... (corrigez les erreurs si présentes)</p>
            <form method="post">
              <input type="hidden" name="step" value="1">
              <button class="btn btn-secondary btn-sm">&larr; Revenir</button>
            </form>
          <?php elseif($step===3): ?>
            <div class="alert alert-success"><strong>Installation terminée.</strong> Vous pouvez maintenant supprimer le dossier install/ ou le protéger.</div>
            <a href="../login.php" class="btn btn-success">Aller au login</a>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <p class="small text-center text-muted mb-0">&copy; <?=date('Y')?> Module gestion_compagnies</p>
</div>
</body></html>
