<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Purchase;
use App\Models\Sale;
use App\Models\StockMovement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ReportController extends Controller
{
    /**
     * GET /api/reports/sales
     */
    public function sales(Request $request)
    {
        $request->validate([
            'date_from'    => ['required', 'date'],
            'date_to'      => ['required', 'date', 'after_or_equal:date_from'],
            'channel'      => ['nullable', 'string', 'max:100'],
            'warehouse_id' => ['nullable', 'exists:warehouses,id'],
        ]);

        $sales = Sale::with(['user:id,name', 'items', 'warehouse:id,code,name'])
            ->whereDate('created_at', '>=', $request->date_from)
            ->whereDate('created_at', '<=', $request->date_to)
            ->when($request->channel, fn($q) => $q->where('channel', $request->channel))
            ->when($request->warehouse_id, fn($q) => $q->where('warehouse_id', $request->warehouse_id))
            ->whereNull('voided_at')
            ->latest()
            ->get();

        $summary = [
            'total_orders'   => $sales->count(),
            'total_revenue'  => $sales->sum('total'),
            'by_channel'     => $sales->groupBy('channel')->map(fn($g) => [
                'count'   => $g->count(),
                'revenue' => $g->sum('total'),
            ]),
            'by_status'      => $sales->groupBy(fn($s) => 'completed')->map(fn($g) => $g->count()),
        ];

        return response()->json([
            'summary' => $summary,
            'data'    => $sales->map(fn($s) => [
                'id'             => $s->id,
                'order_no'       => $s->order_no,
                'channel'        => $s->channel,
                'customer_name'  => $s->customer_name,
                'operator_name'  => $s->user?->name ?? 'Unknown',
                'warehouse_name' => $s->warehouse?->name ?? '-',
                'status'         => 'completed',
                'total'          => $s->total,
                'subtotal'       => $s->subtotal,
                'tax_amount'     => $s->tax_amount,
                'service_amount' => $s->service_amount,
                'items_count'    => $s->items->count(),
                'created_at'     => $s->created_at->toISOString(),
                'items'          => $s->items->map(fn($i) => [
                    'product_name' => $i->product_name,
                    'qty'          => $i->qty,
                    'price'        => $i->price,
                ]),
            ]),
        ]);
    }

    /**
     * GET /api/reports/purchases
     */
    public function purchases(Request $request)
    {
        $request->validate([
            'date_from'    => ['required', 'date'],
            'date_to'      => ['required', 'date', 'after_or_equal:date_from'],
            'warehouse_id' => ['nullable', 'exists:warehouses,id'],
        ]);

        $purchases = Purchase::with(['user:id,name', 'items', 'warehouse:id,code,name'])
            ->whereDate('created_at', '>=', $request->date_from)
            ->whereDate('created_at', '<=', $request->date_to)
            ->when($request->warehouse_id, fn($q) => $q->where('warehouse_id', $request->warehouse_id))
            ->latest()
            ->get();

        $summary = [
            'total_po'      => $purchases->count(),
            'total_spend'   => $purchases->whereIn('status', ['received', 'partial'])->sum('total'),
            'by_status'     => $purchases->groupBy('status')->map(fn($g) => $g->count()),
        ];

        return response()->json([
            'summary' => $summary,
            'data'    => $purchases->map(fn($p) => [
                'id'             => $p->id,
                'po_number'      => $p->po_number,
                'supplier_name'  => $p->supplier_name,
                'operator_name'  => $p->user?->name ?? 'Unknown',
                'warehouse_name' => $p->warehouse?->name ?? '-',
                'status'         => $p->status,
                'total'          => $p->total,
                'expected_date'  => $p->expected_date?->toDateString(),
                'created_at'     => $p->created_at->toISOString(),
            ]),
        ]);
    }

    /**
     * GET /api/reports/movements
     */
    public function movements(Request $request)
    {
        $request->validate([
            'date_from'    => ['required', 'date'],
            'date_to'      => ['required', 'date', 'after_or_equal:date_from'],
            'type'         => ['nullable', 'in:in,out,adjustment'],
            'warehouse_id' => ['nullable', 'exists:warehouses,id'],
        ]);

        $movements = StockMovement::with(['user:id,name', 'warehouse:id,code,name'])
            ->whereDate('created_at', '>=', $request->date_from)
            ->whereDate('created_at', '<=', $request->date_to)
            ->when($request->type, fn($q) => $q->where('type', $request->type))
            ->when($request->warehouse_id, fn($q) => $q->where('warehouse_id', $request->warehouse_id))
            ->latest()
            ->get();

        $summary = [
            'total_in'         => $movements->where('type', 'in')->sum('qty'),
            'total_out'        => $movements->where('type', 'out')->sum('qty'),
            'total_adjustment' => $movements->where('type', 'adjustment')->count(),
        ];

        return response()->json([
            'summary' => $summary,
            'data'    => $movements->map(fn($m) => [
                'id'             => $m->id,
                'product_name'   => $m->product_name,
                'sku'            => $m->sku,
                'type'           => $m->type,
                'reason'         => $m->reason,
                'notes'          => $m->notes,
                'qty'            => $m->qty,
                'stock_before'   => $m->stock_before,
                'stock_after'    => $m->stock_after,
                'reference_no'   => $m->reference_no,
                'user_name'      => $m->user?->name ?? 'System',
                'warehouse_name' => $m->warehouse?->name ?? '-',
                'created_at'     => $m->created_at->toISOString(),
            ]),
        ]);
    }
}
