<?php
/**
 * OTP Cleanup Cron Job
 * - Expires OTPs past their expiry time
 * - Deletes unverified users (if auto-delete is enabled)
 * 
 * Add to your cron jobs:
 * wget --spider -O - https://yourdomain.com/automations/cronjobs/otp_cleanup.php
 */

define('BASEPATH', TRUE);

$config = require __DIR__ . '/../../app/config.php';

try {
    $conn = new PDO(
        "mysql:host=" . $config["db"]["host"] . ";dbname=" . $config["db"]["name"] . ";charset=" . $config["db"]["charset"] . ";",
        $config["db"]["user"],
        $config["db"]["pass"]
    );
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("DB Error: " . $e->getMessage());
}

// Get settings
$settingsStmt = $conn->prepare("SELECT * FROM settings WHERE id = 1");
$settingsStmt->execute();
$settings = $settingsStmt->fetch(PDO::FETCH_ASSOC);

// 1. Expire old OTPs
$expireOtps = $conn->prepare("UPDATE clients SET otp_status = 'expired', otp_code = NULL WHERE otp_status = 'pending' AND otp_expiry < NOW()");
$expireOtps->execute();
$expiredCount = $expireOtps->rowCount();

// 2. Auto-delete unverified users (if enabled)
$deletedCount = 0;
if (($settings["otp_auto_delete_enabled"] ?? 0) == 1) {
    $hours = $settings["otp_auto_delete_hours"] ?? 48;
    
    $deleteStmt = $conn->prepare("DELETE FROM clients WHERE email_verified = 0 AND register_date < DATE_SUB(NOW(), INTERVAL :hours HOUR)");
    $deleteStmt->execute(["hours" => $hours]);
    $deletedCount = $deleteStmt->rowCount();
}

// 3. Reset resend counters (older than 1 hour)
$resetResend = $conn->prepare("UPDATE clients SET otp_resend_count = 0, otp_resend_reset_at = NULL WHERE otp_resend_reset_at IS NOT NULL AND otp_resend_reset_at < NOW()");
$resetResend->execute();

echo json_encode([
    "status" => "success",
    "expired_otps" => $expiredCount,
    "deleted_unverified" => $deletedCount,
    "timestamp" => date("Y-m-d H:i:s")
]);
