<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\PlatformSetting;
use App\Services\ReportService;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ReportController extends Controller
{
    public function __construct(
        protected ReportService $reportService
    ) {}

    public function salesReport(Request $request)
    {
        $this->authorize('view-reports');

        $validated = $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
            'user_id' => 'nullable|exists:users,id',
            'customer_id' => 'nullable|exists:customers,id',
        ]);

        $filters = [
            'user_id' => $validated['user_id'] ?? null,
            'customer_id' => $validated['customer_id'] ?? null,
        ];

        $report = $this->reportService->salesReport(
            $validated['start_date'],
            $validated['end_date'],
            $filters
        );

        return response()->json(['data' => $report]);
    }

    public function inventoryReport()
    {
        $this->authorize('view-reports');

        $report = $this->reportService->inventoryReport();

        return response()->json(['data' => $report]);
    }

    public function profitLossReport(Request $request)
    {
        $this->authorize('view-reports');

        $validated = $request->validate([
            'start_date' => 'required|date',
            'end_date' => 'required|date|after_or_equal:start_date',
        ]);

        $report = $this->reportService->profitLossReport(
            $validated['start_date'],
            $validated['end_date']
        );

        return response()->json(['data' => $report]);
    }

    public function productPerformance(Request $request)
    {
        $this->authorize('view-reports');

        $validated = $request->validate([
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ]);

        $report = $this->reportService->productPerformance(
            $validated['start_date'] ?? null,
            $validated['end_date'] ?? null
        );

        return response()->json(['data' => $report]);
    }

    // ── CSV Exports ───────────────────────────────────────────────────────────

    public function exportSales(Request $request)
    {
        $this->authorize('view-reports');

        $validated = $request->validate([
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after_or_equal:start_date',
        ]);

        $report   = $this->reportService->salesReport($validated['start_date'], $validated['end_date']);
        $sales    = $report['sales'];
        $filename = 'sales_' . $validated['start_date'] . '_to_' . $validated['end_date'] . '.csv';

        $headers = [
            'Content-Type'        => 'text/csv; charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Cache-Control'       => 'no-cache, no-store, must-revalidate',
            'Pragma'              => 'no-cache',
            'Expires'             => '0',
        ];

        $callback = function () use ($sales, $report) {
            $handle = fopen('php://output', 'w');

            // Summary header rows
            fputcsv($handle, ['Report: Sales Summary']);
            fputcsv($handle, ['Total Orders',      $report['total_orders']]);
            fputcsv($handle, ['Total Sales (₦)',   number_format($report['total_sales'], 2)]);
            fputcsv($handle, ['Total Profit (₦)',  number_format($report['total_profit'], 2)]);
            fputcsv($handle, ['Total Discounts (₦)', number_format($report['total_discounts'], 2)]);
            fputcsv($handle, ['Average Order (₦)', number_format($report['average_order'], 2)]);
            fputcsv($handle, []);

            // Detail columns
            fputcsv($handle, ['Sale Number', 'Date', 'Customer', 'Items', 'Total (₦)', 'Profit (₦)']);

            foreach ($sales as $sale) {
                fputcsv($handle, [
                    $sale['sale_number'],
                    $sale['sale_date'],
                    $sale['customer']['name'] ?? 'Walk-in',
                    $sale['items_count'],
                    number_format($sale['total'], 2),
                    number_format($sale['profit'], 2),
                ]);
            }

            fclose($handle);
        };

        return response()->stream($callback, 200, $headers);
    }

    public function exportInventory(Request $request)
    {
        $this->authorize('view-reports');

        $report   = $this->reportService->inventoryReport();
        $products = $report['products'];
        $filename = 'inventory_' . now()->format('Y-m-d') . '.csv';

        $headers = [
            'Content-Type'        => 'text/csv; charset=UTF-8',
            'Content-Disposition' => "attachment; filename=\"{$filename}\"",
            'Cache-Control'       => 'no-cache, no-store, must-revalidate',
            'Pragma'              => 'no-cache',
            'Expires'             => '0',
        ];

        $callback = function () use ($products, $report) {
            $handle = fopen('php://output', 'w');

            // Summary header rows
            fputcsv($handle, ['Report: Inventory Valuation']);
            fputcsv($handle, ['Total Products',         $report['total_products']]);
            fputcsv($handle, ['Stock Value (₦)',        number_format($report['total_value'], 2)]);
            fputcsv($handle, ['Potential Revenue (₦)',  number_format($report['potential_revenue'], 2)]);
            fputcsv($handle, ['Potential Profit (₦)',   number_format($report['potential_profit'], 2)]);
            fputcsv($handle, ['Low Stock Count',        $report['low_stock_count']]);
            fputcsv($handle, ['Out of Stock Count',     $report['out_of_stock_count']]);
            fputcsv($handle, []);

            // Detail columns
            fputcsv($handle, [
                'Product', 'SKU', 'Category', 'Stock Qty', 'Unit',
                'Cost Price (₦)', 'Selling Price (₦)',
                'Stock Value (₦)', 'Potential Revenue (₦)', 'Status',
            ]);

            foreach ($products as $product) {
                $stockValue    = $product->cost_price * $product->stock_quantity;
                $potRevenue    = $product->selling_price * $product->stock_quantity;
                $isLow         = $product->stock_quantity > 0 && $product->stock_quantity <= $product->low_stock_threshold;
                $status        = $product->stock_quantity === 0 ? 'Out of Stock' : ($isLow ? 'Low Stock' : 'In Stock');

                fputcsv($handle, [
                    $product->name,
                    $product->sku ?? '',
                    $product->category->name ?? '',
                    $product->stock_quantity,
                    $product->unit ?? 'pcs',
                    number_format($product->cost_price, 2),
                    number_format($product->selling_price, 2),
                    number_format($stockValue, 2),
                    number_format($potRevenue, 2),
                    $status,
                ]);
            }

            fclose($handle);
        };

        return response()->stream($callback, 200, $headers);
    }

    // ── PDF Exports ───────────────────────────────────────────────────────────

    public function exportSalesPdf(Request $request)
    {
        $this->authorize('view-reports');

        $validated = $request->validate([
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after_or_equal:start_date',
        ]);

        $report = $this->reportService->salesReport($validated['start_date'], $validated['end_date']);

        $pdf = Pdf::loadView('reports.sales-pdf', [
            'report'        => $report,
            'start_date'    => $validated['start_date'],
            'end_date'      => $validated['end_date'],
            'appName'       => PlatformSetting::get('app_name', 'Inventino'),
            'appLogoBase64' => $this->logoBase64(),
        ])->setPaper('a4', 'landscape');

        $filename = 'sales_' . $validated['start_date'] . '_to_' . $validated['end_date'] . '.pdf';

        return $pdf->download($filename);
    }

    public function exportInventoryPdf(Request $request)
    {
        $this->authorize('view-reports');

        $report = $this->reportService->inventoryReport();

        $pdf = Pdf::loadView('reports.inventory-pdf', [
            'report'        => $report,
            'date'          => now()->format('Y-m-d'),
            'appName'       => PlatformSetting::get('app_name', 'Inventino'),
            'appLogoBase64' => $this->logoBase64(),
        ])->setPaper('a4', 'landscape');

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

        return $pdf->download($filename);
    }

    /** Returns a base64 data URI for the platform logo, or null if not set. */
    private function logoBase64(): ?string
    {
        $raw = PlatformSetting::get('app_logo', '');
        if (!$raw) return null;
        // Strip any accidental /storage/ prefix
        $raw = ltrim($raw, '/');
        if (str_starts_with($raw, 'storage/')) {
            $raw = substr($raw, 8);
        }
        if (!Storage::disk('public')->exists($raw)) return null;
        $bytes = Storage::disk('public')->get($raw);
        $mime  = mime_content_type(Storage::disk('public')->path($raw)) ?: 'image/jpeg';
        return 'data:' . $mime . ';base64,' . base64_encode($bytes);
    }
}
