<?php
class UserCleanupSystem {
    const CONFIG_FILE = __DIR__.'/user_cleanup_config.json';
    const DAYS_THRESHOLD = 5;
    const AUTO_RUN_INTERVAL = 86400; // 24 horas en segundos
    
    protected $db;
    protected $config;
    
    public function __construct() {
        $this->loadConfig();
        $this->db = new SQLite3(__DIR__.'/.db.db');
        $this->db->exec('PRAGMA journal_mode = WAL');
        $this->db->exec('PRAGMA foreign_keys = ON'); // Habilitar claves foráneas si es necesario
        
        // Verificar ejecución automática al instanciar
        $this->checkAutoExecution();
    }
    
    protected function checkAutoExecution() {
        if (!$this->config['active']) {
            return;
        }
        
        $now = time();
        $lastRun = $this->config['last_auto_run'] ?? 0;
        
        // Ejecutar si ha pasado el intervalo configurado
        if (($now - $lastRun) >= self::AUTO_RUN_INTERVAL) {
            $this->execute(true); // Ejecución automática
            $this->config['last_auto_run'] = $now;
            $this->saveConfig();
        }
    }
    
    public function execute($isAuto = false, $days = null) {
    $thresholdDays = $days ?? self::DAYS_THRESHOLD;
    $thresholdDate = date('Y-m-d', strtotime('-'.$thresholdDays.' days'));
    $count = 0;

    try {
        $this->db->exec('BEGIN TRANSACTION');

        // 1. Obtener MACs de usuarios vencidos
        $stmt = $this->db->prepare(
            "SELECT mac_address FROM playlist WHERE expiracion <= :threshold"
        );
        $stmt->bindValue(':threshold', $thresholdDate, SQLITE3_TEXT);
        $result = $stmt->execute();

        $macs = [];
        while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
            $macs[] = $row['mac_address'];
        }

        // 2. Eliminar usuarios vencidos directamente en `playlist`
        $stmt = $this->db->prepare(
            "DELETE FROM playlist WHERE expiracion <= :threshold"
        );
        $stmt->bindValue(':threshold', $thresholdDate, SQLITE3_TEXT);
        $stmt->execute();

        $count = $this->db->changes();

        $this->db->exec('COMMIT');

        // Log
        $logType = $isAuto ? 'AUTO' : 'MANUAL';
        $logMessage = sprintf(
            "[UserCleanup][%s] Eliminados %d usuarios vencidos (MACs: %s) con %d días de vencimiento - %s",
            $logType,
            $count,
            implode(', ', $macs),
            $thresholdDays,
            date('Y-m-d H:i:s')
        );
        error_log($logMessage);

    } catch (Exception $e) {
        $this->db->exec('ROLLBACK');
        error_log("[UserCleanup][ERROR] ".$e->getMessage());
        throw $e;
    }

    return $count;
}


    protected function loadConfig() {
        if (!file_exists(self::CONFIG_FILE)) {
            $this->config = [
                'active' => false,
                'last_auto_run' => 0,
                'notify_email' => null // Opcional: añadir email para notificaciones
            ];
            $this->saveConfig();
        } else {
            $this->config = json_decode(file_get_contents(self::CONFIG_FILE), true);
        }
    }
    
    protected function saveConfig() {
        file_put_contents(self::CONFIG_FILE, json_encode($this->config, JSON_PRETTY_PRINT));
    }
    
    public function toggleActivation($status) {
        $this->config['active'] = (bool)$status;
        $this->saveConfig();
        return $this;
    }
    
    public function getStatus() {
        return [
            'active' => $this->config['active'],
            'last_run' => $this->config['last_auto_run'] ? 
                          date('Y-m-d H:i:s', $this->config['last_auto_run']) : 
                          'Nunca',
            'next_run' => $this->config['active'] ? 
                          date('Y-m-d H:i:s', $this->config['last_auto_run'] + self::AUTO_RUN_INTERVAL) : 
                          'No programado',
            'threshold_days' => self::DAYS_THRESHOLD
        ];
    }
    
    public function setNotificationEmail($email) {
        if ($email && filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $this->config['notify_email'] = $email;
            $this->saveConfig();
        }
        return $this;
    }
    
    public function __destruct() {
        if ($this->db) $this->db->close();
    }
}