<?php
session_start();
// Rediriger vers login si non connecté
if (empty($_SESSION['user_email']) && empty($_SESSION['user_name'])) {
  header('Location: login.php');
  exit;
}
// Charger la connexion DB compagnie (peut exposer $COMPANY_DB_AVAILABLE=false si session incomplète)
include 'config/connexion.php';
if (empty($COMPANY_DB_AVAILABLE) || !($conn instanceof mysqli)) {
  header('Location: login.php');
  exit;
}

// Rediriger les rôles non admin / non Super admin vers le dashboard agent simplifié
$__role = strtolower($_SESSION['user_role'] ?? '');
if (!in_array($__role, ['super admin','admin'], true)) {
  header('Location: dashboard_agent.php');
  exit;
}

// Récupérer le mois et l'année courants (en integer pour éviter les zéros en trop)
$currentMonth = (int)date('n');
$currentYear = (int)date('Y');

// Récupérer le mois et l'année précédents
$lastMonth = (int)date('n', strtotime('first day of last month'));
$lastMonthYear = (int)date('Y', strtotime('first day of last month'));

// Montant des chèques et effets validés pour le mois courant (utiliser la date d'échéance)
$sqlCurrent = "SELECT SUM(montant_paye) as total 
    FROM receipts_table 
    WHERE paiement_statut = 1 
      AND UPPER(paiement_mode) IN ('CHEQUE', 'EFFET')
      AND MONTH(echeance_date) = ? AND YEAR(echeance_date) = ?";
$stmtCurrent = $conn->prepare($sqlCurrent);
$stmtCurrent->bind_param("ii", $currentMonth, $currentYear);
$stmtCurrent->execute();
$stmtCurrent->bind_result($totalCurrent);
$stmtCurrent->fetch();
$banqueCurrent = $totalCurrent !== null ? $totalCurrent : 0;
$stmtCurrent->close();

// Montant des chèques et effets validés pour le mois précédent (utiliser la date d'échéance)
$sqlLast = "SELECT SUM(montant_paye) as total 
    FROM receipts_table 
    WHERE paiement_statut = 1 
      AND UPPER(paiement_mode) IN ('CHEQUE', 'EFFET')
      AND MONTH(echeance_date) = ? AND YEAR(echeance_date) = ?";
$stmtLast = $conn->prepare($sqlLast);
$stmtLast->bind_param("ii", $lastMonth, $lastMonthYear);
$stmtLast->execute();
$stmtLast->bind_result($totalLast);
$stmtLast->fetch();
$banqueLast = $totalLast !== null ? $totalLast : 0;
$stmtLast->close();

// Montant des espèces validées pour le mois courant (caisse) -- utiliser date_creation
$sqlCaisse = "SELECT SUM(montant_paye) as total 
    FROM receipts_table 
    WHERE paiement_statut = 1 
      AND UPPER(paiement_mode) = 'ESPECE'
      AND MONTH(date_creation) = ? AND YEAR(date_creation) = ?";
$stmtCaisse = $conn->prepare($sqlCaisse);
$stmtCaisse->bind_param("ii", $currentMonth, $currentYear);
$stmtCaisse->execute();
$stmtCaisse->bind_result($totalCaisse);
$stmtCaisse->fetch();
$caisseCurrent = $totalCaisse !== null ? $totalCaisse : 0;
$stmtCaisse->close();

// Montant des espèces validées pour le mois précédent (caisse) -- utiliser date_creation
$sqlCaisseLast = "SELECT SUM(montant_paye) as total 
    FROM receipts_table 
    WHERE paiement_statut = 1 
      AND UPPER(paiement_mode) = 'ESPECE'
      AND MONTH(date_creation) = ? AND YEAR(date_creation) = ?";
$stmtCaisseLast = $conn->prepare($sqlCaisseLast);
$stmtCaisseLast->bind_param("ii", $lastMonth, $lastMonthYear);
$stmtCaisseLast->execute();
$stmtCaisseLast->bind_result($totalCaisseLast);
$stmtCaisseLast->fetch();
$caisseLast = $totalCaisseLast !== null ? $totalCaisseLast : 0;
$stmtCaisseLast->close();

// Calcul de la variation en pourcentage
$variation = 0;
if ($banqueLast > 0) {
    $variation = (($banqueCurrent - $banqueLast) / $banqueLast) * 100;
}

// Calcul de la variation en pourcentage pour la caisse
$caisseVariation = 0;
if ($caisseLast > 0) {
    $caisseVariation = (($caisseCurrent - $caisseLast) / $caisseLast) * 100;
}

// Récupérer les montants validés par mois
$sql = "SELECT MONTH(date_creation) AS month, SUM(montant_paye) AS total_validated 
        FROM receipts_table 
        WHERE paiement_statut = 1 
        GROUP BY MONTH(date_creation)";
$result = $conn->query($sql);

$monthly_data = [];
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $monthly_data[intval($row['month'])] = floatval($row['total_validated']);
    }
}

// Préparer les données pour le graphique
$chart_labels = json_encode(range(1, 12)); // Mois de 1 à 12
$chart_data = json_encode(array_map(function ($month) use ($monthly_data) {
    return $monthly_data[$month] ?? 0;
}, range(1, 12)));


// Récupérer le nombre de chèques, effets ou virements à échéance aujourd'hui et non validés
$today = date('Y-m-d');
$sqlPaiementsEcheance = "SELECT COUNT(*) AS total_echeance_today FROM receipts_table WHERE paiement_statut = 0 AND (
    UPPER(paiement_mode) = 'CHEQUE' OR UPPER(paiement_mode) = 'EFFET' OR UPPER(paiement_mode) = 'VIREMENT BANCAIRE'
) AND echeance_date = ?";
$stmtEcheance = $conn->prepare($sqlPaiementsEcheance);
$stmtEcheance->bind_param("s", $today);
$stmtEcheance->execute();
$stmtEcheance->bind_result($totalEcheanceToday);
$stmtEcheance->fetch();
$total_echeance_today = $totalEcheanceToday !== null ? intval($totalEcheanceToday) : 0;
$stmtEcheance->close();

// Récupérer le total des crédits vis-à-vis des clients
// Récupérer le nombre de rappels (polices à appeler)
$dateLimit = date('Y-m-d', strtotime('+7 days'));
$today = date('Y-m-d');
$sqlRappels = "SELECT COUNT(*) AS total_rappels FROM policy_table WHERE end_date <= '" . $dateLimit . "' AND end_date >= CURDATE() AND (appel IS NULL OR appel = 0) AND (next_call_date IS NULL OR next_call_date <= '" . $today . "')";
$resultRappels = $conn->query($sqlRappels);
$total_rappels = 0;
if ($resultRappels && $rowRappels = $resultRappels->fetch_assoc()) {
    $total_rappels = intval($rowRappels['total_rappels']);
}
?>
<!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">Dashboard</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item active" aria-current="page">Dashboard</li>
            </ol>
          </div>

          <div class="row mb-3">
            <!-- Earnings (Monthly) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="liste_paiements_policy.php" style="text-decoration:none;">
              <div class="card border-left-primary shadow h-100 py-2" style="cursor:pointer;">
                <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">
                        Banque (Mois Actuel)</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800">
                        <?php echo number_format($banqueCurrent, 2, ',', ' '); ?> DH
                      </div>
                      <div class="mt-2 text-xs text-muted">
                        <span>
                          Depuis le mois dernier :
                          <?php
                            if ($banqueLast > 0) {
                              $sign = ($variation > 0) ? '+' : '';
                              $arrow = $variation > 0
                                ? '<span class="text-success mr-2"><i class="fas fa-arrow-up"></i></span>'
                                : ($variation < 0
                                  ? '<span class="text-danger mr-2"><i class="fas fa-arrow-down"></i></span>'
                                  : '');
                              $color = $variation > 0
                                ? 'text-success'
                                : ($variation < 0 ? 'text-danger' : 'text-muted');
                              echo $arrow . '<span class="' . $color . '">' . $sign . number_format($variation, 2) . '%</span>';
                            } else {
                              echo '<span class="text-muted">0.00%</span>';
                            }
                          ?>
                        </span>
                      </div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-university fa-2x text-danger"></i>
                    </div>
                  </div>
                </div>
              </div>
              </a>
            </div>
            <!-- Earnings (Annual) Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="liste_paiements_espece.php" style="text-decoration:none;">
              <div class="card h-100 border-left-secondary" style="cursor:pointer;">
                <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 mb-1">CAISSE (Mois Actuel)</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo number_format($caisseCurrent, 2, ',', ' '); ?> DH</div>
                      <div class="mt-2 mb-0 text-muted text-xs">
                        <span>
                          Depuis le mois dernier :
                          <?php
                            if ($caisseLast > 0) {
                              $sign = ($caisseVariation > 0) ? '+' : '';
                              $arrow = $caisseVariation > 0
                                ? '<span class="text-success mr-2"><i class="fas fa-arrow-up"></i></span>'
                                : ($caisseVariation < 0
                                  ? '<span class="text-danger mr-2"><i class="fas fa-arrow-down"></i></span>'
                                  : '');
                              $color = $caisseVariation > 0
                                ? 'text-success'
                                : ($caisseVariation < 0 ? 'text-danger' : 'text-muted');
                              echo $arrow . '<span class="' . $color . '">' . $sign . number_format($caisseVariation, 2) . '%</span>';
                            } else {
                              echo '<span class="text-muted">0.00%</span>';
                            }
                          ?>
                        </span>
                      </div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-cash-register fa-2x text-success"></i>
                    </div>
                  </div>
                </div>
              </div>
              </a>
            </div>
            <!-- New User Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="echeances_aujourdhui.php" style="text-decoration:none;">
              <div class="card h-100 border-left-info" style="cursor:pointer;">
                <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-uppercase mb-1">Échéances d'aujourd'hui</div>
                      <div class="h5 mb-0 mr-3 font-weight-bold text-gray-800"><?php echo $total_echeance_today; ?></div>
                    </div>
                    <div class="col-auto">
                      <i class="fas fa-calendar-day fa-2x text-info"></i>
                    </div>
                  </div>
                </div>
              </div>
              </a>
            </div>
            <!-- Rappels Card Example -->
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="appels.php" style="text-decoration:none;">
                <div class="card h-100 border-left-success shadow">
                  <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-uppercase mb-1">Rappels de Clients</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $total_rappels; ?></div>
                      </div>
                      <div class="col-auto">
                        <i class="fas fa-phone fa-2x text-success"></i>
                      </div>
                    </div>
                  </div>
                </div>
              </a>
            </div>

            <!-- Area Chart -->
            <div class="col-xl-8 col-lg-7">
              <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">Monthly Recap Report</h6>
                  <div class="dropdown no-arrow">
                    <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown"
                      aria-haspopup="true" aria-expanded="false">
                      <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                    </a>
                    <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in"
                      aria-labelledby="dropdownMenuLink">
                      <div class="dropdown-header"></div>
                      <a class="dropdown-item" href="#"></a>
                      <a class="dropdown-item" href="#"> </a>
                      <div class="dropdown-divider"></div>
                      <a class="dropdown-item" href="#"></a>
                    </div>
                  </div>
                </div>
                <div class="card-body">
                  <div class="chart-area">
                    <canvas id="myAreaChart"></canvas>
                  </div>
                </div>
              </div>
            </div>
            <!-- Pie Chart -->
            <div class="col-xl-4 col-lg-5">
              <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">Products Sold</h6>
                  <div class="dropdown no-arrow">
                    <a class="dropdown-toggle btn btn-primary btn-sm" href="#" role="button" id="dropdownMenuLink"
                      data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                      Month <i class="fas fa-chevron-down"></i>
                    </a>
                    <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in"
                      aria-labelledby="dropdownMenuLink">
                      <div class="dropdown-header">Select Periode</div>
                      <a class="dropdown-item" href="#">Today</a>
                      <a class="dropdown-item" href="#">Week</a>
                      <a class="dropdown-item active" href="#">Month</a>
                      <a class="dropdown-item" href="#">This Year</a>
                    </div>
                  </div>
                </div>
                <div class="card-body">
                  <div class="mb-3">
                    <div class="small text-gray-500">Oblong T-Shirt
                      <div class="small float-right"><b>600 of 800 Items</b></div>
                    </div>
                    <div class="progress" style="height: 12px;">
                      <div class="progress-bar bg-warning" role="progressbar" style="width: 80%" aria-valuenow="80"
                        aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                  </div>
                  <div class="mb-3">
                    <div class="small text-gray-500">Gundam 90'Editions
                      <div class="small float-right"><b>500 of 800 Items</b></div>
                    </div>
                    <div class="progress" style="height: 12px;">
                      <div class="progress-bar bg-success" role="progressbar" style="width: 70%" aria-valuenow="70"
                        aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                  </div>
                  <div class="mb-3">
                    <div class="small text-gray-500">Rounded Hat
                      <div class="small float-right"><b>455 of 800 Items</b></div>
                    </div>
                    <div class="progress" style="height: 12px;">
                      <div class="progress-bar bg-danger" role="progressbar" style="width: 55%" aria-valuenow="55"
                        aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                  </div>
                  <div class="mb-3">
                    <div class="small text-gray-500">Indomie Goreng
                      <div class="small float-right"><b>400 of 800 Items</b></div>
                    </div>
                    <div class="progress" style="height: 12px;">
                      <div class="progress-bar bg-info" role="progressbar" style="width: 50%" aria-valuenow="50"
                        aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                  </div>
                  <div class="mb-3">
                    <div class="small text-gray-500">Remote Control Car Racing
                      <div class="small float-right"><b>200 of 800 Items</b></div>
                    </div>
                    <div class="progress" style="height: 12px;">
                      <div class="progress-bar bg-success" role="progressbar" style="width: 30%" aria-valuenow="30"
                        aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                  </div>
                </div>
                <div class="card-footer text-center">
                  <a class="m-0 small text-primary card-link" href="#">View More <i
                      class="fas fa-chevron-right"></i></a>
                </div>
              </div>
            </div>
            <!-- Recent Logs -->
            <div class="col-12 mb-4">
              <div class="card">
                <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">Derniers Logs du Système</h6>
                  <a class="btn btn-primary btn-sm" href="view_logs.php">Voir Tous les Logs</a>
                </div>
                <div class="table-responsive">
                  <table class="table align-items-center table-flush">
                    <thead class="thead-light">
                      <tr>
                        <th>Date/Heure</th>
                        <th>Utilisateur</th>
                        <th>Action</th>
                      </tr>
                    </thead>
                    <tbody id="logs-table-body">
                      <!-- Les logs seront chargés ici via AJAX -->
                      <tr>
                        <td colspan="3" class="text-center text-muted">
                          <i class="fas fa-spinner fa-spin mr-2"></i>Chargement des logs...
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          <!--Row-->
        </div>
        <!---Container Fluid-->
      </div>
      <!-- Footer -->
     <?php include('includes/footer.php'); ?>
      <!-- Footer -->
    </div>
  </div>
  <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 src="vendor/chart.js/Chart.min.js"></script> 
  <script>
    // Configuration du graphique
    var ctx = document.getElementById("myAreaChart");
    var myLineChart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo $chart_labels; ?>, // Mois
            datasets: [{
                label: "Montants validés (DH)",
                lineTension: 0.3,
                backgroundColor: "rgba(78, 115, 223, 0.05)",
                borderColor: "rgba(78, 115, 223, 1)",
                pointRadius: 3,
                pointBackgroundColor: "rgba(78, 115, 223, 1)",
                pointBorderColor: "rgba(78, 115, 223, 1)",
                pointHoverRadius: 3,
                pointHoverBackgroundColor: "rgba(78, 115, 223, 1)",
                pointHoverBorderColor: "rgba(78, 115, 223, 1)",
                pointHitRadius: 10,
                pointBorderWidth: 2,
                data: <?php echo $chart_data; ?>, // Montants validés
            }],
        },
        options: {
            maintainAspectRatio: false,
            scales: {
                xAxes: [{
                    time: {
                        unit: 'month'
                    },
                    gridLines: {
                        display: false,
                        drawBorder: false
                    },
                    ticks: {
                        maxTicksLimit: 12
                    }
                }],
                yAxes: [{
                    ticks: {
                        maxTicksLimit: 5,
                        padding: 10,
                        // Inclure le format DH
                        callback: function(value, index, values) {
                            return value.toLocaleString() + ' DH';
                        }
                    },
                    gridLines: {
                        color: "rgb(234, 236, 244)",
                        zeroLineColor: "rgb(234, 236, 244)",
                        drawBorder: false,
                        borderDash: [2],
                        zeroLineBorderDash: [2]
                    }
                }],
            },
            legend: {
                display: false
            },
            tooltips: {
                backgroundColor: "rgb(255, 255, 255)",
                bodyFontColor: "#858796",
                titleMarginBottom: 10,
                titleFontColor: '#6e707e',
                titleFontSize: 14,
                borderColor: '#dddfeb',
                borderWidth: 1,
                xPadding: 15,
                yPadding: 15,
                displayColors: false,
                intersect: false,
                mode: 'index',
                caretPadding: 10,
                callbacks: {
                    label: function(tooltipItem, chart) {
                        var datasetLabel = chart.datasets[tooltipItem.datasetIndex].label || '';
                        return datasetLabel + ': ' + tooltipItem.yLabel.toLocaleString() + ' DH';
                    }
                }
            }
        }
    });
</script>

<script>
    // Fonction pour charger les logs en temps réel
    function loadRecentLogs() {
        $.ajax({
            url: 'get_recent_logs.php',
            method: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success && response.logs) {
                    updateLogsTable(response.logs);
                } else {
                    console.error('Erreur lors du chargement des logs:', response.error);
                }
            },
            error: function(xhr, status, error) {
                console.error('Erreur AJAX:', error);
                // En cas d'erreur, on réessaie dans 10 secondes
                setTimeout(loadRecentLogs, 10000);
            }
        });
    }
    
    // Fonction pour mettre à jour le tableau des logs
    function updateLogsTable(logs) {
        var tbody = $('#logs-table-body');
        var html = '';
        
        if (logs.length > 0) {
            logs.forEach(function(log) {
                var date = new Date(log.datetime);
                var dateStr = date.toLocaleDateString('fr-FR');
                var timeStr = date.toLocaleTimeString('fr-FR');
                
                // Afficher l'action complète
                var action = log.action;
                
                html += '<tr>';
                html += '<td>';
                html += '<small class="text-muted">';
                html += dateStr + '<br>' + timeStr;
                html += '</small>';
                html += '</td>';
                html += '<td>';
                html += '<span class="font-weight-bold">' + escapeHtml(log.user) + '</span>';
                html += '</td>';
                html += '<td>';
                html += '<span class="text-sm">' + escapeHtml(action) + '</span>';
                html += '</td>';
                html += '</tr>';
            });
        } else {
            html = '<tr><td colspan="3" class="text-center text-muted"><em>Aucun log trouvé</em></td></tr>';
        }
        
        tbody.html(html);
    }
    
    // Fonction pour échapper le HTML
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    
    // Charger les logs au démarrage
    $(document).ready(function() {
        loadRecentLogs();
        
        // Rafraîchir les logs toutes les 2 secondes
        setInterval(loadRecentLogs, 2000);
    });
</script>
</body>

</html>