<?php

namespace App\Http\Controllers\Admin;

use DB;
use Log;
use Carbon\Carbon;
use App\Models\License;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Models\LicenseDomain;
use App\Http\Controllers\Controller;
use App\Services\DomainMonitorService;
use Illuminate\Support\Facades\Artisan;
use Spatie\UptimeMonitor\Models\Monitor;
use Spatie\UptimeMonitor\Jobs\CheckUptimeJob;
use Spatie\UptimeMonitor\Commands\CheckUptime;


class DomainMonitorController extends Controller
{
    public function index()
    {
        $licenses = License::with(['domains','product'])->get();
        $domains = LicenseDomain::with(['license', 'monitor'])
            ->get()
            ->map(function ($domain) {

                $monitor = $domain->monitor;
                // dd($monitor);
                return [
                    'id'            => $domain->id,
                    'product_id'    =>$domain->product_id,
                    'license_id'    => $domain->license_id,
                    'domain'        => $domain->domain,
                    'license_key'   => $domain->license->license_key ?? '-',
                    'product_name' => $domain->license->product->name ?? '-',
                    'status'        => $monitor->uptime_status ?? 'not_yet_checked',
                    'last_checked'  => $monitor && $monitor->uptime_last_check_date
                        ? $monitor->uptime_last_check_date->format('Y-m-d H:i')
                        : '—',

                    'response_time' => $monitor->uptime_check_response_time ?? '—',
                ];
            });
            // dd($domains);

        return view('admin.monitor.index', compact('licenses', 'domains'));
    }
    
    public function check(Request $request)
    {
        $request->validate([
            'domain_id' => 'required|exists:license_domains,id',
        ]);

        $domain = LicenseDomain::findOrFail($request->domain_id);
        $url = str_starts_with($domain->domain, 'http')
            ? $domain->domain
            : 'https://' . $domain->domain;
        $monitor = Monitor::where('url', $url)->first();

        if (!$monitor) {
            $monitor = Monitor::create([
                'url' => $url,
                'uptime_check_enabled' => true,
                'uptime_check_interval_in_minutes' => 5,
            ]);
        }
        if (!$domain->monitor_id) {
            $domain->update([
                'monitor_id' => $monitor->id,
            ]);
        }
        Artisan::call('monitor:check-uptime');
        $monitor->refresh();

        if (!$monitor->uptime_status) {
            return response()->json([
                'message' => 'Monitor created. First check is running. Try again shortly.',
            ], 202);
        }
        $domain->update([
            'website_status'     => $monitor->uptime_status,
            'last_checked_at'    => now(),
            'last_response_time' => $monitor->uptime_check_response_time,
        ]);

        return response()->json([
            'domain'        => $domain->domain,
            'status'        => $domain->website_status,
            'checked_at'    => $domain->last_checked_at,
            'response_time' => $domain->last_response_time,
        ]);
    }

    public function assignedDomains(License $license)
    {
        $domains = LicenseDomain::where('license_id', $license->id)->get();
        return response()->json($domains);
    }



    public function assignForm()
    {
        return view('admin.monitor.assign', [
            'licenses' => License::with('product')->get(),

        ]);
    }

    public function monitorDomain(Request $request)
    {
        $request->validate([
            'license_id' => 'required|exists:licenses,id',
            'domain_id'  => 'required|exists:license_domains,id',
        ]);
        $domain = LicenseDomain::findOrFail($request->domain_id);
        $domainUrl = strtolower(trim($domain->domain));
        $exists = Monitor::whereRaw("LOWER(REPLA
        CE(REPLACE(url,'http://',''), 'https://','')) = ?", [$domainUrl])
            ->exists();
        if ($exists) {
            return back()->with('error', 'This domain is already monitored.');
        }

        Artisan::call('monitor:sync-domain', ['domain_id' => $domain->id]);
        Artisan::call('monitor:check-uptime');
        return back()->with('success', 'Domain monitoring started successfully.');
    }
    
    public function destroy($id)
    {
        LicenseDomain::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Domain removed');
    }
    public function destroyDomain(LicenseDomain $domain)
    {
        $domain->delete();

        return response()->json([
            'message' => 'Domain deleted successfully'
        ]);
    }


    public function getLicenses($productId)
    {
        $licenses = License::where('product_id', $productId)
            ->select('id', 'license_key')
            ->get()
            ->toArray();

        return response()->json([
            'licenses' => $licenses
        ]);
    }
    
   public function domainsByProduct($productId)
{
    $domains = LicenseDomain::query()
        ->whereHas('license', function ($q) use ($productId) {
            $q->where('product_id', $productId);
        })
        ->with([
            'license.product',
            'monitor'
        ])
        ->get()
        ->map(function ($d) {

            return [
                'id'           => $d->id,
                'domain'       => $d->domain,

                // License
                'license_id'   => $d->license_id,
                'license_key'  => $d->license?->license_key ?? '—',
                'product_id'   => $d->license?->product_id ?? null,
                'product_name' => $d->license?->product?->name ?? '—',

                // Monitor (SAFE DEFAULTS)
                'monitor_status' => $d->monitor?->uptime_status ?? 'down',

                'last_checked' => $d->monitor?->uptime_last_check_date
                    ? $d->monitor->uptime_last_check_date->diffForHumans()
                    : '—',

                'uptime' => $d->monitor?->uptime_percentage ?? null,
            ];
        });

    return response()->json($domains->values());
}

    
    public function getDomains($licenseId)
    {
        return LicenseDomain::with('license.product')
            ->where('license_id', $licenseId)
            ->get()
            ->map(function ($d) {
                return [
                    'id'           => $d->id,
                    'domain'       => $d->domain,
                    'status'       => $d->status,
                    'last_checked' => $d->last_checked,
                    'license_id'   => $d->license_id,
                    'license_key'  => $d->license->license_key,
                    'product_id'   => $d->license->product->id,
                    'product_name' => $d->license->product->name,
                ];
            });
    }


}
