#!/usr/bin/php56
<?php
require_once('../functions.php');

/**
 * Main script to handle point expiration
 * Rules:
 * 1. Check if there was any credit in the last 24 months
 * 2. If no credit in 24 months -> all points expire
 * 3. If there was credit -> points older than 4 years expire monthly
 */

// Get current month and year
$currentMonth = date('m', time());
$currentYear = date('Y', time());
$currentTimestamp = time();

// Process all users
$result = dbQuery("SELECT userId FROM users") or die(dbError());
while ($row = dbFetchRow($result)) {
    $userId = $row['userId'];
    if ($userId <= 0) {
        continue;
    }

    processUserPoints($userId, $currentYear, $currentMonth, $currentTimestamp);
}

/**
 * Process points for a single user
 */
function processUserPoints($userId, $currentYear, $currentMonth, $currentTimestamp) {
    $konto = new konto($userId);

    // Calculate timestamp for 24 months ago
    $twoYearsAgo = strtotime("-24 months", $currentTimestamp);

    // Check for any credits in last 24 months
    $lastCreditDate = getLastPositiveEntry($userId, $currentTimestamp);

    if ($lastCreditDate === 0 || $lastCreditDate < $twoYearsAgo) {
        // No credits in last 24 months - all points expire
        expireAllPoints($konto, $currentTimestamp);
    } else {
        // Process 4-year expiration
        processFourYearExpiration($konto, $currentYear, $currentMonth, $currentTimestamp);
    }
}

/**
 * Get the date of the last positive entry (credit) for a user
 */
function getLastPositiveEntry($userId, $currentTimestamp) {
    $query = "SELECT MAX(datum) as last_credit 
              FROM kontobewegungen 
              WHERE userId = $userId 
              AND wert > 0 
              AND gueltig = 1 
              AND geloescht != 1 
              AND datum <= $currentTimestamp";

    $result = dbQuery($query) or die(dbError());
    $row = dbFetchRow($result);
    return $row['last_credit'] ? intval($row['last_credit']) : 0;
}

/**
 * Expire all points for inactive accounts (no credits in 24 months)
 */
function expireAllPoints($konto, $currentTimestamp) {
    $currentBalance = $konto->getSaldo();

    if ($currentBalance <= 0) {
        return;
    }

    $user = new user(0, $konto->userId);
    echo "{$konto->userId}, {$user->versnummer}: Expire all points due to 24 months inactivity. Balance: $currentBalance\n";

    // Create expiration entry
    $expiration = new kontoBewegung();
    $expiration->userId = $konto->userId;
    $expiration->kategorie = 0;
    $expiration->unterkategorie = 0;
    $expiration->praemienid = 0;
    $expiration->praemienhmid = 0;
    $expiration->kommentar = 'Punkteverfall, da 2 Jahre keine Punkte aufgefrischt wurden';
    $expiration->datum = $currentTimestamp;
    $expiration->datumerwerb = date('Y-m-d', $currentTimestamp);
    $expiration->beschreibung = 'Punkteverfall, da 2 Jahre keine Punkte aufgefrischt wurden';
    $expiration->wert = -$currentBalance;
    $expiration->gueltig = 0;

    $konto->addKontobewegung($expiration);

    $updateQuery = "UPDATE kontobewegungen SET gueltig = 0
			    	WHERE wert > 0 
					AND gueltig = 1 
					AND geloescht != 1 
					AND userId = {$konto->userId}";
    dbQuery($updateQuery) or die(dbError());
}

/**
 * Process 4-year expiration for active accounts
 */
function processFourYearExpiration($konto, $currentYear, $currentMonth, $currentTimestamp) {
    // Get timestamp for 4 years ago
    $fourYearsAgo = strtotime("-4 years", $currentTimestamp);

    // Get all valid points older than 4 years that haven't expired yet
    $query = "SELECT SUM(wert) as expiring_points 
              FROM kontobewegungen 
              WHERE userId = {$konto->userId} 
              AND datum < $fourYearsAgo 
              AND wert > 0 
              AND gueltig = 1 
              AND geloescht != 1";

    $result = dbQuery($query) or die(dbError());
    $row = dbFetchRow($result);
    $expiringPoints = intval($row['expiring_points']);

    if ($expiringPoints <= 0) {
        return;
    }

    // Make sure we don't expire more points than the current balance
    $currentBalance = $konto->getSaldo();
    if ($expiringPoints > $currentBalance) {
        $expiringPoints = $currentBalance;
    }

    $user = new user(0, $konto->userId);
    echo "{$konto->userId}, {$user->versnummer}: Expire $expiringPoints points older than 4 years. Balance: $currentBalance\n";

    // Create expiration entry
    $expiration = new kontoBewegung();
    $expiration->userId = $konto->userId;
    $expiration->kategorie = 0;
    $expiration->unterkategorie = 0;
    $expiration->praemienid = 0;
    $expiration->praemienhmid = 0;
    $expiration->kommentar = 'Punkteverfall nach 4 Jahren';
    $expiration->datum = $currentTimestamp;
    $expiration->datumerwerb = date('Y-m-d', $currentTimestamp);
    $expiration->beschreibung = 'Punkteverfall nach 4 Jahren';
    $expiration->wert = -$expiringPoints;
    $expiration->gueltig = 0;

    $konto->addKontobewegung($expiration);

    // Mark expired points as invalid
    $updateQuery = "UPDATE kontobewegungen 
                   SET gueltig = 0 
                   WHERE userId = {$konto->userId} 
                   AND datum < $fourYearsAgo 
                   AND wert > 0 
                   AND gueltig = 1 
                   AND geloescht != 1";
    dbQuery($updateQuery) or die(dbError());
}