<?php
// Include database connection
include 'config/connexion.php';
require_once 'includes/simple_log.php';

// Vérifier que l'utilisateur est connecté
if (empty($_SESSION['user_email'])) {
    header('Location: login.php');
    exit;
}

// Initialize variables
$errors = [];
$success = "";
$user_id = $_SESSION['user_id'];

// Déterminer si changement forcé (première connexion)
$forcedFirst = !empty($_SESSION['must_change_password']);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $current_password = $_POST['current_password'] ?? '';
    $new_password = $_POST['new_password'];
    $confirm_password = $_POST['confirm_password'];

    // Validate current password (sauf si forcedFirst)
    if(!$forcedFirst){
        if (empty($current_password)) {
            $errors['current_password'] = "Le mot de passe actuel est obligatoire.";
        } else {
            $query = "SELECT user_pass FROM users_table WHERE id = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $user_data = $result->fetch_assoc();
                if (!password_verify($current_password, $user_data['user_pass'])) {
                    $errors['current_password'] = "Le mot de passe actuel est incorrect.";
                }
            } else {
                $errors['current_password'] = "Erreur de vérification.";
            }
            $stmt->close();
        }
    }

    // Validate new password
    if (empty($new_password)) {
        $errors['new_password'] = "Le nouveau mot de passe est obligatoire.";
    } elseif (strlen($new_password) < 6) {
        $errors['new_password'] = "Le nouveau mot de passe doit contenir au moins 6 caractères.";
    } elseif (!preg_match("/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/", $new_password)) {
        $errors['new_password'] = "Le mot de passe doit contenir au moins une minuscule, une majuscule et un chiffre.";
    }

    // Validate password confirmation
    if (empty($confirm_password)) {
        $errors['confirm_password'] = "La confirmation du mot de passe est obligatoire.";
    } elseif ($new_password !== $confirm_password) {
        $errors['confirm_password'] = "La confirmation ne correspond pas au nouveau mot de passe.";
    }

    // Check if new password is different from current
    if (!empty($new_password) && !empty($current_password) && $new_password === $current_password) {
        $errors['new_password'] = "Le nouveau mot de passe doit être différent de l'actuel.";
    }

    // Update password if no errors
    if (!array_filter($errors)) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        
    $updateQuery = "UPDATE users_table SET user_pass = ?".($forcedFirst?", must_change_password=0":"")." WHERE id = ?";
        $updateStmt = $conn->prepare($updateQuery);
        $updateStmt->bind_param("si", $hashed_password, $user_id);

        if ($updateStmt->execute()) {
            // Enregistrer dans le log
            logMessage("à Changer son mot de passe");
            // Sync vers base centrale (users_compagnie)
            try {
                if(!isset($gc_pdo)) { @require_once __DIR__.'/gestion_compagnies/config/connexion.php'; }
                if(isset($gc_pdo)) {
                    $emailSync = $_SESSION['user_email'] ?? null;
                    $compRefSync = $_SESSION['compagnie_ref'] ?? null;
                    if($emailSync && $compRefSync){
                        $upCentral = $gc_pdo->prepare('UPDATE users_compagnie SET user_pass=? WHERE user_email=? AND compagnie_ref=? LIMIT 1');
                        $upCentral->execute([$hashed_password,$emailSync,$compRefSync]);
                    }
                }
            } catch(Throwable $se) { /* sync silencieuse */ }
            $success = "Mot de passe modifié avec succès."; $_SESSION['must_change_password']=0;
        } else {
            $errors['general'] = "Erreur lors de la modification du mot de passe.";
        }

        $updateStmt->close();
    }
}

// Connection is managed globally; do not close it here.
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <?php include('includes/head.php'); ?>
  <style>
    .password-form {
        background: #fff;
        border-radius: 10px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    }
    
    .form-control:focus {
        border-color: #667eea;
        box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
    }
    
    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
    }
    
    .btn-primary:hover {
        background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    }
    
    .password-strength {
        height: 5px;
        margin-top: 5px;
        border-radius: 3px;
        transition: all 0.3s ease;
    }
    
    .strength-weak { background-color: #dc3545; }
    .strength-medium { background-color: #ffc107; }
    .strength-strong { background-color: #28a745; }
    
    .show-password {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        cursor: pointer;
        color: #6c757d;
    }
    
    .show-password:hover {
        color: #495057;
    }
    
    .form-group {
        position: relative;
    }
  </style>
</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">Changer le Mot de Passe</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
              <li class="breadcrumb-item"><a href="profile.php">Mon Profil</a></li>
              <li class="breadcrumb-item active" aria-current="page">Changer Mot de Passe</li>
            </ol>
          </div>

          <div class="row justify-content-center">
            <div class="col-lg-6">
              <!-- Form -->
              <div class="card password-form 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">
                    <i class="fas fa-key mr-2"></i>Modification du Mot de Passe
                  </h6>
                  <a href="profile.php" class="btn btn-sm btn-secondary">
                    <i class="fas fa-arrow-left mr-1"></i>Retour
                  </a>
                </div>
                <div class="card-body">
                  <?php if (!empty($errors)): ?>
                      <div class="alert alert-danger">
                          <h6><i class="fas fa-exclamation-triangle mr-1"></i>Erreurs de validation :</h6>
                          <ul class="mb-0">
                              <?php foreach ($errors as $error): ?>
                                  <li><?php echo htmlspecialchars($error); ?></li>
                              <?php endforeach; ?>
                          </ul>
                      </div>
                  <?php endif; ?>

                  <?php if (isset($success) && $success): ?>
                      <div class="alert alert-success alert-dismissible fade show" role="alert">
                          <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($success); ?>
                          <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                          </button>
                      </div>
                  <?php endif; ?>

                  <form method="POST" action="change_password.php" id="changePasswordForm">
                      <?php if(!$forcedFirst): ?>
                      <div class="form-group">
                          <label for="current_password">
                              <i class="fas fa-lock mr-1"></i>Mot de passe actuel <span class="text-danger">*</span>
                          </label>
                          <input type="password" class="form-control" id="current_password" name="current_password" required 
                                 placeholder="Votre mot de passe actuel">
                          <i class="fas fa-eye show-password" data-target="current_password"></i>
                          <?php if (isset($errors['current_password'])): ?>
                              <small class="text-danger"><?php echo $errors['current_password']; ?></small>
                          <?php endif; ?>
                      </div>
                      <?php else: ?>
                        <input type="hidden" name="current_password" value="__first__">
                        <div class="alert alert-info py-2"><i class="fas fa-info-circle mr-1"></i>Veuillez définir un nouveau mot de passe avant de continuer.</div>
                      <?php endif; ?>

                      <div class="form-group">
                          <label for="new_password">
                              <i class="fas fa-key mr-1"></i>Nouveau mot de passe <span class="text-danger">*</span>
                          </label>
                          <input type="password" class="form-control" id="new_password" name="new_password" required 
                                 placeholder="Votre nouveau mot de passe">
                          <i class="fas fa-eye show-password" data-target="new_password"></i>
                          <div class="password-strength" id="passwordStrength"></div>
                          <small class="form-text text-muted">
                              Le mot de passe doit contenir au moins 6 caractères avec au moins une minuscule, une majuscule et un chiffre.
                          </small>
                          <?php if (isset($errors['new_password'])): ?>
                              <small class="text-danger"><?php echo $errors['new_password']; ?></small>
                          <?php endif; ?>
                      </div>

                      <div class="form-group">
                          <label for="confirm_password">
                              <i class="fas fa-check mr-1"></i>Confirmer le nouveau mot de passe <span class="text-danger">*</span>
                          </label>
                          <input type="password" class="form-control" id="confirm_password" name="confirm_password" required 
                                 placeholder="Répétez votre nouveau mot de passe">
                          <i class="fas fa-eye show-password" data-target="confirm_password"></i>
                          <div id="passwordMatch" class="mt-2"></div>
                          <?php if (isset($errors['confirm_password'])): ?>
                              <small class="text-danger"><?php echo $errors['confirm_password']; ?></small>
                          <?php endif; ?>
                      </div>

                      <hr>

                      <div class="d-flex justify-content-between">
                          <a href="profile.php" class="btn btn-secondary">
                              <i class="fas fa-times mr-1"></i>Annuler
                          </a>
                          <button type="submit" class="btn btn-primary" id="submitBtn" disabled>
                              <i class="fas fa-save mr-1"></i>Changer le mot de passe
                          </button>
                      </div>
                  </form>
                </div>
              </div>
            </div>
          </div>

          <!-- Security Tips -->
          <div class="row justify-content-center">
            <div class="col-lg-6">
              <div class="card">
                <div class="card-header py-3">
                  <h6 class="m-0 font-weight-bold text-warning">
                    <i class="fas fa-shield-alt mr-2"></i>Conseils de sécurité
                  </h6>
                </div>
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-6">
                      <h6 class="font-weight-bold text-success">✓ Recommandé :</h6>
                      <ul class="text-sm">
                        <li>Au moins 8 caractères</li>
                        <li>Majuscules et minuscules</li>
                        <li>Chiffres et symboles</li>
                        <li>Unique et non prévisible</li>
                      </ul>
                    </div>
                    <div class="col-md-6">
                      <h6 class="font-weight-bold text-danger">✗ À éviter :</h6>
                      <ul class="text-sm">
                        <li>Informations personnelles</li>
                        <li>Mots du dictionnaire</li>
                        <li>Suites logiques (123, abc)</li>
                        <li>Réutiliser d'anciens mots de passe</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </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>

  <script>
    $(document).ready(function() {
        // Show/Hide password functionality
        $('.show-password').on('click', function() {
            const targetId = $(this).data('target');
            const targetInput = $('#' + targetId);
            const icon = $(this);
            
            if (targetInput.attr('type') === 'password') {
                targetInput.attr('type', 'text');
                icon.removeClass('fa-eye').addClass('fa-eye-slash');
            } else {
                targetInput.attr('type', 'password');
                icon.removeClass('fa-eye-slash').addClass('fa-eye');
            }
        });

        // Password strength checker
        $('#new_password').on('input', function() {
            const password = $(this).val();
            const strengthBar = $('#passwordStrength');
            let strength = 0;
            
            // Check length
            if (password.length >= 6) strength++;
            if (password.length >= 8) strength++;
            
            // Check for lowercase
            if (/[a-z]/.test(password)) strength++;
            
            // Check for uppercase
            if (/[A-Z]/.test(password)) strength++;
            
            // Check for numbers
            if (/\d/.test(password)) strength++;
            
            // Check for special characters
            if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;
            
            // Update strength bar
            strengthBar.removeClass('strength-weak strength-medium strength-strong');
            
            if (strength < 3) {
                strengthBar.addClass('strength-weak');
                strengthBar.css('width', '33%');
            } else if (strength < 5) {
                strengthBar.addClass('strength-medium');
                strengthBar.css('width', '66%');
            } else {
                strengthBar.addClass('strength-strong');
                strengthBar.css('width', '100%');
            }
            
            checkFormValidity();
        });

        // Password match checker
        $('#confirm_password').on('input', function() {
            const password = $('#new_password').val();
            const confirmPassword = $(this).val();
            const matchDiv = $('#passwordMatch');
            
            if (confirmPassword.length === 0) {
                matchDiv.html('');
            } else if (password === confirmPassword) {
                matchDiv.html('<small class="text-success"><i class="fas fa-check mr-1"></i>Les mots de passe correspondent</small>');
            } else {
                matchDiv.html('<small class="text-danger"><i class="fas fa-times mr-1"></i>Les mots de passe ne correspondent pas</small>');
            }
            
            checkFormValidity();
        });

                // Check form validity
                function checkFormValidity() {
                        const hasCurrentField = $('#current_password').length > 0;
                        const currentPassword = hasCurrentField ? $('#current_password').val() : '__first__';
                        const newPassword = $('#new_password').val();
                        const confirmPassword = $('#confirm_password').val();
                        const submitBtn = $('#submitBtn');

                        let isValid = newPassword.length >= 6 &&
                                                    /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(newPassword) &&
                                                    newPassword === confirmPassword;
                        if(hasCurrentField){
                            isValid = isValid && currentPassword.length > 0 && newPassword !== currentPassword;
                        }
                        submitBtn.prop('disabled', !isValid);
                }

                // Bind validity checks
                $('#new_password, #confirm_password').on('input', checkFormValidity);
                if($('#current_password').length){ $('#current_password').on('input', checkFormValidity); }

                // Auto-focus: champ actuel ou nouveau selon mode
                if($('#current_password').length){ $('#current_password').focus(); } else { $('#new_password').focus(); }

        // Form submission confirmation
        $('#changePasswordForm').on('submit', function(e) {
            if (!confirm('Êtes-vous sûr de vouloir changer votre mot de passe ?')) {
                e.preventDefault();
            }
        });
    });
  </script>

</body>

</html>
