<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreYarnRequest;
use App\Models\Yarn;
use App\Services\ActivityLogService;
use Illuminate\Http\Request;

class YarnController extends Controller
{
    public function __construct(protected ActivityLogService $log) {}

    public function index(Request $request)
    {
        $query = Yarn::withCount(['purchaseItems', 'saleItems']);
        if ($request->search) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->search}%")
                  ->orWhere('code', 'like', "%{$request->search}%")
                  ->orWhere('category', 'like', "%{$request->search}%");
            });
        }
        if ($request->category) $query->where('category', $request->category);
        $yarns = $query->orderBy('name')->paginate(20)->withQueryString();
        return view('stock.yarns', compact('yarns'));
    }

    public function create()
    {
        return view('stock.yarn-form', ['yarn' => null]);
    }

    public function store(StoreYarnRequest $request)
    {
        $yarn = Yarn::create($request->validated());
        $this->log->log('created', 'yarn', $yarn, "Yarn {$yarn->name} created");
        return redirect()->route('yarn.index')->with('success', "Yarn {$yarn->name} created.");
    }

    public function show(Yarn $yarn)
    {
        $yarn->loadCount(['purchaseItems', 'saleItems']);
        $stockIn = (float) $yarn->stockLedgers()->sum('in_qty');
        $stockOut = (float) $yarn->stockLedgers()->sum('out_qty');
        $avgCost = $yarn->average_cost;
        return view('stock.yarn-show', compact('yarn', 'stockIn', 'stockOut', 'avgCost'));
    }

    public function edit(Yarn $yarn)
    {
        return view('stock.yarn-form', compact('yarn'));
    }

    public function update(StoreYarnRequest $request, Yarn $yarn)
    {
        $old = $yarn->toArray();
        $yarn->update($request->validated());
        $this->log->log('updated', 'yarn', $yarn, "Yarn {$yarn->name} updated", $old, $yarn->toArray());
        return redirect()->route('yarn.index')->with('success', "Yarn {$yarn->name} updated.");
    }

    public function destroy(Yarn $yarn)
    {
        $name = $yarn->name;
        $yarn->delete();
        $this->log->logAction('deleted', 'yarn', Yarn::class, $yarn->id, "Yarn {$name} deleted", ['name' => $name]);
        return back()->with('success', "Yarn {$name} deleted.");
    }

    public function restore($id)
    {
        $yarn = Yarn::onlyTrashed()->findOrFail($id);
        $yarn->restore();
        $this->log->log('restored', 'yarn', $yarn, "Yarn {$yarn->name} restored");
        return back()->with('success', "Yarn {$yarn->name} restored.");
    }

    public function forceDelete($id)
    {
        $yarn = Yarn::onlyTrashed()->findOrFail($id);
        $name = $yarn->name;
        $yarn->forceDelete();
        $this->log->logAction('force_deleted', 'yarn', Yarn::class, $id, "Yarn {$name} permanently deleted");
        return back()->with('success', "Yarn {$name} permanently deleted.");
    }
}
