<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AuditLog;
use App\Models\License;
use App\Models\User;

class DashboardController extends Controller
{
    public function stats()
    {
        $user = auth()->user();

        $licenseQuery = License::query();
        if ($user->isOwner()) {
            // Owner sees everything
        } elseif ($user->isAdmin()) {
            // Admin sees own keys + keys generated by their resellers
            $resellerIds = User::where('referred_by', $user->id)
                ->where('role', 'reseller')
                ->pluck('id');
            $licenseQuery->whereIn('created_by', $resellerIds->push($user->id));
        } else {
            // Reseller sees only their own keys
            $licenseQuery->where('created_by', $user->id);
        }

        $total   = (clone $licenseQuery)->count();
        $active  = (clone $licenseQuery)->where('is_active', true)->where('is_blocked', false)->where('expires_at', '>=', now())->count();
        $expired = (clone $licenseQuery)->where('expires_at', '<', now())->count();
        $unused  = (clone $licenseQuery)->where('device_count', 0)->count();
        $blocked = (clone $licenseQuery)->where('is_blocked', true)->count();

        $data = [
            'total_keys'   => $total,
            'active_keys'  => $active,
            'expired_keys' => $expired,
            'unused_keys'  => $unused,
            'blocked_keys' => $blocked,
            'balance'      => $user->balance,
        ];

        if ($user->isAdmin()) {
            if ($user->isOwner()) {
                $data['panel_users'] = User::count();
            } else {
                // Admin sees count of their direct resellers only
                $data['panel_users'] = User::where('referred_by', $user->id)->count();
            }
        }

        // Fetch last 3 recent activities
        $logQuery = AuditLog::with('user')->latest();
        if (!$user->isOwner()) {
            $logQuery->where('user_id', $user->id);
        }
        $data['recent_logs'] = $logQuery->take(3)->get()->map(function($log) {
            return [
                'action' => $log->action,
                'details' => $log->details,
                'time_ago' => $log->created_at ? $log->created_at->diffForHumans() : 'Just now'
            ];
        });

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

    public function auditLogs()
    {
        if (!auth()->user()->isOwner()) {
            return response()->json(['success' => false, 'message' => 'Forbidden'], 403);
        }
        $logs = AuditLog::with('user')->latest()->paginate(50);
        return response()->json(['success' => true, 'data' => $logs]);
    }
}
