<?php

declare(strict_types=1);

namespace App\Controllers\PlatformAdmin;

use App\Core\BaseController;
use App\Core\Database;
use App\Core\PlatformAuth;
use App\Core\Request;
use App\Core\Response;
use App\Core\Validator;
use App\Models\SubscriptionCodeModel;
use PDO;

final class PlatformSubscriptionCodeController extends BaseController
{
    public function index(Request $request): Response
    {
        $companies = Database::connection()
            ->query('SELECT id, name FROM business_lines ORDER BY name')
            ->fetchAll(PDO::FETCH_ASSOC);

        return $this->view('platform/codes', [
            'title' => 'Subscription codes',
            'codes' => (new SubscriptionCodeModel())->all(),
            'companies' => $companies,
        ], useLayout: false);
    }

    public function create(Request $request): Response
    {
        $validator = Validator::make($request->all(), [
            'intent' => 'required|in:activate_new,renew_existing,either',
            'business_line_id' => 'nullable|integer',
            'duration_months' => 'required|integer|min:1|max:60',
            'max_uses' => 'required|integer|min:1|max:1000',
            'expires_at' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return $this->withErrors($request, $validator->errors(), 'platform/codes');
        }

        $data = $validator->validated();
        $businessLineId = !empty($data['business_line_id']) ? (int) $data['business_line_id'] : null;

        // A code tied to one company only ever makes sense as a
        // renewal for that company, not a fresh signup.
        if ($businessLineId !== null) {
            $data['intent'] = 'renew_existing';
        }

        $result = (new SubscriptionCodeModel())->create(
            intent: $data['intent'],
            businessLineId: $businessLineId,
            durationMonths: (int) $data['duration_months'],
            maxUses: (int) $data['max_uses'],
            expiresAt: !empty($data['expires_at']) ? $data['expires_at'] : null,
            createdByAdminId: (int) PlatformAuth::id(),
        );

        return $this->view('platform/codes-created', [
            'title' => 'Code generated',
            'plaintextCode' => $result['plaintext_code'],
        ], useLayout: false);
    }

    public function revoke(Request $request, int $codeId): Response
    {
        (new SubscriptionCodeModel())->revoke($codeId);

        return $this->redirect('platform/codes');
    }
}
