<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreSaleRequest;
use App\Models\Party;
use App\Models\Yarn;
use App\Models\Sale;
use App\Services\SaleService;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;

class SaleController extends Controller
{
    public function __construct(
        protected SaleService $saleService,
        protected ActivityLogService $log
    ) {
    }

    public function index(Request $request)
    {
        $sales = $this->saleService->getFiltered($request);
        $totals = $this->saleService->getTotals($sales);

        return view('sales.index', compact('sales', 'totals'));
    }

    public function create()
    {
        $customers = Party::customers()->active()->orderBy('name')->get();
        $yarns = Yarn::active()->orderBy('name')->get();

        return view('sales.create', compact('customers', 'yarns'));
    }

    public function store(StoreSaleRequest $request)
    {
        $sale = $this->saleService->create($request->validated());
        $this->log->log('created', 'sale', $sale, "Sale {$sale->voucher_no} created");

        return redirect()
            ->route('sales.show', $sale->id)
            ->with('success', "Sale {$sale->voucher_no} created successfully.");
    }

    public function show(Sale $sale)
    {
        $sale->load(['party', 'items.yarn', 'creator']);

        return view('sales.show', compact('sale'));
    }

    public function edit(Sale $sale)
    {
        $sale->load(['party', 'items.yarn']);
        $customers = Party::customers()->active()->orderBy('name')->get();
        $yarns = Yarn::active()->orderBy('name')->get();

        return view('sales.edit', compact('sale', 'customers', 'yarns'));
    }

    public function update(StoreSaleRequest $request, Sale $sale)
    {
        $old = $sale->toArray();
        $this->saleService->update($sale, $request->validated());
        $this->log->log('updated', 'sale', $sale, "Sale {$sale->voucher_no} updated", $old, $sale->fresh()->toArray());

        return redirect()
            ->route('sales.show', $sale->id)
            ->with('success', "Sale {$sale->voucher_no} updated successfully.");
    }

    public function destroy(Sale $sale)
    {
        $vno = $sale->voucher_no;
        $sale->delete();
        $this->log->logAction('deleted', 'sale', Sale::class, $sale->id, "Sale {$vno} deleted");

        return redirect()
            ->route('sales.index')
            ->with('success', 'Sale deleted successfully.');
    }
}
