<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiController;
use App\Http\Requests\DigitalMenuStoreRequest;
use App\Http\Resources\PosFoodCategoryResource;
use App\Http\Resources\PosFoodItemResource;
use App\Http\Resources\PosModifierResource;
use App\Http\Resources\PosServiceTableResource;
use App\Http\Resources\PosTaxResource;
use App\Models\Customer;
use App\Models\FoodCategory;
use App\Models\FoodItem;
use App\Models\Modifier;
use App\Models\Sale;
use App\Models\ServiceTable;
use App\Models\Tax;
use App\Notifications\App\OnCollectionNotification;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Exception;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;


class TableMenuController extends ApiController
{

    public function collectOrder(DigitalMenuStoreRequest $request)
    {
        DB::beginTransaction();
        try {
            $validated = $this->handleRequestWithOrderType($request);
            // Set default values for optional fields
            $validated['order_taker_id'] = $validated['order_taker_id'] ?? 1;
            $validated['took_at'] = $validated['took_at'] ?? now()->toDateTimeString();
            $validated['uuid'] = Str::orderedUuid();
            $validated['tracking'] = $this->getTrackingIdentity();
            $email = Arr::get($validated, 'email', null);
            $phone = Arr::get($validated, 'phone', null);
            // create customer
            $customer = Customer::where('email',  $email)->orWhere('phone',  $phone)->first();
            if ($customer) {
                $validated['customer_id'] = $customer->id;
            } else {
                $customer = Customer::create([
                    'uuid' => Str::orderedUuid(),
                    'name' => $validated['name'],
                    'email' =>  $email,
                    'phone' =>  $phone,
                ]);
                $validated['customer_id'] = $customer->id;
            }

            if (config('app.modes.cashbooks')) {
                $validated['cash_book_id'] = $this->activeRegisterIdentityForDigitalMenu();
            }


            // Create the Sale record
            $sale = Sale::create($validated);
            $this->createSaleItemRecords($sale, $validated['items']);
            $sale->serviceTable()->update(['is_booked' => true]);
            $sale->customer->notify((new OnCollectionNotification($this->channelConfigs($sale->customer), $sale))
                ->locale(config('app.locale')));
            DB::commit();
            return response()->json([
                'message' => __('Order placed successfully'),
                'order' => $sale->tracking,
            ]);
        } catch (Exception $e) {
            DB::rollback();
            return response()->json(
                [
                    'error' => __('Something went wrong try again !'),
                    'message' => $e->getMessage(),
                ],
                422
            );
        }
    }

    public function products(Request $request): JsonResponse
    {
        $sort = $this->sort($request);
        $items = FoodItem::filter($request->all())
            ->orderBy($sort['column'], $sort['order'])
            ->paginate((int) $request->get('perPage', 18));
        Artisan::call('optimize:clear');
        return response()->json(
            [
                'items' => PosFoodItemResource::collection($items->items()),
                'pagination' => $this->pagination($items),
            ]
        );
    }


    public function taxes(): JsonResponse
    {
        $taxes = Tax::get();
        return response()->json(PosTaxResource::collection($taxes));
    }

    public function serviceTables(): JsonResponse
    {
        $tables = ServiceTable::get();
        return response()->json(PosServiceTableResource::collection($tables));
    }

    public function modifiers(): JsonResponse
    {
        $modifiers = Modifier::get();
        return response()->json(PosModifierResource::collection($modifiers));
    }

    public function categories(Request $request): JsonResponse
    {
        $categories = FoodCategory::get();
        return response()->json(PosFoodCategoryResource::collection($categories));
    }
}
