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

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

// Récupérer les informations complètes de l'utilisateur depuis la base de données
$user_id = $_SESSION['user_id'];
$query = "SELECT * 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) {
    header('Location: login.php');
    exit;
}

$user = $result->fetch_assoc();
$stmt->close();

// Statistiques de l'utilisateur
$stats = [];

// Compter les polices créées par cet utilisateur (si il y a un champ agent/user dans policy_table)
try {
    $user_name = $_SESSION['user_name'];
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM policy_table WHERE agent = ?");
    $stmt->bind_param("s", $user_name);
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['policies'] = $result->fetch_assoc()['count'];
    $stmt->close();
} catch (Exception $e) {
    $stats['policies'] = 0;
}

// Compter les reçus créés par cet utilisateur
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM receipts_table WHERE agent = ?");
    $stmt->bind_param("s", $user_name);
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['receipts'] = $result->fetch_assoc()['count'];
    $stmt->close();
} catch (Exception $e) {
    $stats['receipts'] = 0;
}

// Compter les factures créées par cet utilisateur
try {
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM facture_table WHERE created_by = ? OR agent = ?");
    $stmt->bind_param("ss", $user_name, $user_name);
    $stmt->execute();
    $result = $stmt->get_result();
    $stats['factures'] = $result->fetch_assoc()['count'];
    $stmt->close();
} catch (Exception $e) {
    $stats['factures'] = 0;
}

// Préparer logo agence avec fallback si le fichier n'existe pas
$compagnieRef = isset($_SESSION['compagnie_ref']) ? $_SESSION['compagnie_ref'] : 'default';
$logoFileName = 'logo.png';
$logoRelativePath = 'data/' . basename($compagnieRef) . '/' . $logoFileName; // chemin relatif utilisé dans src
$logoFsPath = __DIR__ . '/' . $logoRelativePath; // chemin absolu
if(!is_file($logoFsPath) || filesize($logoFsPath) == 0){
  $logoRelativePath = 'data/default_logo.png';
}

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

<head>
  <?php include('includes/head.php'); ?>  <style>
    .profile-card {
        background: url('https://cdn.pixabay.com/photo/2022/04/15/07/58/sunset-7133867_1280.jpg') center/cover;
        background-size: cover;
        background-position: center;
        border-radius: 15px;
        color: white;
        padding: 30px;
        text-align: center;
        margin-bottom: 30px;
        position: relative;
    }
    
    .profile-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.4);
        border-radius: 15px;
        z-index: 1;
    }
    
    .profile-card > * {
        position: relative;
        z-index: 2;
    }
    
    .profile-avatar {
        width: 100px;
        height: 100px;
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        font-size: 2.5rem;
        border: 3px solid rgba(255, 255, 255, 0.3);
    }
      .stat-card {
        transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        border: none;
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
        background: linear-gradient(145deg, #ffffff 0%, #f8f9ff 100%);
        overflow: hidden;
        position: relative;
    }
    
    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: var(--gradient-color, linear-gradient(135deg, #667eea 0%, #764ba2 100%));
    }
    
    .stat-card.border-left-primary::before {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
    }
    
    .stat-card.border-left-success::before {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
    }
    
    .stat-card.border-left-info::before {
        background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
    }
    
    .stat-card.border-left-warning::before {
        background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
    }
    
    .stat-card:hover {
        transform: translateY(-8px) scale(1.02);
        box-shadow: 0 25px 50px rgba(0, 0, 0, 0.15);
    }
    
    .stat-icon {
        font-size: 3rem;
        margin-bottom: 20px;
        background: linear-gradient(135deg, currentColor 0%, rgba(0,0,0,0.1) 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        filter: drop-shadow(0 2px 4px rgba(0,0,0,0.1));
    }
    
    .card {
        border: none;
        border-radius: 20px;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
        background: linear-gradient(145deg, #ffffff 0%, #f8f9ff 100%);
        transition: all 0.3s ease;
        overflow: hidden;
        position: relative;
    }
    
    .card:hover {
        transform: translateY(-2px);
        box-shadow: 0 15px 40px rgba(0, 0, 0, 0.12);
    }
    
    .card-header {
        background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        border-radius: 20px 20px 0 0 !important;
        position: relative;
    }
    
    .card-header::before {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        height: 2px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    
    .info-item {
        padding: 15px 0;
        border-bottom: 1px solid rgba(0, 0, 0, 0.05);
        transition: all 0.2s ease;
        border-radius: 8px;
        margin: 2px 0;
    }
    
    .info-item:hover {
        background: linear-gradient(135deg, #f8f9ff 0%, #e9ecef 50%);
        padding-left: 10px;
        border-left: 3px solid #667eea;
    }
    
    .info-item:last-child {
        border-bottom: none;
    }
    
    .info-label {
        font-weight: 700;
        color: #495057;
        width: 160px;
        display: inline-block;
        font-size: 0.9rem;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }
    
    .info-value {
        color: #2c3e50;
        font-weight: 600;
        font-size: 1rem;
    }
    
    .status-badge {
        font-size: 0.85rem;
        padding: 8px 16px;
        border-radius: 25px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    
    .badge-success {
        background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);
        border: none;
    }
    
    .badge-danger {
        background: linear-gradient(135deg, #e74a3b 0%, #c0392b 100%);
        border: none;
    }
    
    .badge-primary {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        border: none;
    }
    
    .role-badge {
        font-size: 1rem;
        padding: 10px 20px;
        border-radius: 30px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border: none;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 1px;
        box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
    }
    
    .btn {
        border-radius: 15px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
    }
    
    .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }
    
    .btn-outline-warning {
        border: 2px solid #f6c23e;
        background: linear-gradient(135deg, rgba(246, 194, 62, 0.1) 0%, rgba(221, 162, 10, 0.1) 100%);
    }
    
    .btn-outline-warning:hover {
        background: linear-gradient(135deg, #f6c23e 0%, #dda20a 100%);
        border-color: #dda20a;
    }
    
    .btn-outline-danger {
        border: 2px solid #e74a3b;
        background: linear-gradient(135deg, rgba(231, 74, 59, 0.1) 0%, rgba(192, 57, 43, 0.1) 100%);
    }
    
    .btn-outline-danger:hover {
        background: linear-gradient(135deg, #e74a3b 0%, #c0392b 100%);
        border-color: #c0392b;
    }
  </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">Mon Profil</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
              <li class="breadcrumb-item active" aria-current="page">Mon Profil</li>
            </ol>
          </div>

          <!-- Profile Header -->
          <div class="profile-card">
            <div class="profile-avatar">
              <i class="fas fa-user"></i>
            </div>
            <h2 class="mb-2"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></h2>
            <p class="mb-3 opacity-75"><?php echo htmlspecialchars($user['user_email']); ?></p>
            <span class="role-badge"><?php echo htmlspecialchars($user['user_role']); ?></span>
          </div>

          <div class="row">
            <!-- Statistiques -->
            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card stat-card border-left-primary">
                <div class="card-body text-center">
                  <div class="stat-icon text-primary">
                    <i class="fas fa-file-contract"></i>
                  </div>                  <div class="text-xs font-weight-bold text-primary text-uppercase mb-1" style="letter-spacing: 1px;">Polices créées</div>
                  <div class="h3 mb-0 font-weight-bold text-gray-800" style="color: #2c3e50 !important;"><?php echo number_format($stats['policies']); ?></div>
                </div>
              </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card stat-card border-left-success">
                <div class="card-body text-center">
                  <div class="stat-icon text-success">
                    <i class="fas fa-receipt"></i>
                  </div>                  <div class="text-xs font-weight-bold text-success text-uppercase mb-1" style="letter-spacing: 1px;">Reçus émis</div>
                  <div class="h3 mb-0 font-weight-bold text-gray-800" style="color: #2c3e50 !important;"><?php echo number_format($stats['receipts']); ?></div>
                </div>
              </div>
            </div>

            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card stat-card border-left-info">
                <div class="card-body text-center">
                  <div class="stat-icon text-info">
                    <i class="fas fa-file-invoice"></i>
                  </div>                  <div class="text-xs font-weight-bold text-info text-uppercase mb-1" style="letter-spacing: 1px;">Factures créées</div>
                  <div class="h3 mb-0 font-weight-bold text-gray-800" style="color: #2c3e50 !important;"><?php echo number_format($stats['factures']); ?></div>
                </div>
              </div>
            </div>            <div class="col-xl-3 col-md-6 mb-4">
              <div class="card stat-card border-left-warning">
                <div class="card-body text-center">
                  <div class="stat-icon text-warning">
                    <i class="fas fa-users"></i>
                  </div>                  <div class="text-xs font-weight-bold text-warning text-uppercase mb-1" style="letter-spacing: 1px;">Activité</div>
                  <div class="h4 mb-0 font-weight-bold" style="color: #2c3e50 !important;">
                    <span class="badge badge-success" style="font-size: 1rem; padding: 8px 16px;">Active</span>
                  </div>
                </div>
              </div>
            </div>
          </div>          <div class="row">
            <!-- Informations personnelles -->
            <div class="col-lg-8">
              <div class="card mb-4">
                <div class="card-header py-3 d-flex justify-content-between align-items-center">
                  <h6 class="m-0 font-weight-bold text-primary">Informations Personnelles</h6>
                  <a href="edit_profile.php" class="btn btn-sm btn-primary">
                    <i class="fas fa-edit mr-1"></i>Modifier
                  </a>
                </div>
                <div class="card-body">
                  <div class="info-item">
                    <span class="info-label">Prénom :</span>
                    <span class="info-value"><?php echo htmlspecialchars($user['first_name']); ?></span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">Nom :</span>
                    <span class="info-value"><?php echo htmlspecialchars($user['last_name']); ?></span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">Email :</span>
                    <span class="info-value"><?php echo htmlspecialchars($user['user_email']); ?></span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">Téléphone :</span>
                    <span class="info-value"><?php echo htmlspecialchars($user['phone_num']); ?></span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">Rôle :</span>
                    <span class="info-value">
                      <span class="badge badge-primary"><?php echo htmlspecialchars($user['user_role']); ?></span>
                    </span>
                  </div>
                  <div class="info-item">
                    <span class="info-label">Statut :</span>
                    <span class="info-value">
                      <?php if ($user['status'] == 1): ?>
                        <span class="badge badge-success status-badge">Actif</span>
                      <?php else: ?>
                        <span class="badge badge-danger status-badge">Inactif</span>
                      <?php endif; ?>
                    </span>
                  </div>
                  <?php if (isset($user['created_at']) && !empty($user['created_at'])): ?>
                  <div class="info-item">
                    <span class="info-label">Créé le :</span>
                    <span class="info-value"><?php echo date('d/m/Y à H:i', strtotime($user['created_at'])); ?></span>
                  </div>
                  <?php endif; ?>
                  <?php if (isset($user['updated_at']) && !empty($user['updated_at'])): ?>
                  <div class="info-item">
                    <span class="info-label">Modifié le :</span>
                    <span class="info-value"><?php echo date('d/m/Y à H:i', strtotime($user['updated_at'])); ?></span>
                  </div>
                  <?php endif; ?>
                </div>
              </div>

              <!-- Session Actuelle -->
              <div class="card mb-4">
                <div class="card-header py-3">
                  <h6 class="m-0 font-weight-bold text-info">Session Actuelle</h6>
                </div>
                <div class="card-body">
                  <div class="row">
                    <div class="col-md-6">
                      <small class="text-muted">
                        <i class="fas fa-clock mr-1"></i>
                        Connecté depuis: <?php echo date('d/m/Y H:i'); ?>
                      </small>
                    </div>
                    <div class="col-md-6">
                      <small class="text-muted">
                        <i class="fas fa-globe mr-1"></i>
                        IP: <?php echo $_SERVER['REMOTE_ADDR'] ?? 'N/A'; ?>
                      </small>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- Agence et Sécurité -->
            <div class="col-lg-4">
              <!-- Informations Agence -->
              <div class="card mb-4">
                <div class="card-header py-3">
                  <h6 class="m-0 font-weight-bold text-success">Agence</h6>
                </div>
                <div class="card-body">
                  <div class="text-center">
        <img src="<?php echo htmlspecialchars('./'.$logoRelativePath,ENT_QUOTES,'UTF-8'); ?>" 
          alt="Logo Agence" class="img-fluid mb-3" style="max-height: 80px;object-fit:contain;background:#fff;padding:4px;border-radius:6px;">
                    <p class="font-weight-bold">Référence: <?php echo htmlspecialchars($_SESSION['compagnie_ref'] ?? '123456'); ?></p>
                  </div>
                </div>
              </div>

              <!-- Actions de Sécurité -->
              <div class="card mb-4">
                <div class="card-header py-3">
                  <h6 class="m-0 font-weight-bold text-warning">Sécurité</h6>
                </div>
                <div class="card-body">
                  <div class="d-grid gap-2">
                    <a href="change_password.php" class="btn btn-outline-warning btn-block mb-2">
                      <i class="fas fa-key mr-2"></i>Changer le mot de passe
                    </a>
                    <a href="logout.php" class="btn btn-outline-danger btn-block">
                      <i class="fas fa-sign-out-alt mr-2"></i>Se déconnecter
                    </a>
                  </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() {
      // Animation des cartes statistiques au chargement
      $('.stat-card').each(function(index) {
        $(this).delay(index * 100).animate({opacity: 1}, 500);
      });
        // Effet de compteur pour les statistiques
      $('.h3').each(function() {
        var $this = $(this);
        var countTo = parseInt($this.text().replace(/,/g, ''));
        
        if (!isNaN(countTo)) {
          $({ countNum: 0 }).animate({
            countNum: countTo
          }, {
            duration: 2000,
            easing: 'linear',
            step: function() {
              $this.text(Math.floor(this.countNum).toLocaleString());
            },
            complete: function() {
              $this.text(countTo.toLocaleString());
            }
          });
        }
      });
    });
  </script>

</body>

</html>
