<?php
// ═══════════════════════════════════════════════════════════
//  FICTION IGNITION — api/subscription/index.php
//  Routes: POST /api/subscription/?action=checkout
//          POST /api/subscription/?action=cancel
//          GET  /api/subscription/?action=status
// ═══════════════════════════════════════════════════════════

declare(strict_types=1);

require_once __DIR__ . '/../lib/config.php';
require_once __DIR__ . '/../lib/square.php';
require_once __DIR__ . '/../lib/mailer.php';

fi_json_headers();

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

match (true) {
    $method === 'POST' && $action === 'checkout' => handle_checkout($input),
    $method === 'POST' && $action === 'cancel'   => handle_cancel(),
    $method === 'GET'  && $action === 'status'   => handle_status(),
    default => fi_error('Unknown action', 404),
};

// ── Checkout — create Square subscription ─────────────────
function handle_checkout(array $in): never {
    $session   = fi_require_auth();
    $planKey   = $in['plan']        ?? '';
    $cardNonce = $in['card_nonce']  ?? '';  // From Square Web Payments SDK

    $validPlans = ['starter', 'writer', 'author_pro'];
    if (!in_array($planKey, $validPlans, true)) fi_error('Invalid plan selected.');
    if (!$cardNonce) fi_error('Payment information is required.');

    $db = fi_db();

    // Check if user already has an active subscription
    $stmt = $db->prepare("SELECT status FROM subscriptions WHERE user_id = ? LIMIT 1");
    $stmt->execute([$session['id']]);
    $existing = $stmt->fetch();
    if ($existing && $existing['status'] === 'active') {
        fi_error('You already have an active subscription. Cancel it first to switch plans.');
    }

    try {
        // Get/create Square customer
        $customerId = square_get_or_create_customer(
            $session['id'],
            $session['email'],
            $session['name']
        );

        // Create subscription
        $result = square_create_subscription($customerId, $planKey, $cardNonce);
        $sub    = $result['subscription'];
        $cardId = $result['card_id'];

        // Save to DB
        $db->prepare('
            INSERT INTO subscriptions
                (user_id, square_subscription_id, square_customer_id, square_card_id, plan_key, status, current_period_start, current_period_end)
            VALUES (?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE
                square_subscription_id = VALUES(square_subscription_id),
                square_customer_id     = VALUES(square_customer_id),
                square_card_id         = VALUES(square_card_id),
                plan_key               = VALUES(plan_key),
                status                 = VALUES(status),
                current_period_start   = VALUES(current_period_start),
                current_period_end     = VALUES(current_period_end)
        ')->execute([
            $session['id'],
            $sub['id'],
            $customerId,
            $cardId,
            $planKey,
            'active',
            $sub['start_date'] ?? date('Y-m-d'),
            $sub['charged_through_date'] ?? date('Y-m-d', strtotime('+1 month')),
        ]);

        // Upgrade user tier
        $db->prepare('UPDATE users SET tier = ? WHERE id = ?')->execute([$planKey, $session['id']]);

        // Send confirmation email
        $prices = ['starter' => '$2.99', 'writer' => '$6.99', 'author_pro' => '$9.99'];
        $labels = ['starter' => 'Starter', 'writer' => 'Writer', 'author_pro' => 'Author Pro'];
        $html   = fi_email_payment_confirm_template(
            $session['name'],
            $labels[$planKey],
            $prices[$planKey]
        );
        fi_send_email($session['email'], $session['name'], 'Fiction Ignition — Subscription Confirmed! 🎉', $html);

        fi_ok([
            'message'  => 'Subscription activated!',
            'plan'     => $planKey,
            'tier'     => $planKey,
        ]);

    } catch (RuntimeException $e) {
        fi_error($e->getMessage());
    }
}

// ── Cancel subscription ────────────────────────────────────
function handle_cancel(): never {
    $session = fi_require_auth();
    $db      = fi_db();

    $stmt = $db->prepare("SELECT * FROM subscriptions WHERE user_id = ? AND status = 'active' LIMIT 1");
    $stmt->execute([$session['id']]);
    $sub = $stmt->fetch();

    if (!$sub) fi_error('No active subscription found.');

    try {
        square_cancel_subscription($sub['square_subscription_id']);

        // Mark as cancelled; user keeps tier until period end
        $db->prepare("UPDATE subscriptions SET status = 'cancelled', cancelled_at = NOW() WHERE id = ?")
           ->execute([$sub['id']]);

        // Downgrade to free immediately (or you could downgrade at period end via webhook)
        $db->prepare('UPDATE users SET tier = \'free\' WHERE id = ?')->execute([$session['id']]);

        fi_ok(['message' => 'Subscription cancelled. Your access will end at the current billing period.']);

    } catch (RuntimeException $e) {
        fi_error($e->getMessage());
    }
}

// ── Status ─────────────────────────────────────────────────
function handle_status(): never {
    $session = fi_require_auth();
    $db      = fi_db();

    $stmt = $db->prepare('SELECT * FROM subscriptions WHERE user_id = ? LIMIT 1');
    $stmt->execute([$session['id']]);
    $sub = $stmt->fetch();

    if (!$sub) {
        fi_ok(['subscription' => null, 'tier' => 'free']);
    }

    fi_ok([
        'subscription' => [
            'plan'         => $sub['plan_key'],
            'status'       => $sub['status'],
            'period_start' => $sub['current_period_start'],
            'period_end'   => $sub['current_period_end'],
            'cancelled_at' => $sub['cancelled_at'],
        ],
        'tier' => $session['tier'],
    ]);
}
