<?php
session_start();
// Rediriger vers login si non connecté
if (empty($_SESSION['user_email']) && empty($_SESSION['user_name'])) { header('Location: login.php'); exit; }
include 'config/connexion.php';
if (empty($COMPANY_DB_AVAILABLE) || !($conn instanceof mysqli)) { header('Location: login.php'); exit; }

$user_role = $_SESSION['user_role'] ?? '';
// Optionnel: empêcher l'accès aux admins/super admin si vous voulez une vue uniquement agents
// if (in_array(strtolower($user_role), ['super admin','admin'])) { header('Location: dashboard.php'); exit; }

// Statistiques simples pour l'agent (limitées)
// Récupération nombre de polices actives assignées à l'agent s'il y a une colonne owner_email / assigned_to (à adapter)
$agentEmail = $_SESSION['user_email'];
$policesCount = 0; $rappelsCount=0; $echeancesToday=0; $appelsCount=0;
 $appelsPaiementsToday=0;
try {
  if ($conn instanceof mysqli) {
    // Adapter ces requêtes si la structure diffère (assumptions raisonnables)
  if ($res = $conn->query("SELECT COUNT(*) c FROM policy_table")) { $row=$res->fetch_assoc(); $policesCount=(int)$row['c']; }
  // Nombre de clients à appeler (même logique que topbar: end_date sous 7 jours, pas encore appelés)
  $dateLimit = date('Y-m-d', strtotime('+7 days'));
  $sqlApp = "SELECT COUNT(DISTINCT client_cin) AS nb FROM policy_table WHERE client_cin IS NOT NULL AND end_date <= '".$conn->real_escape_string($dateLimit)."' AND end_date >= CURDATE() AND (appel IS NULL OR appel = 0) AND (next_call_date IS NULL OR next_call_date <= CURDATE())";
  if ($res = $conn->query($sqlApp)) { $row=$res->fetch_assoc(); $appelsCount = (int)$row['nb']; }
  $today = date('Y-m-d');
    // Déterminer l'identité agent comme dans topbar (user_name > first/last > email)
    $agentIdent = null;
    if (!empty($_SESSION['user_name'])) { $agentIdent = $_SESSION['user_name']; }
    elseif (!empty($_SESSION['first_name']) || !empty($_SESSION['last_name'])) { $agentIdent = trim(($_SESSION['first_name'] ?? '').' '.($_SESSION['last_name'] ?? '')); }
    elseif (!empty($_SESSION['user_email'])) { $agentIdent = $_SESSION['user_email']; }
    // Rappels (tâches) du jour depuis rappels_table pour cet agent
    if ($agentIdent) {
      $stmtRJ = $conn->prepare("SELECT COUNT(*) c FROM rappels_table WHERE agent=? AND date_rappel=?");
      if($stmtRJ){ $stmtRJ->bind_param('ss',$agentIdent,$today); $stmtRJ->execute(); $resRJ=$stmtRJ->get_result(); if($resRJ){ $row=$resRJ->fetch_assoc(); $rappelsCount = (int)($row['c']??0); } $stmtRJ->close(); }
    }
    if ($res = $conn->query("SELECT COUNT(*) c FROM receipts_table WHERE paiement_statut=0 AND echeance_date='".$conn->real_escape_string($today)."'")) { $row=$res->fetch_assoc(); $echeancesToday=(int)$row['c']; }
    // Appels paiements aujourd'hui (next_paiement = today & reste > 0)
    if ($colNP = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'")) {
      if ($colNP->num_rows>0) {
        $stmtAPT = $conn->prepare("SELECT COUNT(DISTINCT client_cin) AS nb FROM policy_table WHERE next_paiement = ? AND total_reste > 0.009");
        $stmtAPT->bind_param('s',$today);
        $stmtAPT->execute();
        $resAPT = $stmtAPT->get_result();
        $rowAPT = $resAPT? $resAPT->fetch_assoc(): null;
        $appelsPaiementsToday = $rowAPT && isset($rowAPT['nb']) ? (int)$rowAPT['nb'] : 0;
        $stmtAPT->close();
      }
      $colNP->close();
    }
  }
} catch(Throwable $e) { /* silencieux */ }
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <?php include 'includes/head.php'; ?>
</head>
<body id="page-top">
  <div id="wrapper">
    <?php include 'includes/sidebar.php'; ?>
    <div id="content-wrapper" class="d-flex flex-column">
      <div id="content">
        <?php include 'includes/topbar.php'; ?>
        <div class="container-fluid" id="container-wrapper">
          <div class="d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h4 mb-0 text-gray-800">Dashboard Agent</h1>
            <ol class="breadcrumb">
              <li class="breadcrumb-item"><a href="./">Accueil</a></li>
              <li class="breadcrumb-item active" aria-current="page">Dashboard Agent</li>
            </ol>
          </div>
          <div class="row mb-4">
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="appels.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">Appels Clients (7 jours)</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $appelsCount; ?></div>
                    </div>
                    <div class="col-auto"><i class="fas fa-phone-volume fa-2x text-primary"></i></div>
                  </div>
                </div>
              </div>
              </a>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="appels_paiements_aujourdhui.php" style="text-decoration:none;">
                <div class="card border-left-info 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-info text-uppercase mb-1">Appels Paiements Aujourd'hui</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $appelsPaiementsToday; ?></div>
                      </div>
                      <div class="col-auto"><i class="fas fa-coins fa-2x text-info"></i></div>
                    </div>
                  </div>
                </div>
              </a>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="rappels_jour.php" style="text-decoration:none;">
                <div class="card border-left-warning shadow h-100 py-2 hover-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-warning text-uppercase mb-1">Tâches / Rappels Aujourd'hui</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $rappelsCount; ?></div>
                      </div>
                      <div class="col-auto"><i class="fas fa-bell fa-2x text-warning"></i></div>
                    </div>
                  </div>
                </div>
              </a>
            </div>
            <div class="col-xl-3 col-md-6 mb-4">
              <a href="echeances_aujourdhui.php" style="text-decoration:none;">
              <div class="card border-left-info 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-info text-uppercase mb-1">Échéances Paiements Aujourd'hui</div>
                      <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $echeancesToday; ?></div>
                    </div>
                    <div class="col-auto"><i class="fas fa-calendar-day fa-2x text-info"></i></div>
                  </div>
                </div>
              </div>
              </a>
            </div>
          </div>

          <div class="row">
            <div class="col-lg-12 mb-4">
              <div class="card shadow">
                <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">Activité Récente (Logs)</h6>
                  <a class="btn btn-sm btn-primary" href="view_logs.php">Voir Tous</a>
                </div>
                <div class="table-responsive">
                  <table class="table align-items-center table-flush mb-0">
                    <thead class="thead-light">
                      <tr><th>Date/Heure</th><th>Utilisateur</th><th>Action</th></tr>
                    </thead>
                    <tbody id="logs-table-body">
                      <tr><td colspan="3" class="text-center text-muted"><i class="fas fa-spinner fa-spin mr-2"></i>Chargement...</td></tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <?php include 'includes/footer.php'; ?>
    </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>
    function loadRecentLogs(){
      $.getJSON('get_recent_logs.php', function(resp){
        if(resp.success && resp.logs){
          var html='';
          resp.logs.forEach(function(log){
            var d=new Date(log.datetime); var ds=d.toLocaleDateString('fr-FR'); var ts=d.toLocaleTimeString('fr-FR');
            html+='<tr>'+
              '<td><small class="text-muted">'+ds+'<br>'+ts+'</small></td>'+
              '<td><span class="font-weight-bold">'+escapeHtml(log.user)+'</span></td>'+
              '<td><span>'+escapeHtml(log.action)+'</span></td>'+
            '</tr>';
          });
          if(!html) html='<tr><td colspan="3" class="text-center text-muted"><em>Aucun log</em></td></tr>';
          $('#logs-table-body').html(html);
        }
      });
    }
    function escapeHtml(t){return t? t.replace(/[&<>"']/g,function(c){return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;','\'':'&#039;'}[c];}):'';}
    $(function(){ loadRecentLogs(); setInterval(loadRecentLogs,4000); });
  </script>
</body>
</html>
