<?php

namespace App\Http\Controllers\Seller;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Order;
use App\Models\LoadSheet;

class LoadSheetController extends Controller
{
    public function index(Request $request)
    {
        $query = LoadSheet::where('user_id', auth()->id())->withCount('orders');

        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('id', 'like', "%$search%")
                  ->orWhere('rider_name', 'like', "%$search%");
            });
        }

        $logs = $query->latest()->paginate(10);

        return view('seller.load-sheet.index', compact('logs'));
    }

    public function create(Request $request)
    {
        $query = Order::where('user_id', auth()->id())->where('status', 'Pending'); // Only pending orders can be added to a load sheet

        // Date filtering
        if ($request->filled('from_date')) {
            $query->whereDate('created_at', '>=', $request->get('from_date'));
        }
        if ($request->filled('to_date')) {
            $query->whereDate('created_at', '<=', $request->get('to_date'));
        }

        // Search filtering
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('tracking_id', 'like', "%$search%")
                  ->orWhere('recipient_name', 'like', "%$search%");
            });
        }

        $orders = $query->latest()->paginate(10);

        return view('seller.load-sheet.create', compact('orders'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'orders' => 'required|array|min:1',
            'rider_name' => 'required|string|max:255',
        ]);

        $loadSheet = LoadSheet::create([
            'user_id' => auth()->id(),
            'rider_name' => $request->input('rider_name'),
            'load_sheet_date' => now(),
        ]);

        Order::whereIn('id', $request->input('orders'))
            ->update(['load_sheet_id' => $loadSheet->id, 'status' => 'Booked']);

        return redirect()->route('seller.load-sheet.index')->with('success', 'Load sheet generated successfully.');
    }
}
