<?php
session_start();

// 1. Clase para manejar recordatorios
class ReminderService {
    public static function generateMessage($clientData) {
        $formattedDate = date('d/m/Y', strtotime($clientData['expire_date']));
        return "¡Hola *{$clientData['name']}*! 👋\n\n" .
               "📢 *Recordatorio importante:*\n" .
               "Tu servicio está por vencer en *{$clientData['days_left']} día(s)*.\n" .
               "📅 *Fecha de vencimiento:* $formattedDate\n\n" .
               "Por favor, realiza tu renovación para evitar interrupciones. ¡Gracias! 😊\n" .
               "¿Necesitas ayuda? Estamos aquí para asistirte. 📞";
    }
}

// 2. Función para obtener clientes por vencer (con WhatsApp)
function getUpcomingClients() {
    $db = new SQLite3(__DIR__.'/api/.db.db');
    $today = date('Y-m-d');
    $threshold = date('Y-m-d', strtotime('+3 days'));

    $query = $db->prepare("
        SELECT id, cliente_nombre as name, cliente_whatsapp as whatsapp, expiracion as expire_date,
               julianday(expiracion) - julianday(:today) as days_left
        FROM playlist
        WHERE expiracion BETWEEN :today AND :threshold
          AND cliente_whatsapp IS NOT NULL
          AND cliente_whatsapp != ''
        ORDER BY expiracion ASC
    ");
    $query->bindValue(':today', $today, SQLITE3_TEXT);
    $query->bindValue(':threshold', $threshold, SQLITE3_TEXT);
    $result = $query->execute();

    $clients = [];
    while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $row['days_left'] = floor($row['days_left']);
        $clients[] = $row;
    }
    $db->close();
    return $clients;
}


// 3. Procesar acciones
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__.'/api/auto_user_cleanup.php';
    $control = new UserCleanupSystem();

    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'activate':
                $control->toggleActivation(true);
                $_SESSION['cleanup_message'] = '✅ Limpieza automática ACTIVADA';
                break;
            case 'deactivate':
                $control->toggleActivation(false);
                $_SESSION['cleanup_message'] = '⛔ Limpieza automática DESACTIVADA';
                break;
            case 'run_now':
                $count = $control->execute(true);
                $_SESSION['cleanup_message'] = "🧹 Limpieza manual completada. Eliminados: $count usuarios";
                break;
        }
    }

    if (isset($_POST['send_reminder']) && !empty($_POST['whatsapp'])) {
        $clientData = [
            'id' => $_POST['client_id'],
            'name' => $_POST['client_name'],
            'whatsapp' => $_POST['whatsapp'],
            'expire_date' => $_POST['expire_date'],
            'days_left' => $_POST['days_left']
        ];

        $message = ReminderService::generateMessage($clientData);
        $encodedMessage = urlencode($message);
        header("Location: https://wa.me/{$clientData['whatsapp']}?text=$encodedMessage");
        exit();
    }

    header('Location: '.$_SERVER['PHP_SELF']);
    exit();
}

// 4. Cargar estadísticas
$db1 = new SQLite3(__DIR__.'/api/.db.db');

$estadisticas = [
  'activos' => 0,
  'por_vencer' => 0,
  'vencidos' => 0
];

try {
    // Activos: expiracion > hoy + 3 días
   $estadisticas['activos'] = $db1->querySingle("SELECT COUNT(*) FROM playlist WHERE date(expiracion) >= date('now')");
    
    // Por vencer: expiracion entre hoy y hoy+3 días (inclusive)
    $estadisticas['por_vencer'] = $db1->querySingle("SELECT COUNT(*) FROM playlist WHERE date(expiracion) <= date('now', '+3 days') AND date(expiracion) >= date('now')");
    
    // Vencidos: expiracion < hoy
    $estadisticas['vencidos'] = $db1->querySingle("SELECT COUNT(*) FROM playlist WHERE date(expiracion) < date('now')");
} catch (Exception $e) {
    error_log("Error al calcular estadísticas: " . $e->getMessage());
}

$db1->close();

// 5. Incluir cabecera
include 'includes/header.php';

// 6. Mostrar mensajes
if (!empty($_SESSION['cleanup_message'])) {
    echo '<div class="alert alert-info alert-dismissible fade show">'
        .htmlspecialchars($_SESSION['cleanup_message']).
        '<button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>';
    unset($_SESSION['cleanup_message']);
}

// 7. Cargar estado de sistema
require_once __DIR__.'/api/auto_user_cleanup.php';
$control = new UserCleanupSystem();
$status = $control->getStatus();

// 8. Obtener clientes por vencer
$upcomingClients = getUpcomingClients();
?>

<!-- UI: Panel de Control -->

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Panel de Control Rgvip</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css" rel="stylesheet" />  
</head>
<body>
<!--<div class="container my-4">-->
  <!-- Botones tipo Dashboard -->
  <div class="row">
  <!-- Estado del Sistema (con modal) -->
  <div class="col-6 col-md-3 mb-3">
  <div class="card bg-success text-white text-center shadow-sm h-100">
    <div class="card-body d-flex flex-column justify-content-center align-items-center small">
      <i class="fas fa-shield-alt fa-2x mb-2"></i>
      <h5 class="card-title mb-1">Limpieza Sistema</h5>
      <span class="badge badge-light text-success mb-2"><?= $status['active'] ? 'ACTIVO' : 'INACTIVO' ?></span>
      <p class="mb-1"><i class="fas fa-history"></i> <small>Última: <?= $status['last_run'] ?></small></p>
      <p class="mb-2"><i class="fas fa-clock"></i> <small>Próxima: <?= $status['next_run'] ?></small></p>
      <button type="button" class="btn btn-light btn-sm mt-auto" data-toggle="modal" data-target="#accionesModal">
        <i class="fas fa-cogs"></i> Acciones
      </button>
    </div>
  </div>
</div>
  <!-- Usuarios Activos -->
  <div class="col-6 col-md-3 mb-3">
    <div class="card bg-success text-white text-center shadow-sm h-100">
      <div class="card-body d-flex flex-column justify-content-center align-items-center">
        <i class="fas fa-user-check fa-2x mb-2"></i>
        <h5 class="card-title mb-1">Activos</h5>
        <h3 class="font-weight-bold"><?= $estadisticas['activos'] ?></h3>
      </div>
    </div>
  </div>
  <!-- Por Vencer -->
  <div class="col-6 col-md-3 mb-3">
    <div class="card bg-warning text-dark text-center shadow-sm h-100">
      <div class="card-body d-flex flex-column justify-content-center align-items-center">
        <i class="fas fa-user-clock fa-2x mb-2"></i>
        <h5 class="card-title mb-1">Por Vencer</h5>
        <h3 class="font-weight-bold"><?= $estadisticas['por_vencer'] ?></h3>
      </div>
    </div>
  </div>
  <!-- Vencidos -->
  <div class="col-6 col-md-3 mb-3">
    <div class="card bg-danger text-white text-center shadow-sm h-100">
      <div class="card-body d-flex flex-column justify-content-center align-items-center">
        <i class="fas fa-user-times fa-2x mb-2"></i>
        <h5 class="card-title mb-1">Vencidos</h5>
        <h3 class="font-weight-bold"><?= $estadisticas['vencidos'] ?></h3>
      </div>
    </div>
  </div>
</div>
  <!-- Clientes por Vencer -->
  <div class="card shadow-sm border-left-warning mb-3">
    <div class="card-header bg-warning text-dark py-2">
      <i class="fas fa-bell"></i> Clientes por Vencer (Aquí podrás enviar recordatorios de pago)
    </div>
    <div class="card-body small">
      <?php if (empty($upcomingClients)): ?>
        <div class="alert alert-success mb-0">
          <i class="fas fa-check-circle"></i> No hay clientes por vencer en los próximos días.
        </div>
      <?php else: ?>
        <div class="table-responsive">
          <table class="table table-dark table-hover table-striped table-sm mb-0">
            <thead class="thead-light">
              <tr>
                <th>Nombre</th>
                <th>Vencimiento</th>
                <th>Días Restantes</th>
                <th>Acción</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($upcomingClients as $client): ?>
                <tr>
                  <td><?= htmlspecialchars($client['name']) ?></td>
                  <td><?= date('d/m/Y', strtotime($client['expire_date'])) ?></td>
                  <td>
                    <span class="badge badge-<?= 
  $client['days_left'] < 0 ? 'danger' :   // ya vencido
  ($client['days_left'] <= 3 ? 'warning' : 'info') 
?>">
  <?= max($client['days_left'], 0) ?> día(s)
</span>

                  </td>
                  <td>
                    <form method="post" class="d-inline">
                      <input type="hidden" name="client_id" value="<?= $client['id'] ?>">
                      <input type="hidden" name="whatsapp" value="<?= $client['whatsapp'] ?>">
                      <input type="hidden" name="client_name" value="<?= htmlspecialchars($client['name']) ?>">
                      <input type="hidden" name="expire_date" value="<?= $client['expire_date'] ?>">
                      <input type="hidden" name="days_left" value="<?= $client['days_left'] ?>">
                      <button type="submit" name="send_reminder" class="btn btn-sm btn-outline-warning">
                        <i class="fa fa-bell"></i> Enviar Recordatorio
                      </button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>
<!-- Modal de Acciones -->
<div class="modal fade" id="accionesModal" tabindex="-1" role="dialog" aria-labelledby="accionesModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content border-left-primary">
      <div class="modal-header bg-primary text-white py-2">
        <h5 class="modal-title" id="accionesModalLabel"><i class="fas fa-cogs"></i> Acciones Disponibles</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Cerrar">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body small">
        <form method="post">
          <button type="submit" name="action" value="activate" class="btn btn-success btn-block btn-sm mb-2 <?= $status['active'] ? 'disabled' : '' ?>">
            <i class="fas fa-toggle-on"></i> Activar Automático
          </button>
          <button type="submit" name="action" value="deactivate" class="btn btn-danger btn-block btn-sm mb-2 <?= !$status['active'] ? 'disabled' : '' ?>">
            <i class="fas fa-toggle-off"></i> Desactivar Automático
          </button>
          <button type="submit" name="action" value="run_now" class="btn btn-info btn-block btn-sm">
            <i class="fas fa-play-circle"></i> Ejecutar Limpieza Manual
          </button>
        </form>
        <hr class="my-2">
        <small class="text-muted">
          ⚙️ El sistema elimina usuarios vencidos hace más de <strong><?= UserCleanupSystem::DAYS_THRESHOLD ?></strong> días, verificando cada 24 horas.
        </small>
      </div>
    </div>
  </div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
<?php include 'includes/footer.php'; ?>
