<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use Illuminate\Http\Request;
use App\Models\History;
use App\Models\Service;
use Carbon\Carbon;

class HistoryController extends Controller
{
           public function index(Request $request)
    {
        $search = $request->query('search');
        $startDate = $request->query('start_date');
        $endDate = $request->query('end_date');

        $query = History::with(['services.stock']) // Eager load services with stock
            ->join('customer', 'customer.id', '=', 'history.customer_id')
            ->join('employee', 'employee.id', '=', 'history.employee_id')
            ->select('history.*', 'employee.nama as nama_pegawai', 'customer.nama', 'customer.telp');

        if ($search) {
            $query->where(function ($query) use ($search) {
                $query->where('customer.nama', 'like', '%' . $search . '%')
                      ->orWhere('history.no_polisi', 'like', '%' . $search . '%')
                      ->orWhere('employee.nama', 'like', '%' . $search . '%');
            });
        }

        if ($startDate) {
            $query->whereDate('history.created_at', '>=', Carbon::parse($startDate));
        }

        if ($endDate) {
            $query->whereDate('history.created_at', '<=', Carbon::parse($endDate));
        }

        $history = $query->orderBy('history.created_at', 'DESC')->get();

        return view('history', compact('history'));
    }

    public function deleteHistory($id)
    {
        $data = History::where('id', $id)->first();
        $employee = Employee::where('id', $data->employee_id)->first();
        $employee->jumlah_kendaraan = $employee->jumlah_kendaraan - 1;
        $employee->save();
        Service::where('id_history', $id)->delete();
        $data->delete();
        return redirect(route('history.index'));
    }

    public function print($id)
    {
        $history = History::with(['services.stock'])
            ->join('customer', 'customer.id', 'history.customer_id')
            ->join('employee', 'employee.id', 'history.employee_id')
            ->select('history.*', 'employee.nama as nama_pegawai', 'customer.nama', 'customer.telp')
            ->where('history.id', $id)
            ->first();

        $data = Service::leftjoin('stock', 'stock.id', 'service.stock_id')
            ->where('id_history', $id)
            ->select('service.*', 'stock.nama_barang', 'stock.harga_barang')
            ->get();

        return view('service.print', compact('history', 'data'));
    }
}
