<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\StockMovement;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\View\View;

/**
 * Stock movements ledger — read-only audit trail of every change. Filters
 * by store / type / date range / product search. Gated by `products.view`.
 */
class StockMovementController extends Controller
{
    /** Movement types the system writes; surfaced to the filter dropdown. */
    public const TYPES = [
        'opening', 'adjustment', 'sale', 'return',
        'purchase', 'transfer_out', 'transfer_in',
    ];

    public function index(Request $request): View
    {
        $this->authorize('viewAny', StockMovement::class);

        $storeId = enforce_store_access($request->integer('store_id') ?: current_store_id());
        $type    = (string) $request->query('type', '');
        $from    = $request->query('from');
        $to      = $request->query('to');
        $q       = trim((string) $request->query('q', ''));

        $movements = StockMovement::query()
            ->with(['product:id,sku,name', 'variant:id,sku,attributes', 'store:id,name', 'creator:id,name'])
            ->when($storeId, fn ($qb) => $qb->where('store_id', $storeId))
            ->when($type !== '' && in_array($type, self::TYPES, true), fn ($qb) => $qb->where('type', $type))
            ->when($from, fn ($qb) => $qb->whereDate('created_at', '>=', $from))
            ->when($to,   fn ($qb) => $qb->whereDate('created_at', '<=', $to))
            ->when($q !== '', function ($qb) use ($q) {
                $qb->whereHas('product', fn ($pq) =>
                    $pq->where('name', 'like', "%{$q}%")->orWhere('sku', 'like', "%{$q}%"));
            })
            ->orderByDesc('created_at')
            ->orderByDesc('id')
            ->get();

        $stores = accessible_stores();

        $trimQty = fn ($v) => rtrim(rtrim(number_format((float) $v, 4, '.', ''), '0'), '.') ?: '0';
        $summaryCards = [
            ['label' => __('inventory.movements.summary.count'), 'value' => number_format($movements->count())],
            ['label' => __('inventory.movements.summary.in'),    'value' => $trimQty($movements->where('quantity_delta', '>', 0)->sum('quantity_delta')), 'tone' => 'positive'],
            ['label' => __('inventory.movements.summary.out'),   'value' => $trimQty(abs((float) $movements->where('quantity_delta', '<', 0)->sum('quantity_delta'))), 'tone' => 'danger'],
        ];

        return view('admin.inventory.movements.index', [
            'movements'    => $movements,
            'summaryCards' => $summaryCards,
            'stores'       => $stores,
            'types'        => self::TYPES,
            'filters'      => compact('storeId', 'type', 'from', 'to', 'q'),
        ]);
    }
}
