<?php
include '../db.php';
include '../auth.php';
require_right('Access POS'); // Require POS access for KDS cleanup

include '../kds_cleanup.php';

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$action = $input['action'] ?? '';

try {
    switch ($action) {
        case 'get_stats':
            $result = getKDSCleanupStats($conn);
            echo json_encode($result);
            break;
            
        case 'dry_run':
            $retention_days = isset($input['retention_days']) ? intval($input['retention_days']) : null;
            $result = performKDSCleanup($conn, $retention_days, true);
            echo json_encode($result);
            break;
            
        case 'cleanup':
            $retention_days = isset($input['retention_days']) ? intval($input['retention_days']) : null;
            $result = performKDSCleanup($conn, $retention_days, false);
            echo json_encode($result);
            break;
            
        case 'update_settings':
            $retention_days = isset($input['retention_days']) ? max(1, min(90, intval($input['retention_days']))) : 7;
            $auto_cleanup = isset($input['auto_cleanup']) ? ($input['auto_cleanup'] ? '1' : '0') : '1';
            
            // Update retention days setting
            $stmt1 = $conn->prepare("UPDATE settings SET value = ? WHERE code = 'kds_record_retention_days'");
            $stmt1->bind_param("s", $retention_days);
            $stmt1->execute();
            $stmt1->close();
            
            // Update auto cleanup setting
            $stmt2 = $conn->prepare("UPDATE settings SET value = ? WHERE code = 'kds_auto_cleanup_enabled'");
            $stmt2->bind_param("s", $auto_cleanup);
            $stmt2->execute();
            $stmt2->close();
            
            echo json_encode([
                'success' => true,
                'message' => 'KDS cleanup settings updated successfully',
                'retention_days' => $retention_days,
                'auto_cleanup_enabled' => $auto_cleanup === '1'
            ]);
            break;
            
        case 'get_cleanup_history':
            $limit = isset($input['limit']) ? max(1, min(100, intval($input['limit']))) : 20;
            
            $stmt = $conn->prepare("
                SELECT * FROM kds_cleanup_log 
                ORDER BY cleanup_date DESC 
                LIMIT ?
            ");
            $stmt->bind_param("i", $limit);
            $stmt->execute();
            $result = $stmt->get_result();
            
            $history = [];
            while ($row = $result->fetch_assoc()) {
                $history[] = $row;
            }
            $stmt->close();
            
            echo json_encode([
                'success' => true,
                'history' => $history
            ]);
            break;
            
        default:
            echo json_encode([
                'success' => false,
                'message' => 'Invalid action'
            ]);
            break;
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
