<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;
use App\Models\LegalCase;
use App\Models\Invoice;
use App\Models\Document;
use Carbon\Carbon;


class AdminController extends Controller
{

   public function index()
    {
        $user = Auth::user();

        // 1. KPI METRICS
        $stats = [
            'active_cases' => LegalCase::whereNotIn('status', ['closed', 'archived'])->count(),

            'documents_count' => Document::count(),

            // "Cash Collected" - Invoices marked paid this month
            'monthly_revenue' => Invoice::where('status', 'paid')
                ->whereMonth('updated_at', Carbon::now()->month) // Use updated_at for payment timing
                ->whereYear('updated_at', Carbon::now()->year)
                ->sum('total_amount'),

            // "Pending" - Money owed to the firm
            'pending_revenue' => Invoice::whereIn('status', ['unpaid', 'partially_paid', 'overdue'])->sum('total_amount'),
        ];

        // 2. CHART: REVENUE TREND (Last 6 Months)
        // We use a raw query compatible with MySQL strict mode
        $revenueData = Invoice::selectRaw("DATE_FORMAT(created_at, '%Y-%m') as month_key, DATE_FORMAT(created_at, '%b') as month_label, SUM(total_amount) as total")
            ->where('status', 'paid')
            ->where('created_at', '>=', Carbon::now()->subMonths(6))
            ->groupBy('month_key', 'month_label')
            ->orderBy('month_key', 'ASC')
            ->get();

        $revenueLabels = $revenueData->pluck('month_label');
        $revenueValues = $revenueData->pluck('total');

        // 3. CHART: CASE STATUS SNAPSHOT
        $caseStatusData = LegalCase::select('status', DB::raw('count(*) as total'))
            ->groupBy('status')
            ->pluck('total', 'status')
            ->toArray();

        // Normalize data for chart (ensure arrays are aligned)
        $caseLabels = array_keys($caseStatusData);
        $caseValues = array_values($caseStatusData);

        // 4. LISTS
        $recent_cases = LegalCase::with('client')
            ->latest()
            ->take(5)
            ->get();

        $upcoming_hearings = LegalCase::whereNotNull('court_date')
            ->where('court_date', '>=', now()) // Only future hearings
            ->orderBy('court_date', 'asc')
            ->take(5)
            ->get();

        return view('admin.dashboard', compact(
            'user',
            'stats',
            'recent_cases',
            'upcoming_hearings',
            'revenueLabels',
            'revenueValues',
            'caseLabels',
            'caseValues'
        ));
    }

    public function userDashboard()
    {
        $user = Auth::user();

        if ($user->hasRole('client')) {
            $cases = LegalCase::where('client_id', $user->id)->latest()->get();

            $pendingInvoices = Invoice::whereHas('case', function ($q) use ($user) {
                $q->where('client_id', $user->id);
            })->where('status', '!=', 'paid')->get();

            $nextHearing = LegalCase::where('client_id', $user->id)
                ->whereNotNull('court_date')
                ->where('court_date', '>=', now())
                ->orderBy('court_date', 'asc')
                ->first();

            return view('dashboard', compact('cases', 'pendingInvoices', 'nextHearing'));
        }
    }


    public function userTenantDashboard()
{
    $user = Auth::user();

    // 1. Find the Client profile associated with the logged-in user
    // We match by email since the User and Client tables are likely separate
    $client = \App\Models\User::where('email', $user->email)->first();

    // 2. Handle scenario where no Client profile exists yet
    if (!$client) {
        return view('dashboard', [
            'cases' => collect(),
            'pendingInvoices' => collect(),
            'nextHearing' => null
        ]);
    }

    // 3. Fetch the Client's Active Data
    $cases = LegalCase::where('client_id', $client->id)
        ->latest()
        ->get();

    $pendingInvoices = Invoice::whereHas('case', function($q) use ($client) {
            $q->where('client_id', $client->id);
        })
        ->whereIn('status', ['unpaid', 'partially_paid', 'overdue'])
        ->orderBy('due_date', 'asc')
        ->get();

    $nextHearing = LegalCase::where('client_id', $client->id)
        ->whereNotNull('court_date')
        ->where('court_date', '>=', now())
        ->orderBy('court_date', 'asc')
        ->first();

    // 4. Return the view with data
    return view('dashboard', compact('cases', 'pendingInvoices', 'nextHearing'));
}
}
