<?php

namespace App\Http\Controllers;

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

class CSC extends Controller
{
    // Display all car sales
    public function index()
    {
        $carSales = Car::orderBy('id', 'desc')->get();
        return view('cars.index2', compact('carSales'));
    }

    // Show a single car sale
    public function show($id)
    {
        $sale = Car::findOrFail($id);
        return view('cars.show', compact('sale'));
    }

    // Edit a car sale
    public function edit($id)
    {
        $sale = Car::findOrFail($id);
        return view('cars.edit', compact('sale'));
    }

    // Update the car sale
    public function update(Request $request, $id)
    {
        $request->validate([
            'registration_no' => 'required',
            'make' => 'required',
            'model' => 'required',
            'seller_name' => 'required',
            'buyer_name' => 'required',
            'soled_price' => 'required|numeric',
            'remaining_payment' => 'required|numeric',
            'date' => 'required|date',
        ]);

        $sale = Car::findOrFail($id);
        $sale->update($request->all());

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

    // Delete a car sale
    public function destroy($id)
    {
        $sale = Car::findOrFail($id);
        $sale->delete();

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

    // Optional: Print invoice
    public function print($id)
    {
        $sale = Car::findOrFail($id);
        return view('cars.print', compact('sale'));
    }
}
