<?php
session_start();
// Include database connection
include 'config/connexion.php';
// Guard: require authenticated session and available company DB connection
if (empty($_SESSION['user_email']) && empty($_SESSION['user_name'])) { header('Location: login.php'); exit; }
if (empty($COMPANY_DB_AVAILABLE) || !($conn instanceof mysqli)) { header('Location: login.php'); exit; }
// Include log module
require_once 'includes/simple_log.php';
// Initialize variables for form submission
$errors = [
    'client_cin' => '',
    'client_name' => '',
    'client_phone' => '',
    'client_email' => '',
    'client_company' => '',
    'client_genre' => '',
    'client_adresse' => '',
    'n_dossier' => '',
    'client_ice' => ''
];
$success = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $client_cin = strtoupper(trim($_POST['client_cin']));
    $client_name = strtoupper(trim($_POST['client_name']));
    $client_phone = trim($_POST['client_phone']);
    $client_email = trim($_POST['client_email']);
    $client_company = strtoupper(trim($_POST['client_company']));
    $client_genre = trim($_POST['client_genre']);
    $client_adresse = trim($_POST['client_adresse']);
    $n_dossier = trim($_POST['n_dossier']); // Nouveau champ
    $client_ice = trim($_POST['client_ice']); // Champ ICE non obligatoire

    // Validate CIN
    if (empty($client_cin)) {
        $errors['client_cin'] = "Le CIN du client est obligatoire.";
    }

    // Validate Name
    if (empty($client_name)) {
        $errors['client_name'] = "Le nom du client est obligatoire.";
    } elseif (!preg_match("/^[a-zA-Z\s\-]+$/", $client_name)) {
        $errors['client_name'] = "Le nom du client ne doit contenir que des lettres, des espaces et des tirets.";
    }

    // Validate Phone
    if (empty($client_phone)) {
        $errors['client_phone'] = "Le numéro de téléphone du client est obligatoire.";
    } elseif (!preg_match("/^\d+$/", $client_phone)) {
        $errors['client_phone'] = "Le numéro de téléphone ne doit contenir que des chiffres.";
    }

    // Validate Email
    if (!empty($client_email) && !filter_var($client_email, FILTER_VALIDATE_EMAIL)) {
        $errors['client_email'] = "L'email n'est pas valide.";
    }

    // Validate Genre
    if (empty($client_genre)) {
        $errors['client_genre'] = "Le genre du client est obligatoire.";
    }

    // Validate Address
    if (empty($client_adresse)) {
        $errors['client_adresse'] = "L'adresse du client est obligatoire.";
    }

    // Validate Folder Number
    if (empty($n_dossier)) {
        $errors['n_dossier'] = "Le numéro de dossier est obligatoire.";
    } elseif (!preg_match("/^\d+$/", $n_dossier)) {
        $errors['n_dossier'] = "Le numéro de dossier doit contenir uniquement des chiffres.";
    }

    // Check for unique constraints if no validation errors
    if (!array_filter($errors)) {
        // Check for duplicate CIN
        $query = "SELECT id FROM clients_table WHERE client_cin = ?";
        $stmt = $conn->prepare($query);
        $stmt->bind_param("s", $client_cin);
        $stmt->execute();
        $stmt->bind_result($existing_id);
        if ($stmt->fetch()) {
            $errors['client_cin'] = "Le CIN existe déjà.";
        }
        $stmt->close();

        // Check for duplicate phone if no CIN error
        if (empty($errors['client_cin'])) {
            $query = "SELECT id FROM clients_table WHERE client_phone = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $client_phone);
            $stmt->execute();
            $stmt->bind_result($existing_id);
            if ($stmt->fetch()) {
                $errors['client_phone'] = "Le numéro de téléphone existe déjà.";
            }
            $stmt->close();
        }

        // Check for duplicate email if no CIN or phone error
        if (empty($errors['client_cin']) && empty($errors['client_phone']) && !empty($client_email)) {
            $query = "SELECT id FROM clients_table WHERE client_email = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $client_email);
            $stmt->execute();
            $stmt->bind_result($existing_id);
            if ($stmt->fetch()) {
                $errors['client_email'] = "L'email existe déjà.";
            }
            $stmt->close();
        }

        // Si Entreprise est vide, utiliser le nom du client
        if (empty($client_company)) {
            $client_company = $client_name;
        }

        // Vérification de l'unicité du numéro de dossier
        $sql_check = "SELECT COUNT(*) FROM clients_table WHERE n_dossier = ?";
        $stmt_check = $conn->prepare($sql_check);
        $stmt_check->bind_param("s", $n_dossier);
        $stmt_check->execute();
        $stmt_check->bind_result($count);
        $stmt_check->fetch();
        $stmt_check->close();

        if ($count > 0) {
            $errors['n_dossier'] = "Le numéro de dossier doit être unique.";
        } else {
            // Insert the client if no errors
            if (!array_filter($errors)) {
                $insertQuery = "INSERT INTO clients_table (client_cin, client_name, client_phone, client_email, client_company, client_genre, client_adresse, n_dossier, client_ice) 
                                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $insertStmt = $conn->prepare($insertQuery);
                $insertStmt->bind_param("sssssssss", $client_cin, $client_name, $client_phone, $client_email, $client_company, $client_genre, $client_adresse, $n_dossier, $client_ice);

                if ($insertStmt->execute()) {
                    // Enregistrer la création dans le log
                    logClientCreation($client_name, $client_cin, $n_dossier);
                    
                    $success = "Client ajouté avec succès.";
                    
                    // Clear form fields after success
                    $client_cin = $client_name = $client_phone = $client_email = $client_company = $client_genre = $client_adresse = $n_dossier = $client_ice = '';
                } else {
                    $errors['client_cin'] = "Erreur lors de l'ajout du client.";
                }

                $insertStmt->close();
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
 <?php include ('includes/head.php'); ?>
</head>

<body id="page-top">
  <div id="wrapper">
    <!-- Sidebar -->
   <?php include ('includes/sidebar.php'); ?>
    <!-- Sidebar -->
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <!-- TopBar -->
       <?php include ('includes/topbar.php'); ?>
        <!-- Topbar -->

        <!-- Container Fluid-->
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h3 mb-0 text-gray-800">Form Basics</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Home</a></li>
              <li class="breadcrumb-item">Forms</li>
              <li class="breadcrumb-item active" aria-current="page">Form Basics</li>
            </ol>
          </div>

          <div class="row">
            <div class="col-lg-6">
              <!-- Form Basic -->
              <div class="card mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                  <h6 class="m-0 font-weight-bold text-primary">Form Basic</h6>
                </div>
                <div class="card-body">
                <?php if ($success): ?>
        <div class="alert alert-success">
            <?php echo $success; ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="add_client.php">
        <div class="form-group">
            <label for="client_cin">CIN du client</label>
            <input type="text" class="form-control" id="client_cin" name="client_cin" required 
                   value="<?php if(!empty($client_cin)){echo htmlspecialchars($client_cin);} ?>">
            <?php if ($errors['client_cin']): ?>
                <small class="text-danger"><?php echo $errors['client_cin']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_name">Nom du client</label>
            <input type="text" class="form-control" id="client_name" name="client_name" required 
                   value="<?php if(!empty($client_name)){echo htmlspecialchars($client_name);} ?>">
            <?php if ($errors['client_name']): ?>
                <small class="text-danger"><?php echo $errors['client_name']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_phone">Numéro de téléphone</label>
            <input type="text" class="form-control" id="client_phone" name="client_phone" required 
                   value="<?php if(!empty($client_phone)){echo htmlspecialchars($client_phone);} ?>">
            <?php if ($errors['client_phone']): ?>
                <small class="text-danger"><?php echo $errors['client_phone']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_email">Email</label>
            <input type="email" class="form-control" id="client_email" name="client_email" 
                   value="<?php if(!empty($client_email)){echo htmlspecialchars($client_email);} ?>">
            <?php if ($errors['client_email']): ?>
                <small class="text-danger"><?php echo $errors['client_email']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_company">Entreprise</label>
            <input type="text" class="form-control" id="client_company" name="client_company" 
                   value="<?php if(!empty($client_company)){echo htmlspecialchars($client_company);} ?>">
        </div>
        <div class="form-group">
            <label for="client_genre">Genre</label>
            <select class="form-control" id="client_genre" name="client_genre" required>
                <option value="" disabled selected>Choisir le genre</option>
                <option value="Mâle" <?php if(!empty($client_genre)){if ($client_genre === 'Mâle') echo 'selected';} ?>>Mâle</option>
                <option value="Femelle" <?php if(!empty($client_genre)){if ($client_genre === 'Femelle') echo 'selected';} ?>>Femelle</option>
                <option value="Personne Morale" <?php if(!empty($client_genre)){if ($client_genre === 'Personne Morale') echo 'selected';} ?>>Personne Morale</option> <!-- Nouvelle option -->
            </select>
            <?php if ($errors['client_genre']): ?>
                <small class="text-danger"><?php echo $errors['client_genre']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_adresse">Adresse</label>
            <input type="text" class="form-control" id="client_adresse" name="client_adresse" required 
                   value="<?php if(!empty($client_adresse)){echo htmlspecialchars($client_adresse);} ?>">
            <?php if (!empty($errors['client_adresse'])): ?>
                <small class="text-danger"><?php echo $errors['client_adresse']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="n_dossier">Numéro de dossier (chiffres seulement)</label>
            <input type="text" name="n_dossier" id="n_dossier" class="form-control" required pattern="\d+" inputmode="numeric"
                   value="<?php if(!empty($n_dossier)){echo htmlspecialchars($n_dossier);} ?>">
            <?php if (!empty($errors['n_dossier'])): ?>
                <small class="text-danger"><?php echo $errors['n_dossier']; ?></small>
            <?php endif; ?>
        </div>
        <div class="form-group">
            <label for="client_ice">ICE (Identifiant Commun de l'Entreprise)</label>
            <input type="text" name="client_ice" id="client_ice" class="form-control" 
                   value="<?php if(!empty($client_ice)){echo htmlspecialchars($client_ice);} ?>"
                   placeholder="Facultatif">
            <?php if (!empty($errors['client_ice'])): ?>
                <small class="text-danger"><?php echo $errors['client_ice']; ?></small>
            <?php endif; ?>
        </div>
        <div class="d-flex justify-content-between">
            <button type="submit" class="btn btn-primary">Ajouter</button>
            <a href="clients_table.php" class="btn btn-secondary">Annuler</a>
        </div>
    </form>
                </div>
              </div>
            </div>
          </div>
          <!--Row-->
          
        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
      <?php include ('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>

  <!-- Scroll to top -->
  <a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
  </a>

  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="js/ruang-admin.min.js"></script>

</body>

</html>