<?php

namespace App\Http\Controllers;

use App\Models\Vendor;
use Illuminate\Http\Request;

class VendorController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(\Illuminate\Http\Request $request): \Inertia\Response
    {
        $query = Vendor::query();

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('code', 'like', "%{$search}%")
                  ->orWhere('tax_id', 'like', "%{$search}%")
                  ->orWhere('owner', 'like', "%{$search}%")
                  ->orWhere('contact_name', 'like', "%{$search}%");
            });
        }

        $sortField = $request->input('sort_field', 'id');
        $sortDirection = $request->input('sort_direction', 'desc');

        $allowedSorts = ['id', 'code', 'name', 'owner', 'contact_name', 'phone'];
        if (!in_array($sortField, $allowedSorts)) {
            $sortField = 'id';
        }
        if (!in_array(strtolower($sortDirection), ['asc', 'desc'])) {
            $sortDirection = 'desc';
        }

        $perPage = $request->input('per_page', 10);

        $vendors = $query->orderBy($sortField, $sortDirection)
            ->paginate($perPage)
            ->withQueryString();

        return \Inertia\Inertia::render('Vendor/Index', [
            'vendors' => $vendors,
            'filters' => $request->only(['search', 'sort_field', 'sort_direction', 'per_page']),
        ]);
    }

    /**
     * Display the specified resource.
     */
    public function show(Vendor $vendor): \Inertia\Response
    {
        $vendor->load(['products.baseUnit', 'products.largeUnit']);
        return \Inertia\Inertia::render('Vendor/Show', [
            'vendor' => $vendor,
            'products' => \App\Models\Product::with('baseUnit')->get(),
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(\Illuminate\Http\Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'short_name' => 'nullable|string|max:255',
            'tax_id' => 'nullable|string|max:8',
            'owner' => 'nullable|string|max:255',
            'contact_name' => 'nullable|string|max:255',
            'tel' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'remark' => 'nullable|string',
        ]);

        // Auto-generate code
        $prefix = 'V';
        $lastVendor = Vendor::latest('id')->first();
        $nextId = $lastVendor ? $lastVendor->id + 1 : 1;
        $code = $prefix . str_pad($nextId, 5, '0', STR_PAD_LEFT);

        $validated['code'] = $code;
        
        Vendor::create($validated);

        return redirect()->back()->with('success', '廠商已建立');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(\Illuminate\Http\Request $request, Vendor $vendor)
    {
         $validated = $request->validate([
            'name' => 'required|string|max:255',
            'short_name' => 'nullable|string|max:255',
            'tax_id' => 'nullable|string|max:8',
            'owner' => 'nullable|string|max:255',
            'contact_name' => 'nullable|string|max:255',
            'tel' => 'nullable|string|max:50',
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:255',
            'address' => 'nullable|string',
            'remark' => 'nullable|string',
        ]);

        $vendor->update($validated);

        return redirect()->back()->with('success', '廠商資料已更新');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Vendor $vendor)
    {
        $vendor->delete();

        return redirect()->back()->with('success', '廠商已刪除');
    }
}
