<?php

namespace App\Http\Controllers;

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

class EmailController extends Controller
{
    protected CPanelService $cpanel;

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

    // ── helpers ────────────────────────────────────────────────

    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);
    }

    private function apiError(array $res): ?string
    {
        if (isset($res['status']) && (int)$res['status'] === 0) {
            $errs = $res['errors'] ?? [];
            return is_array($errs) ? ($errs[0] ?? 'API error') : (string)$errs;
        }
        return null;
    }

    // ── main page ──────────────────────────────────────────────

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

        foreach ($userDomains as $domain) {
            try {
                $res  = $this->cpanel->listEmailAccounts($domain);
                $list = $res['data'] ?? [];
                foreach ($list as $acc) {
                    $acc['_domain'] = $domain;
                    $emails[] = $acc;
                }
            } catch (\Throwable) {}
        }

        $cpanelHost  = preg_replace('#^https?://#', '', rtrim(env('CPANEL_DOMAIN', ''), '/'));
        $webmailUrl  = "https://{$cpanelHost}:2096/";

        return view('dashboard.emails', compact('emails', 'userDomains', 'webmailUrl'));
    }

    // ── AJAX: create email ─────────────────────────────────────

    public function create(Request $request)
    {
        $request->validate([
            'email'    => 'required|string|regex:/^[a-zA-Z0-9._\-\+]+$/|max:64',
            'domain'   => 'required|string',
            'password' => 'required|string|min:8',
            'quota'    => 'sometimes|integer|min:0|max:10240',
        ]);

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

        $res = $this->cpanel->createEmailAccount(
            $request->email,
            $request->password,
            $request->domain,
            (int)($request->quota ?? 250)
        );

        if ($err = $this->apiError($res))
            return response()->json(['success' => false, 'message' => $err]);

        return response()->json([
            'success'  => true,
            'full'     => $request->email . '@' . $request->domain,
        ]);
    }

    // ── AJAX: delete email ─────────────────────────────────────

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

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

        $res = $this->cpanel->deleteEmailAccount($request->email, $request->domain);
        if ($err = $this->apiError($res))
            return response()->json(['success' => false, 'message' => $err]);

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

    // ── AJAX: change password ──────────────────────────────────

    public function changePassword(Request $request)
    {
        $request->validate([
            'email'    => 'required|string',
            'domain'   => 'required|string',
            'password' => 'required|string|min:8',
        ]);

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

        $res = $this->cpanel->changeEmailPassword($request->email, $request->domain, $request->password);
        if ($err = $this->apiError($res))
            return response()->json(['success' => false, 'message' => $err]);

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

    // ── Webmail auto-login ─────────────────────────────────────

    public function webmail(Request $request)
    {
        $cpanelHost = preg_replace('#^https?://#', '', rtrim(env('CPANEL_DOMAIN', ''), '/'));
        $email      = $request->get('email', '');   // full email address
        $webmailUrl = "https://{$cpanelHost}:2096/";

        return view('dashboard.webmail_redirect', compact('webmailUrl', 'email'));
    }
}
