<?php

namespace App\Http\Controllers\admin;

use App\Exports\OrdersExportkoombiyo;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class koombiyoreportController extends Controller
{
    public function koombiyodashboard(){
     return view('admin.koombiyo.koombiyoreport');
    }
  public function downloadReport(Request $request)
{
       $request->validate([
        'start_date' => 'required|date',
        'end_date' => 'required|date|after_or_equal:start_date',
        'report_type' => 'required|in:excel,csv'
    ]);

    $query = Order::with('productData') // Eager load relationships if needed
                ->whereBetween('created_at', [
                    $request->start_date,
                    Carbon::parse($request->end_date)->endOfDay()
                ]);

    if ($request->has('status') && $request->status !== 'all') {
        switch ($request->status) {
            case 'processing':
                $query->where('processing', 1)->where('ready', 0)->where('picked', 0)->where('on_the_way', 0)->where('delivered', 0)->where('cancellation', 0);
                break;
            case 'ready':
                $query->where('processing', 1)->where('ready', 1)->where('picked', 0)->where('on_the_way', 0)->where('delivered', 0)->where('cancellation', 0);
                break;
            case 'picked':
                $query->where('processing', 1)->where('ready', 1)->where('picked', 1)->where('on_the_way', 0)->where('delivered', 0)->where('cancellation', 0);
                break;
            case 'on_the_way':
                $query->where('processing', 1)->where('ready', 1)->where('picked', 1)->where('on_the_way', 1)->where('delivered', 0)->where('cancellation', 0);
                break;
            case 'delivered':
                $query->where('delivered', 1)->where('cancellation', 0);
                break;
            case 'cancelled':
                $query->where('cancellation', 1);
                break;
        }
    }

    $orders = $query->get();

    $fileName = 'orders_' . $request->start_date . '_to_' . $request->end_date;

    if ($request->report_type === 'excel') {
        return Excel::download(new OrdersExportkoombiyo($orders), $fileName . '.xlsx');
    }

    return Excel::download(new OrdersExportkoombiyo($orders), $fileName . '.csv', \Maatwebsite\Excel\Excel::CSV);

}
}
