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

// Traitement de la mise à jour du statut
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    $notification_id = intval($_POST['notification_id']);
    $new_status = $_POST['status'];
    
    $allowed_statuses = ['pending', 'sent', 'failed'];
    if (in_array($new_status, $allowed_statuses)) {
        $update_sql = "UPDATE notification_log SET status = ? WHERE id = ?";
        $update_stmt = $conn->prepare($update_sql);
        $update_stmt->bind_param("si", $new_status, $notification_id);
        $update_stmt->execute();
        $update_stmt->close();
    }
}

// Récupérer les notifications avec pagination
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$page = (int)$page; // S'assurer que $page est bien un entier
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Filtres
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$date_filter = isset($_GET['date']) ? $_GET['date'] : '';

// Construction de la requête
$where_conditions = [];
$params = [];
$param_types = '';

if (!empty($status_filter)) {
    $where_conditions[] = "nl.status = ?";
    $params[] = $status_filter;
    $param_types .= 's';
}

if (!empty($date_filter)) {
    $where_conditions[] = "DATE(nl.sent_date) = ?";
    $params[] = $date_filter;
    $param_types .= 's';
}

$where_clause = '';
if (!empty($where_conditions)) {
    $where_clause = 'WHERE ' . implode(' AND ', $where_conditions);
}

// Compter le total des notifications
$count_sql = "SELECT COUNT(*) as total 
              FROM notification_log nl 
              LEFT JOIN policy_table p ON nl.policy_id = p.id 
              $where_clause";
$count_stmt = $conn->prepare($count_sql);
if (!empty($params)) {
    $count_stmt->bind_param($param_types, ...$params);
}
$count_stmt->execute();
$total_result = $count_stmt->get_result();
$total_row = $total_result->fetch_assoc();
$total_notifications = intval($total_row['total']);
$total_pages = intval(ceil($total_notifications / $per_page));
$total_pages = (int)$total_pages; // S'assurer que $total_pages est bien un entier
$count_stmt->close();

// Récupérer les notifications
$sql = "SELECT nl.*, p.n_policy, p.client_name, p.end_date, p.montant_to_paie
        FROM notification_log nl
        LEFT JOIN policy_table p ON nl.policy_id = p.id
        $where_clause
        ORDER BY nl.sent_date DESC
        LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($sql);
$stmt->bind_param($param_types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

$notifications = [];
while ($row = $result->fetch_assoc()) {
    $notifications[] = $row;
}
$stmt->close();

// Statistiques
$stats_sql = "SELECT 
                COUNT(*) as total,
                SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
                SUM(CASE WHEN status = 'sent' THEN 1 ELSE 0 END) as sent,
                SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed
              FROM notification_log";
$stats_result = $conn->query($stats_sql);
$stats = $stats_result->fetch_assoc();
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include ('includes/head.php'); ?>  <style>
    .status-badge {
      font-size: 0.8em;
    }
    .notification-message {
      max-width: 300px;
      white-space: pre-wrap;
      font-size: 0.85em;
    }
  </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">Historique des Notifications (Français + العربية)</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item"><a href="notifications_expiration.php">Notifications</a></li>
              <li class="breadcrumb-item active" aria-current="page">Historique</li>
            </ol>
          </div>

          <!-- Statistiques -->
          <div class="row mb-4">
            <div class="col-md-3">
              <div class="card border-left-primary">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                        Total Notifications</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['total']; ?></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-bell fa-2x text-primary"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-left-warning">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                        En Attente</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['pending']; ?></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-clock fa-2x text-warning"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-left-success">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                        Envoyées</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['sent']; ?></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-check fa-2x text-success"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-left-danger">
                <div class="card-body">
                  <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                      <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                        Échecs</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $stats['failed']; ?></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-times fa-2x text-danger"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Filtres -->
          <div class="card mb-4">
            <div class="card-body">
              <form method="GET" action="" class="row">
                <div class="col-md-3">
                  <label for="status">Statut :</label>
                  <select name="status" id="status" class="form-control">
                    <option value="">Tous les statuts</option>
                    <option value="pending" <?php echo $status_filter === 'pending' ? 'selected' : ''; ?>>En attente</option>
                    <option value="sent" <?php echo $status_filter === 'sent' ? 'selected' : ''; ?>>Envoyées</option>
                    <option value="failed" <?php echo $status_filter === 'failed' ? 'selected' : ''; ?>>Échecs</option>
                  </select>
                </div>                <div class="col-md-3">
                  <label for="date">Date :</label>
                  <input type="date" name="date" id="date" class="form-control" value="<?php echo htmlspecialchars($date_filter ?? ''); ?>">
                </div>
                <div class="col-md-3">
                  <label>&nbsp;</label>
                  <div>
                    <button type="submit" class="btn btn-primary">Filtrer</button>
                    <a href="?" class="btn btn-secondary">Reset</a>
                  </div>
                </div>                <div class="col-md-3">
                  <label>&nbsp;</label>
                  <div>
                    <div class="btn-group" role="group">
                      <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown">
                        <i class="fas fa-plus"></i> Nouvelles Notifications
                      </button>
                      <div class="dropdown-menu">
                        <a class="dropdown-item" href="notifications_email_cron.php">
                          <i class="fas fa-envelope"></i> Notifications Email
                        </a>
                        <a class="dropdown-item" href="notifications_sms_cron.php">
                          <i class="fas fa-sms"></i> Notifications SMS
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              </form>
            </div>
          </div>

          <!-- Liste des notifications -->
          <div class="card">
            <div class="card-header py-3">
              <h6 class="m-0 font-weight-bold text-primary">
                Notifications (<?php echo $total_notifications; ?> au total)
              </h6>
            </div>
            <div class="card-body">
              <?php if (empty($notifications)): ?>
                <div class="text-center py-4">
                  <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                  <h5>Aucune notification trouvée</h5>
                  <p class="text-muted">Aucune notification ne correspond aux critères sélectionnés.</p>
                </div>
              <?php else: ?>
                <div class="table-responsive">
                  <table class="table table-bordered">
                    <thead>                      <tr>
                        <th>Date</th>
                        <th>Police</th>
                        <th>Client</th>
                        <th>Type</th>
                        <th>Contact</th>
                        <th>Statut</th>
                        <th>Actions</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php foreach ($notifications as $notification): ?>
                      <tr>                        <td>
                          <small><?php echo $notification['sent_date'] ? date('d/m/Y H:i', strtotime($notification['sent_date'])) : 'N/A'; ?></small>
                        </td>                        <td>
                          <strong><?php echo htmlspecialchars($notification['n_policy'] ?? ''); ?></strong>
                          <br><small class="text-muted">
                            Exp: <?php echo $notification['end_date'] ? date('d/m/Y', strtotime($notification['end_date'])) : 'N/A'; ?>
                          </small>
                        </td>                        <td>
                          <?php echo htmlspecialchars($notification['client_name'] ?? ''); ?>
                          <br><small class="text-muted">
                            <?php echo number_format($notification['montant_to_paie'] ?? 0, 2, ',', ' '); ?> DH
                          </small>
                        </td>
                        <td>
                          <?php
                          $type_classes = [
                            'email' => 'badge-primary',
                            'sms' => 'badge-success',
                            'whatsapp' => 'badge-info'
                          ];
                          $type_icons = [
                            'email' => 'fas fa-envelope',
                            'sms' => 'fas fa-sms',
                            'whatsapp' => 'fab fa-whatsapp'
                          ];
                          $type = $notification['notification_type'] ?? 'email';
                          $type_class = $type_classes[$type] ?? 'badge-secondary';
                          $type_icon = $type_icons[$type] ?? 'fas fa-bell';
                          ?>
                          <span class="badge <?php echo $type_class; ?>">
                            <i class="<?php echo $type_icon; ?>"></i> <?php echo strtoupper($type); ?>
                          </span>
                        </td>                        <td>
                          <?php if ($type === 'email'): ?>
                            <span style="font-family: monospace; font-size: 0.9em;">
                              <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($notification['recipient'] ?? 'N/A'); ?>
                            </span>
                          <?php elseif ($type === 'sms'): ?>
                            <span style="font-family: monospace; font-size: 0.9em;">
                              <i class="fas fa-phone"></i> <?php echo htmlspecialchars($notification['recipient'] ?? 'N/A'); ?>
                            </span>
                          <?php else: ?>
                            <span style="font-family: monospace; font-size: 0.9em;">
                              <?php echo htmlspecialchars($notification['recipient'] ?? 'N/A'); ?>
                            </span>
                          <?php endif; ?>
                        </td>
                        <td>
                          <?php
                          $status_classes = [
                            'pending' => 'badge-warning',
                            'sent' => 'badge-success',
                            'failed' => 'badge-danger'
                          ];
                          $status_labels = [
                            'pending' => 'En attente',
                            'sent' => 'Envoyée',
                            'failed' => 'Échec'
                          ];
                          $badge_class = $status_classes[$notification['status']] ?? 'badge-secondary';
                          $status_label = $status_labels[$notification['status']] ?? $notification['status'];
                          ?>
                          <span class="badge <?php echo $badge_class; ?> status-badge">
                            <?php echo $status_label; ?>
                          </span>
                        </td>                        <td>
                          <div class="btn-group" role="group">
                            <button type="button" class="btn btn-sm btn-outline-primary dropdown-toggle" 
                                    data-toggle="dropdown" title="Changer le statut">
                              <i class="fas fa-edit"></i>
                            </button>
                            <div class="dropdown-menu">
                              <form method="POST" style="margin: 0;">
                                <input type="hidden" name="notification_id" value="<?php echo $notification['id']; ?>">
                                <button type="submit" name="update_status" value="pending" 
                                        class="dropdown-item <?php echo $notification['status'] === 'pending' ? 'active' : ''; ?>">
                                  <input type="hidden" name="status" value="pending">
                                  <i class="fas fa-clock text-warning"></i> En attente
                                </button>
                                <button type="submit" name="update_status" value="sent" 
                                        class="dropdown-item <?php echo $notification['status'] === 'sent' ? 'active' : ''; ?>">
                                  <input type="hidden" name="status" value="sent">
                                  <i class="fas fa-check text-success"></i> Envoyée
                                </button>
                                <button type="submit" name="update_status" value="failed" 
                                        class="dropdown-item <?php echo $notification['status'] === 'failed' ? 'active' : ''; ?>">
                                  <input type="hidden" name="status" value="failed">
                                  <i class="fas fa-times text-danger"></i> Échec
                                </button>
                              </form>
                            </div>
                          </div>
                        </td>
                      </tr>
                      <?php endforeach; ?>
                    </tbody>
                  </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <nav aria-label="Navigation des notifications">
                  <ul class="pagination justify-content-center">                    <?php if ($page > 1): ?>
                    <li class="page-item">
                      <a class="page-link" href="?page=<?php echo ((int)$page - 1); ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>">Précédent</a>
                    </li>
                    <?php endif; ?>

                    <?php for ($i = max(1, (int)$page - 2); $i <= min((int)$total_pages, (int)$page + 2); $i++): ?>
                    <li class="page-item <?php echo $i === (int)$page ? 'active' : ''; ?>">
                      <a class="page-link" href="?page=<?php echo $i; ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>"><?php echo $i; ?></a>
                    </li>
                    <?php endfor; ?>

                    <?php if ($page < $total_pages): ?>
                    <li class="page-item">
                      <a class="page-link" href="?page=<?php echo ((int)$page + 1); ?>&status=<?php echo urlencode($status_filter); ?>&date=<?php echo urlencode($date_filter); ?>">Suivant</a>
                    </li>
                    <?php endif; ?>
                  </ul>
                </nav>
                <?php endif; ?>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
     <?php include ('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>

  <!-- Modal pour afficher le message complet -->
  <div class="modal fade" id="fullMessageModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
      <div class="modal-content">        <div class="modal-header">
          <h5 class="modal-title">Détails de la Notification</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span>&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div id="fullMessageContent"></div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Include required scripts -->
  <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>
    function showFullMessage(notificationId) {
      // Récupérer le message complet via AJAX
      $.ajax({
        url: 'get_notification_message.php',
        method: 'GET',
        data: { id: notificationId },
        success: function(response) {
          $('#fullMessageContent').html('<pre>' + response + '</pre>');
          $('#fullMessageModal').modal('show');
        },
        error: function() {
          alert('Erreur lors du chargement du message');
        }
      });
    }
  </script>
</body>

</html>
