<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\PurchaseOrder;
use App\Models\Supplier;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Mpdf\Mpdf;
use Mpdf\Output\Destination;

class FinancialReportPdfController extends Controller
{
    public function __invoke(Request $request)
    {
        $user = auth()->user();
        if (! $user || ! $user->hasPermissionTo('view_financial_reports')) {
            abort(403, 'غير مصرح');
        }

        $startDate = $request->input('startDate', Carbon::today()->subDays(29)->format('Y-m-d'));
        $endDate = $request->input('endDate', Carbon::today()->format('Y-m-d'));
        $supplierId = $request->input('supplierId');
        $agentId = $request->input('agentId');

        $baseQuery = Order::query()
            ->whereBetween('created_at', [$startDate . ' 00:00:00', $endDate . ' 23:59:59']);

        if ($supplierId) {
            $baseQuery->whereHas('items.variant', fn ($q) => $q->where('default_supplier_id', $supplierId));
        }
        if ($agentId) {
            $baseQuery->where('user_id', $agentId);
        }

        $summary = (clone $baseQuery)
            ->selectRaw("
                SUM(CASE WHEN status != 'returned' THEN total ELSE 0 END) as total_revenue,
                SUM(CASE WHEN status != 'returned' THEN total_profit ELSE 0 END) as total_profit,
                SUM(CASE WHEN status != 'returned' THEN COALESCE(shipping_cost, 0) + COALESCE(payment_fee, 0) ELSE 0 END) as shipping_fees,
                COUNT(CASE WHEN status != 'returned' THEN 1 END) as orders_count
            ")
            ->first();

        $supplierQ = Supplier::where('is_active', true);
        if ($supplierId) {
            $supplierQ->where('id', $supplierId);
        }
        $totalSupplierDebt = (float) $supplierQ->sum('current_balance');
        $netProfit = (float) ($summary->total_profit ?? 0) - $totalSupplierDebt;

        $recentOrders = (clone $baseQuery)
            ->with('user')
            ->orderByDesc('created_at')
            ->limit(20)
            ->get();

        $statusLabels = Order::getStatusLabels();

        $html = view('pdf.financial-report', [
            'startDate' => $startDate,
            'endDate' => $endDate,
            'totalRevenue' => (float) ($summary->total_revenue ?? 0),
            'totalShippingFees' => (float) ($summary->shipping_fees ?? 0),
            'totalSupplierDebt' => $totalSupplierDebt,
            'netProfit' => $netProfit,
            'ordersCount' => (int) ($summary->orders_count ?? 0),
            'recentOrders' => $recentOrders,
            'statusLabels' => $statusLabels,
        ])->render();

        $mpdf = new Mpdf([
            'mode' => 'utf-8',
            'format' => 'A4',
            'default_font' => 'xbriyaz',
            'default_font_size' => 10,
            'margin_left' => 12,
            'margin_right' => 12,
            'margin_top' => 16,
            'margin_bottom' => 16,
            'autoArabic' => true,
            'mirrorMargins' => true,
        ]);
        $mpdf->WriteHTML($html);

        $filename = 'financial-report-' . now()->format('Y-m-d-His') . '.pdf';

        return response($mpdf->Output(null, Destination::STRING_RETURN))
            ->header('Content-Type', 'application/pdf')
            ->header('Content-Disposition', 'attachment; filename="' . $filename . '"');
    }
}
