<?php
// update_poi_cleaning_status.php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$debugLogFile = __DIR__ . '/update_poi_cleaning_status_debug.log';

require_once __DIR__ . '/logging_functions.php';
require_once __DIR__ . '/validation_functions.php';
require_once __DIR__ . '/update_poi_general.php';
require_once __DIR__ . '/db-connection.php'; // Sicherstellen, dass die DB-Verbindung steht
$config = require __DIR__ . '/config.php';

// Validierung (API-Key / Rechte / DB-Typ)
enforceValidRequest($debugLogFile);

internal_debug_log("--- " . basename(__FILE__) . " START ---", $debugLogFile);
header('Content-Type: application/json');

try {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE || !is_array($data)) {
        throw new Exception("Ungültige JSON-Eingabe.");
    }

    // Parameter auslesen (Gid und der neue Zeit-Code)
    $gid = $data['gid'] ?? null;
    $timeCode = isset($data['time_code']) ? (int)$data['time_code'] : 0;

    if (!$gid) {
        throw new Exception("Gid fehlt.");
    }

    // --- DATUMSSTEUERUNG ---
    // 0 = aktuell, 1 = -1 Monat, 2 = -3 Monate, 4 = -12 Monate
switch ($timeCode) {
        case 1:
            $lastCleaned = date('Y-m-d H:i:s', strtotime('-1 month'));
            $actionText = 'is_dirty'; 
            break;
        case 2:
            $lastCleaned = date('Y-m-d H:i:s', strtotime('-4 months'));
            $actionText = 'is_dirty';
            break;
        case 4:
            $lastCleaned = date('Y-m-d H:i:s', strtotime('-12 months'));
            $actionText = 'is_dirty';
            break;
        case 0:
        default:
            $lastCleaned = date('Y-m-d H:i:s'); 
            $actionText = 'is_clean';
            break;
    }

    $dataToUpdate = [
        'gid'          => $gid,
        'updated_at'   => date('Y-m-d H:i:s'),
        'action_text'  => $actionText,
        'last_cleaned' => $lastCleaned,
        'poiTable'     => $config['poiTable']
    ];
    
    internal_debug_log("Status-Update (Code $timeCode): " . print_r($dataToUpdate, true), $debugLogFile);

    // Aufruf der zentralen Update-Logik
    $response = update_poi_general($dataToUpdate, $debugLogFile);

    echo json_encode($response);

} catch (Throwable $e) {
    $errorMessage = $e->getMessage() . " in " . $e->getFile() . " on line " . $e->getLine();
    internal_debug_log("Fehler: " . $errorMessage, $debugLogFile);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}

internal_debug_log("--- " . basename(__FILE__) . " END ---", $debugLogFile);
?>