<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Services\CPanelService;
use App\Models\UserDomain;

class SslController extends Controller
{
    protected CPanelService $cpanel;

    public function __construct()
    {
        $this->cpanel = new CPanelService(
            env('CPANEL_DOMAIN'),
            env('CPANEL_USERNAME'),
            env('CPANEL_API_TOKEN')
        );
    }

    private function userDomains(): array
    {
        $user    = Auth::user();
        $domains = $user->primary_domain ? [$user->primary_domain] : [];
        $addon   = UserDomain::where('user_id', $user->id)->pluck('domain')->toArray();
        return array_unique(array_merge($domains, $addon));
    }

    private function userOwnsDomain(string $domain): bool
    {
        return in_array($domain, $this->userDomains(), true);
    }

    // ── Main page ──────────────────────────────────────────────

    public function index()
    {
        $userDomains = $this->userDomains();

        // Fetch AutoSSL metadata for all domains
        $autoSslMeta = [];
        try {
            $meta = $this->cpanel->getAutoSslMetadata();
            foreach ($meta as $item) {
                $d = $item['domain'] ?? null;
                if ($d) $autoSslMeta[$d] = $item;
            }
        } catch (\Throwable) {}

        // Fetch SSL cert info per domain
        $sslInfo = [];
        foreach ($userDomains as $domain) {
            try {
                $info = $this->cpanel->getSslForDomain($domain);
                $sslInfo[$domain] = $info;
            } catch (\Throwable) {
                $sslInfo[$domain] = [];
            }
        }

        return view('dashboard.ssl', compact('userDomains', 'sslInfo', 'autoSslMeta'));
    }

    // ── AJAX: Run AutoSSL (Let's Encrypt) ─────────────────────

    public function runAutoSsl(Request $request)
    {
        $res = $this->cpanel->runAutoSsl();

        if (isset($res['status']) && (int)$res['status'] === 0) {
            $err = $res['errors'][0] ?? 'AutoSSL check failed';
            return response()->json(['success' => false, 'message' => $err]);
        }

        return response()->json(['success' => true, 'message' => 'AutoSSL check started. Certificates will be issued shortly.']);
    }

    // ── AJAX: Get SSL status for a single domain ───────────────

    public function checkDomain(Request $request)
    {
        $request->validate(['domain' => 'required|string']);

        if (!$this->userOwnsDomain($request->domain))
            return response()->json(['error' => 'Unauthorized'], 403);

        try {
            $info = $this->cpanel->getSslForDomain($request->domain);
            $installed = $this->cpanel->checkSslStatus($request->domain);
            return response()->json([
                'success'   => true,
                'cert'      => $info,
                'installed' => $installed,
            ]);
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'message' => $e->getMessage()]);
        }
    }

    // ── AJAX: Remove SSL from domain ───────────────────────────

    public function removeSsl(Request $request)
    {
        $request->validate(['domain' => 'required|string']);

        if (!$this->userOwnsDomain($request->domain))
            return response()->json(['success' => false, 'message' => 'Unauthorized'], 403);

        $res = $this->cpanel->removeSsl($request->domain);

        if (isset($res['status']) && (int)$res['status'] === 0) {
            $err = $res['errors'][0] ?? 'Failed to remove SSL';
            return response()->json(['success' => false, 'message' => $err]);
        }

        return response()->json(['success' => true]);
    }
}
