<?php

namespace App\Http\Controllers\admin;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Lab;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class LabsController extends Controller
{
    public function index()
    {
        $labs = Lab::all();
        return view('admin.labs.index', ['labs' => $labs]);
    }
    public function create()
    {
        return view('admin.labs.create');
    }
    public function save(Request $request)
    {
        Lab::create([
            'name' => $request->name,
            'address' => $request->address,
            'city' => $request->city,
            'state' => $request->state,
            'zip_code' => $request->zip
        ]);
        return redirect('admin/labs');
    }
    public function edit($id)
    {
        $labEdit = Lab::find($id);
        return view('admin.labs.edit', ['labEdit' => $labEdit]);
    }
    public function update($id, Request $request)
    {
        $labEdit = Lab::find($id);
        $labEdit->name = $request->name;
        $labEdit->address = $request->address;
        $labEdit->city = $request->city;
        $labEdit->state = $request->state;
        $labEdit->zip_code = $request->zip;
        $labEdit->save();
        return redirect('admin/labs');
    }
    public function getOrderData(Request $request)
    {
        $perPage = $request->get('per_page', 20); // Items per page (default 10)

        // Get carts with patient data and order count
        $carts = Cart::with('patient')
            ->select('patient_id', DB::raw('COUNT(*) as cart_count'))
            ->groupBy('patient_id')
            ->paginate($perPage);

        // Manually create paginator instance (due to aggregation)
        $paginator = new LengthAwarePaginator(
            $carts->items(),
            $carts->total(),
            $perPage,
            $carts->currentPage()
        );

        return response()->json([
            'status' => 'Success',
            'orderData' => $paginator
        ], 200);
    }
}
