<?php
require_once __DIR__ . '/../../config/db.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);
$fingerprint = $input['fingerprint'] ?? null;
$plan = $input['plan'] ?? null;
$paymentRef = $input['payment_ref'] ?? null;

if (!$fingerprint || !$plan) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing fingerprint or plan']);
    exit;
}

$validPlans = ['free', 'basic', 'pro', 'annual'];
if (!in_array($plan, $validPlans)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid plan type']);
    exit;
}

// Calculate expiration date based on plan
$expiresAt = null;
if ($plan === 'basic' || $plan === 'pro') {
    $expiresAt = date('Y-m-d H:i:s', strtotime('+30 days'));
} elseif ($plan === 'annual') {
    $expiresAt = date('Y-m-d H:i:s', strtotime('+365 days'));
}

try {
    $pdo->beginTransaction();

    // Deactivate previous active subscriptions for this device
    $stmt = $pdo->prepare("UPDATE subscriptions SET is_active = 0 WHERE fingerprint = :fingerprint");
    $stmt->execute([':fingerprint' => $fingerprint]);

    // Insert new subscription
    $stmt = $pdo->prepare("INSERT INTO subscriptions (fingerprint, plan, expires_at, payment_ref, is_active) 
                           VALUES (:fingerprint, :plan, :expires_at, :payment_ref, 1)");
    $stmt->execute([
        ':fingerprint' => $fingerprint,
        ':plan' => $plan,
        ':expires_at' => $expiresAt,
        ':payment_ref' => $paymentRef
    ]);

    $pdo->commit();

    echo json_encode([
        'success' => true,
        'message' => 'Subscription activated successfully',
        'plan' => $plan,
        'expires_at' => $expiresAt
    ]);

} catch (PDOException $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}
