<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST");

$file = 'data/listings.json';

// Ensure data dir
if (!is_dir('data')) mkdir('data');

$method = $_SERVER['REQUEST_METHOD'];

// DATA LOADING
$data = [];
if (file_exists($file)) {
    $json = file_get_contents($file);
    $data = json_decode($json, true) ?? [];
}

if ($method === 'GET') {
    // FILTER EXPIRATION (7 Days = 604800 seconds)
    $showAll = isset($_GET['all']) && $_GET['all'] === 'true';
    $targetUser = $_GET['user'] ?? null;

    $now = time();
    $expiryTime = 604800; // 7 days

    if ($targetUser) {
        // Return ALL items for specific user (even expired)
        $data = array_values(array_filter($data, function ($item) use ($targetUser) {
            $sId = $item['sellerId'] ?? '';
            $uId = $item['userId'] ?? '';
            $uEmail = isset($item['user']['email']) ? $item['user']['email'] : '';
            return ($sId === $targetUser || $uEmail === $targetUser || $uId === $targetUser);
        }));
    } elseif (!$showAll) {
        // Filter out expired items for general feed
        $data = array_values(array_filter($data, function ($item) use ($now, $expiryTime) {
            // If no timestamp, assume valid (legacy) or filter? Let's assume valid.
            if (!isset($item['timestamp'])) return true;

            // Check if seconds or ms
            $ts = $item['timestamp'];
            if ($ts > 10000000000) $ts = $ts / 1000;

            return ($now - $ts) < $expiryTime;
        }));
    }

    echo json_encode(['success' => true, 'listings' => $data]);
} elseif ($method === 'POST') {
    $input = file_get_contents('php://input');
    $payload = json_decode($input, true);

    if (!$payload) {
        echo json_encode(['success' => false, 'error' => 'Invalid JSON']);
        exit;
    }

    // RENEW ACTION
    if (isset($payload['action']) && $payload['action'] === 'renew') {
        $id = $payload['id'] ?? null;
        if (!$id) {
            echo json_encode(['success' => false, 'error' => 'No ID']);
            exit;
        }

        $found = false;
        foreach ($data as &$item) {
            if ($item['id'] == $id) {
                $item['timestamp'] = time();
                $found = true;
                break;
            }
        }
        if ($found) {
            if (file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT))) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'Write failed']);
            }
        } else {
            echo json_encode(['success' => false, 'error' => 'Item not found']);
        }
        exit;
    }

    // SAVE / UPDATE LOGIC
    if (isset($payload['id'])) {
        $found = false;
        foreach ($data as &$item) {
            if ($item['id'] == $payload['id']) {
                $item = array_merge($item, $payload); // Merge updates
                $found = true;
                break;
            }
        }
        if (!$found) {
            // NEW ITEM
            if (!isset($payload['timestamp'])) $payload['timestamp'] = time();
            if (isset($payload['timestamp']) && $payload['timestamp'] > 10000000000) $payload['timestamp'] = $payload['timestamp'] / 1000;

            $data[] = $payload;
        }

        if (file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT))) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Write failed']);
        }
    }
}
