<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/helpers.php';

$email = $_GET['email'] ?? '';
$platform_id = (int)($_GET['platform_id'] ?? 0);

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

if (!$email || !$platform_id) {
    echo json_encode(['error' => 'Parámetros incompletos.']);
    exit;
}

$stmt = pdo()->prepare('SELECT id, email, expiration_date, price, screens_bought FROM assigned_accounts WHERE email = ? AND platform_id = ? ORDER BY expiration_date DESC');
$stmt->execute([$email, $platform_id]);
$rows = $stmt->fetchAll();

$history = [];
$today = new DateTimeImmutable('today');

foreach ($rows as $r) {
    $expDate = $r['expiration_date'] ? DateTimeImmutable::createFromFormat('Y-m-d', $r['expiration_date']) : null;
    $daysRemaining = $expDate ? $expDate->diff($today)->format('%r%a') : 'N/A';
    if (is_string($daysRemaining)) {
        $daysRemainingStr = $daysRemaining === 'N/A' ? 'N/A' : ((int)$daysRemaining < 0 ? 'Expirada' : ((int)$daysRemaining === 0 ? 'Vence hoy' : ((int)$daysRemaining === 1 ? 'Vence mañana' : $daysRemaining . ' días')));
    } else {
        $daysRemainingStr = 'N/A';
    }
    $history[] = [
        'id' => $r['id'],
        'email' => $r['email'],
        'expiration_date_display' => $expDate ? $expDate->format('d/m/Y') : 'N/A',
        'days_remaining' => $daysRemainingStr,
        'price' => $r['price'],
        'screens_bought' => $r['screens_bought'],
    ];
}

echo json_encode(['history' => $history]);
