<?php

namespace App\Http\Controllers\AiPortal;

use App\Models\WhmcsAdminUser;
use App\Models\WhmcsClientProducts;
use App\Models\WhmcsServer;
use App\Services\AuditLogger;
use App\Services\Whmcs\WhmcsMirrorSyncer;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * Read + admin actions for the local WHMCS data mirror. The mirror is
 * refreshed every 6 h by the scheduler; this controller exposes:
 *   - `status`: row counts + last-sync timestamps for the dashboard
 *   - `sync`:   manual "Sync now" button (full sync of all three sources)
 *   - `recentChanges`: tail of the WHMCS-diff audit-log entries
 */
class WhmcsMirrorController extends Controller
{
    public function status(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        return response()->json([
            'servers' => [
                'count'         => WhmcsServer::count(),
                'last_synced_at'=> WhmcsServer::max('last_synced_at'),
            ],
            'admin_users' => [
                'count'         => WhmcsAdminUser::count(),
                'last_synced_at'=> WhmcsAdminUser::max('last_synced_at'),
            ],
            'client_products' => [
                'count'         => WhmcsClientProducts::count(),
                'last_synced_at'=> WhmcsClientProducts::max('last_synced_at'),
                'stale_count'   => WhmcsClientProducts::where('last_synced_at', '<=', now()->subHours(6))->count(),
            ],
        ]);
    }

    public function sync(Request $request, WhmcsMirrorSyncer $mirror)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        // Refreshing every active client can take 10–30 s if a customer
        // has many tickets — bump time limits so the request doesn't get
        // killed by PHP defaults.
        @set_time_limit(600);
        ini_set('max_execution_time', '600');

        $stats = $mirror->syncAll();

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'whmcs_mirror.manual_sync', 'whmcs_mirror', null,
            ['stats' => $stats], $request);

        return response()->json($stats);
    }

    /**
     * Most-recent change-detected audit entries. Renders as a "What
     * changed in WHMCS lately?" panel — handy for spotting unexpected
     * edits without paging back through the full audit log.
     */
    public function recentChanges(Request $request)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $rows = \DB::table('audit_logs')
            ->whereIn('action', [
                'whmcs_server.changed', 'whmcs_server.added', 'whmcs_server.removed',
                'whmcs_admin.changed',
                'whmcs_client_products.changed',
            ])
            ->orderByDesc('logged_at')
            ->limit(50)
            ->get(['logged_at', 'action', 'target_type', 'target_id', 'payload']);

        // Decode payload JSON for the UI.
        $decoded = $rows->map(function ($r) {
            $r->payload = json_decode($r->payload ?? '[]', true) ?: [];
            return $r;
        });
        return response()->json(['changes' => $decoded]);
    }
}
