<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SecondHandBuy;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SecondHandBuyController extends Controller
{
    public function index()
    {
        $secondHandBuys = SecondHandBuy::latest()->get();

        return Inertia::render('Admin/Pages/SecondHandBuys/Index', [
            'secondHandBuys' => $secondHandBuys,
        ]);
    }

    public function create()
    {
        return Inertia::render('Admin/Pages/SecondHandBuys/Create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'mobile_model' => 'required|string|max:255',
            'imei' => 'required|string|max:50',
            'buy_price' => 'required|numeric|min:0',
            'condition' => 'required|in:Good,Bad',
        ]);

        SecondHandBuy::create([
            'customer_name' => $request->customer_name,
            'phone_number' => $request->phone_number,
            'mobile_model' => $request->mobile_model,
            'imei' => $request->imei,
            'buy_price' => $request->buy_price,
            'condition' => $request->condition,
            'date' => today(),
        ]);

        return redirect()->route('admin.second-hand-buys.index');
    }

    public function edit(SecondHandBuy $secondHandBuy)
    {
        return Inertia::render('Admin/Pages/SecondHandBuys/Edit', [
            'secondHandBuy' => $secondHandBuy,
        ]);
    }

    public function update(Request $request, SecondHandBuy $secondHandBuy)
    {
        $request->validate([
            'customer_name' => 'required|string|max:255',
            'phone_number' => 'required|string|max:20',
            'mobile_model' => 'required|string|max:255',
            'imei' => 'required|string|max:50',
            'buy_price' => 'required|numeric|min:0',
            'condition' => 'required|in:Good,Bad',
        ]);

        $secondHandBuy->update($request->all());

        return redirect()->route('admin.second-hand-buys.index');
    }

    public function destroy(SecondHandBuy $secondHandBuy)
    {
        $secondHandBuy->delete();

        return redirect()->route('admin.second-hand-buys.index');
    }
}