<?php
session_start();
include 'config/connexion.php';

// Auth check
if (empty($_SESSION['user_email'])) {
    header('Location: login.php');
    exit;
}

// Marquer appels paiement comme traités / reporter
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $numero_police_raw = $_POST['numero_police'] ?? '';
    $user_name = $_SESSION['user_name'] ?? 'Utilisateur';
    $policies = array_filter(array_map('trim', explode(',', $numero_police_raw)));
    $policies = array_unique(array_values(array_filter($policies, function($p){return preg_match('/^[A-Za-z0-9_-]+$/',$p);})));
    if ($action && $policies) {
        include 'includes/simple_log.php';
        $placeholders = implode(',', array_fill(0, count($policies), '?'));
    if ($action === 'appel_passe') {
      // Marquer l'appel comme effectué : on retire la date next_paiement (NULL) pour ne plus afficher aujourd'hui
      try {
        $chkNP = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
        if(!$chkNP || $chkNP->num_rows===0){ $conn->query("ALTER TABLE policy_table ADD COLUMN next_paiement DATE NULL"); }
        if($chkNP) $chkNP->close();
      } catch(Throwable $e){}
      $sql = "UPDATE policy_table SET next_paiement = NULL WHERE n_policy IN ($placeholders)";
      $stmt = $conn->prepare($sql);
      $stmt->bind_param(str_repeat('s', count($policies)), ...$policies);
      $stmt->execute();
      $affected = $stmt->affected_rows; $stmt->close();
      logMessage("$user_name a marqué l'appel de paiement comme passé (next_paiement NULL) pour ".count($policies)." police(s): ".implode(',', $policies));
      $_SESSION['success_message'] = "Appel paiement passé (".count($policies)." polices) - dates effacées: $affected";
    } elseif ($action === 'reporter') {
      // Reporter à demain: mettre à jour next_paiement = demain et remettre appel_paiement = 0
      $demain = date('Y-m-d', strtotime('+1 day'));
      // S'assurer que la colonne next_paiement existe (devrait déjà exister)
      try {
        $chk3 = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
        if(!$chk3 || $chk3->num_rows===0){ $conn->query("ALTER TABLE policy_table ADD COLUMN next_paiement DATE NULL"); }
        if($chk3) $chk3->close();
      } catch(Throwable $e){}
      $sql = "UPDATE policy_table SET next_paiement = ? WHERE n_policy IN ($placeholders)";
      $stmt = $conn->prepare($sql);
      $types = 's'.str_repeat('s', count($policies));
      $params = array_merge([$demain], $policies);
      $stmt->bind_param($types, ...$params);
      $stmt->execute();
      $affected = $stmt->affected_rows; $stmt->close();
      logMessage("$user_name a reporté l'appel de paiement (".count($policies)." polices) à demain ($demain): ".implode(',', $policies));
      $_SESSION['success_message'] = "Appel paiement reporté à demain ($demain) (".count($policies)." polices) - mises à jour: $affected";
    } elseif ($action === 'reporter_custom') {
      // Reporter à une date personnalisée (champ custom_date)
      $custom_date = $_POST['custom_date'] ?? '';
      $valid = false;
      if(preg_match('/^\d{4}-\d{2}-\d{2}$/', $custom_date)) {
        $ts = strtotime($custom_date);
        if($ts !== false) { $valid = true; }
      }
      if(!$valid){
        $_SESSION['error_message'] = "Date personnalisée invalide.";
        header('Location: appels_paiements_aujourdhui.php');
        exit;
      }
      try {
        $chk4 = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
        if(!$chk4 || $chk4->num_rows===0){ $conn->query("ALTER TABLE policy_table ADD COLUMN next_paiement DATE NULL"); }
        if($chk4) $chk4->close();
      } catch(Throwable $e){}
            $sql = "UPDATE policy_table SET next_paiement = ? WHERE n_policy IN ($placeholders)";
      $stmt = $conn->prepare($sql);
      $types = 's'.str_repeat('s', count($policies));
      $params = array_merge([$custom_date], $policies);
      $stmt->bind_param($types, ...$params);
      $stmt->execute();
      $affected = $stmt->affected_rows; $stmt->close();
      logMessage("$user_name a reporté l'appel de paiement (".count($policies)." polices) au $custom_date: ".implode(',', $policies));
      $_SESSION['success_message'] = "Appel paiement reporté au $custom_date (".count($policies)." polices) - mises à jour: $affected";
        }
        header('Location: appels_paiements_aujourdhui.php');
        exit;
    }
}

$today = date('Y-m-d');
// Construire condition colonne next_paiement
$policies = [];
try {
    $chkCol = $conn->query("SHOW COLUMNS FROM policy_table LIKE 'next_paiement'");
    if($chkCol && $chkCol->num_rows>0){
        $query = "SELECT p.n_policy, p.client_cin, p.next_paiement, p.total_reste, p.montant_to_paie, p.montant_paye, c.client_name, c.client_phone, c.client_company
                  FROM policy_table p LEFT JOIN clients_table c ON p.client_cin = c.client_cin
                  WHERE p.next_paiement = ? AND (p.total_reste > 0.009)"; // reste > 0
        $stmt = $conn->prepare($query);
        $stmt->bind_param('s', $today);
        $stmt->execute();
        $res = $stmt->get_result();
        $policies = $res->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
    if($chkCol) $chkCol->close();
} catch(Throwable $e) { /* silencieux */ }

// Regrouper par client
$clients = [];
foreach($policies as $p){
    $cin = $p['client_cin'] ?? '';
    if(!isset($clients[$cin])){
        $clients[$cin] = [
            'client_name' => $p['client_name'],
            'client_phone' => $p['client_phone'],
            'client_company' => $p['client_company'],
            'policies' => []
        ];
    }
    $clients[$cin]['policies'][] = $p;
}
$clientsCount = count($clients);
?>
<!DOCTYPE html>
<html lang="fr">
<head>
  <?php include 'includes/head.php'; ?>
  <style>
    .notification-card {
      border-left: 6px solid #6f42c1;
      background: linear-gradient(90deg, #f8f3ff 0%, #efe6ff 100%);
      transition: all .3s;
    }
    .notification-card:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 25px rgba(111,66,193,0.15);
    }
    .badge-pay {
      background: #6f42c1;
      color: #fff;
      font-weight: 600;
    }
    .badge-overdue {
      background: #5a32a3;
      color: #fff;
      font-weight: 600;
      margin-left: 10px;
    }
    .header-bar {
      background: linear-gradient(45deg,#6f42c1,#8e5ad9);
      color: #fff;
      border-radius: 8px;
      padding: 18px 24px;
      margin-bottom: 30px;
      box-shadow: 0 2px 8px rgba(111,66,193,0.25);
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .header-bar .fa {
      font-size: 2.2rem;
      margin-right: 18px;
    }
    .action-buttons .btn {
      border-radius: 20px;
      font-weight: 600;
      text-transform: uppercase;
      letter-spacing: 0.5px;
      transition: all 0.3s ease;
    }
    .action-buttons .btn-success {
      background: #27ae60;
      border: none;
    }
    .action-buttons .btn-warning {
      background: #f39c12;
      border: none;
      color: #fff;
    }
  </style>
</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="header-bar mb-4">
          <div>
            <i class="fas fa-money-bill-wave" style="filter:drop-shadow(0 2px 2px rgba(0,0,0,0.15));"></i>
            <span style="font-size:1.5rem;font-weight:700;">Appels Paiements à Relancer</span>
            <span class="ml-3" style="font-size:1rem;font-weight:400;opacity:.85;">(Prochains paiements attendus aujourd'hui ou en retard)</span>
          </div>
          <div>
            <span class="badge badge-pay p-2">Clients à relancer : <?php echo $clientsCount; ?></span>
          </div>
        </div>
        <?php if(isset($_SESSION['success_message'])): ?>
          <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle mr-2"></i><?php echo htmlspecialchars($_SESSION['success_message']); unset($_SESSION['success_message']); ?>
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
          </div>
        <?php endif; ?>
        <?php if(isset($_SESSION['error_message'])): ?>
          <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle mr-2"></i><?php echo htmlspecialchars($_SESSION['error_message']); unset($_SESSION['error_message']); ?>
            <button type="button" class="close" data-dismiss="alert"><span>&times;</span></button>
          </div>
        <?php endif; ?>
        <div class="row mb-4">
          <div class="col-lg-12">
            <div class="card border-left-info 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-info text-uppercase mb-1">Clients à appeler aujourd'hui</div>
                    <div class="h5 mb-0 font-weight-bold text-gray-800"><?php echo $clientsCount; ?> client(s)</div>
                  </div>
                  <div class="col-auto"><i class="fas fa-coins fa-2x text-info"></i></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-lg-12">
            <?php if(empty($clients)): ?>
              <div class="card shadow"><div class="card-body text-center py-5"><i class="fas fa-check-circle fa-3x text-success mb-3"></i><h4 class="text-success">Aucun appel paiement à relancer</h4><p class="text-muted">Tout est à jour.</p></div></div>
            <?php else: ?>
              <?php $__i = 0; foreach($clients as $cin=>$client): $__i++; ?>
                <div class="card notification-card shadow mb-4">
                  <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background:#f3eaff;">
                    <h6 class="m-0 font-weight-bold" style="color:#5a32a3;"><i class="fas fa-user mr-2"></i><?php echo htmlspecialchars($client['client_name'] ?? 'N/A'); ?><?php if(!empty($client['client_company'])): ?><small class="text-muted d-block"><?php echo htmlspecialchars($client['client_company']); ?></small><?php endif; ?></h6>
                    <span class="badge badge-pay badge-pill p-2"><i class="fas fa-money-bill-wave mr-1"></i>À relancer</span>
                  </div>
                  <div class="card-body">
                    <div class="row">
                      <div class="col-md-8">
                        <p class="mb-2"><strong><i class="fas fa-phone text-primary mr-2"></i>Téléphone :</strong><br>
                          <a href="tel:<?php echo htmlspecialchars($client['client_phone'] ?? ''); ?>" class="text-decoration-none btn btn-primary btn-sm font-weight-bold" style="font-size:1.05rem; padding:8px 15px; background:#6f42c1; border:none;">
                            <i class="fas fa-phone mr-2"></i><?php echo htmlspecialchars($client['client_phone'] ?? 'Non renseigné'); ?>
                          </a>
                        </p>
                        <div class="mb-2">
                          <strong>Polices concernées :</strong>
                          <ul class="list-group mb-2">
                            <?php foreach($client['policies'] as $policy): ?>
                              <li class="list-group-item d-flex justify-content-between align-items-center">
                                <div>
                                  <span class="font-weight-bold">Police N° <?php echo htmlspecialchars($policy['n_policy']); ?></span>
                                  <?php
                                    $isOverdue = false;
                                    if (!empty($policy['next_paiement'])) {
                                      $isOverdue = strtotime($policy['next_paiement']) < strtotime(date('Y-m-d'));
                                    }
                                  ?>
                                  <?php if($isOverdue): ?><span class="badge badge-overdue">En retard</span><?php endif; ?>
                                  <br>
                                  <small>
                                    <?php echo 'Montant à payer : '.number_format($policy['montant_to_paie'] ?? 0,2,',',' ').' DH'; ?> | 
                                    <?php echo 'Payé : '.number_format($policy['montant_paye'] ?? 0,2,',',' ').' DH'; ?> | 
                                    <?php echo 'Reste : '.number_format($policy['total_reste'] ?? 0,2,',',' ').' DH'; ?>
                                    <?php if(!empty($policy['next_paiement'])): ?> | <span style="color:#5a32a3;">Prochain paiement : <?php echo date('d/m/Y', strtotime($policy['next_paiement'])); ?></span><?php endif; ?>
                                  </small>
                                </div>
                              </li>
                            <?php endforeach; ?>
                          </ul>
                        </div>
                      </div>
                      <div class="col-md-4">
                        <div class="action-buttons">
                          <h6 class="font-weight-bold mb-3">Actions :</h6>
                          <form method="POST" class="d-inline confirm-action" data-confirm-message="Confirmer : appel passé ?">
                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($client['policies'], 'n_policy'))); ?>">
                            <input type="hidden" name="action" value="appel_passe">
                            <button type="submit" class="btn btn-success btn-sm btn-block mb-2"><i class="fas fa-phone mr-1"></i> Appel Passé</button>
                          </form>
                          <form method="POST" class="d-inline mb-2 confirm-action" data-confirm-message="Confirmer : reporter à demain ?">
                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($client['policies'], 'n_policy'))); ?>">
                            <input type="hidden" name="action" value="reporter">
                            <button type="submit" class="btn btn-warning btn-sm btn-block"><i class="fas fa-clock mr-1"></i> Reporter à demain</button>
                          </form><br>
                          <button type="button" class="btn btn-secondary btn-sm btn-block mb-2" onclick="toggleCustomDate('customDate_<?php echo $__i; ?>')"><i class="fas fa-calendar-plus mr-1"></i> Fixer une date</button>
                          <form id="customDate_<?php echo $__i; ?>" method="POST" class="border rounded p-2 mb-2 confirm-action" data-confirm-message="Confirmer : reprogrammer à cette date ?" style="display:none;background:#f9f6ff;" onsubmit="return this.custom_date.value ? true : (alert('Choisir une date'), false);">
                            <input type="hidden" name="numero_police" value="<?php echo htmlspecialchars(implode(',', array_column($client['policies'], 'n_policy'))); ?>">
                            <input type="hidden" name="action" value="reporter_custom">
                            <label class="small font-weight-bold mb-1" style="color:#5a32a3;">Nouvelle date de paiement</label>
                            <div class="input-group input-group-sm mb-2">
                              <input type="date" name="custom_date" class="form-control" min="<?php echo date('Y-m-d'); ?>" value="" required>
                              <div class="input-group-append">
                                <button class="btn btn-warning" type="submit" title="Valider"><i class="fas fa-check"></i></button>
                                <button class="btn btn-outline-secondary" type="button" title="Annuler" onclick="toggleCustomDate('customDate_<?php echo $__i; ?>')"><i class="fas fa-times"></i></button>
                              </div>
                            </div>
                            <small class="text-muted">Choisir une date future pour reprogrammer l'appel.</small>
                          </form>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </div>
        </div>
      </div>
    </div>
    <?php include 'includes/footer.php'; ?>
  </div>
</div>
<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>
function toggleCustomDate(id){
  var el=document.getElementById(id);
  if(!el) return;
  if(el.style.display==='none' || el.style.display===''){ el.style.display='block'; }
  else { el.style.display='none'; }
}
// Confirmation modal logic
let pendingForm = null;
document.addEventListener('DOMContentLoaded', function(){
  const forms = document.querySelectorAll('form.confirm-action');
  forms.forEach(f => {
    f.addEventListener('submit', function(e){
      if(f.dataset.confirmed === '1') { return; }
      e.preventDefault();
      pendingForm = f;
      const msg = f.getAttribute('data-confirm-message') || 'Confirmer cette action ?';
      document.getElementById('confirmModalMessage').textContent = msg;
      $('#confirmActionModal').modal('show');
    });
  });
  document.getElementById('confirmModalValidate').addEventListener('click', function(){
    if(pendingForm){
      pendingForm.dataset.confirmed = '1';
      pendingForm.submit();
    }
  });
});
</script>
<!-- Confirmation Modal -->
<div class="modal fade" id="confirmActionModal" tabindex="-1" role="dialog" aria-labelledby="confirmActionModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header" style="background:#6f42c1; color:#fff;">
        <h5 class="modal-title" id="confirmActionModalLabel"><i class="fas fa-question-circle mr-2"></i>Confirmation</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
        <p id="confirmModalMessage" class="mb-0">Confirmer cette action ?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Annuler</button>
        <button type="button" class="btn btn-primary" id="confirmModalValidate">Valider</button>
      </div>
    </div>
  </div>
</div>
</body>
</html>
