<?php

namespace App\Http\Controllers\Franchise;

use App\Http\Controllers\Controller;
use App\Models\Franchise;
use App\Models\Order;
use Illuminate\Contracts\View\View;
use Illuminate\Http\Response;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;

class SalesController extends Controller
{
    public function index(): View
    {
        $franchise = Franchise::query()->where('created_by', auth()->id())->first();

        $orders = new LengthAwarePaginator([], 0, 20);
        if ($franchise) {
            $orders = Order::query()
                ->where('franchise_id', $franchise->id)
                ->where('order_type', 'franchise')
                ->latest('id')
                ->paginate(20);
        }

        return view('franchise.sales', [
            'franchise' => $franchise,
            'orders' => $orders,
        ]);
    }

    public function invoice(Order $order): Response
    {
        $franchise = Franchise::query()->where('created_by', auth()->id())->first();
        if (! $franchise || $order->franchise_id !== $franchise->id) {
            abort(403);
        }

        $order->load('items.product', 'user');

        return response()->view('franchise.invoice', compact('order', 'franchise'));
    }
}
