<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\DB;
use App\Services\MercadoPagoService;

class SubscriptionController extends Controller
{
    public function show(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $tenant = DB::pdo()->prepare("SELECT t.id, t.status, p.name, p.price, p.id AS plan_id FROM tenants t LEFT JOIN plans p ON t.plan_id = p.id WHERE t.id = ?");
        $tenant->execute([$tenantId]);
        $data = $tenant->fetch();
        $this->view('plan/checkout', ['data' => $data]);
    }

    public function create(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $stmt = DB::pdo()->prepare("SELECT t.id, p.id AS plan_id, p.price FROM tenants t LEFT JOIN plans p ON t.plan_id = p.id WHERE t.id = ?");
        $stmt->execute([$tenantId]);
        $row = $stmt->fetch();
        $amount = (float)($row['price'] ?? 0);
        $ext = $tenantId . ':' . ($row['plan_id'] ?? 0) . ':' . time();
        $res = MercadoPagoService::createSubscription($tenantId, (int)($row['plan_id'] ?? 0), $amount, $ext);
        $status = $res['status'] ?? 0;
        $mpId = (string)($res['body']['id'] ?? '');
        $ins = DB::pdo()->prepare("INSERT INTO payments (tenant_id, plan_id, mp_payment_id, status, amount, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $now = date('Y-m-d H:i:s');
        $ins->execute([$tenantId, (int)($row['plan_id'] ?? 0), $mpId, $status === 201 ? 'pending' : 'error', $amount, $now, $now]);
        header('Location: /plano/status');
    }

    public function status(): void
    {
        $tenantId = $_SESSION['tenant_id'] ?? 0;
        $stmt = DB::pdo()->prepare("SELECT t.status, p.name, p.limit_notas FROM tenants t LEFT JOIN plans p ON t.plan_id = p.id WHERE t.id = ?");
        $stmt->execute([$tenantId]);
        $info = $stmt->fetch();
        $pay = DB::pdo()->prepare("SELECT status, amount, created_at FROM payments WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 10");
        $pay->execute([$tenantId]);
        $list = $pay->fetchAll();
        $this->view('plan/status', ['info' => $info, 'list' => $list]);
    }
}
