<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\CabinClass;
use App\Models\AdminNotification;
use App\Events\AdminNotificationEvent;

use App\Models\Document;


class CabinController extends Controller
{
    public function __construct()
    {
        //
        $this->middleware('auth:api');

        $api_user = auth()->guard('api')->user();

        if (!$api_user)
        {
            return response()->json(['error' => 'Unauthorized.'], 401);
        }

    }

    public function delete($id, Request $request) {
        $user = auth()->guard('api')->user();
        $company = $user->company;

        # $cabin = CabinClass::find($id);
        $cabin = CabinClass::where('id', $id)->with('products')->first();

        if ($cabin->company_id != $company->id) {
            return response()->json(['error' => 'Unauthorized.'], 401);
        }

        if ($cabin) {

            if (isset($cabin->products)) {
                foreach ($cabin->products as $k => $v) {
                    $document = Document::where('product_id', $v->id)->first();
                    if ($document) {
                        $document->product_id = null;
                        $document->save();
                    }
                }
            }

            $notification = AdminNotification::create(['cta_label' => 'View Company']);
            $notification->instigator_id = $user->id;
            $notification->message = $user->first_name.' '.$user->last_name.' deleted cabin class '.$cabin->name.' from '.$company->name.' and all '.$cabin->products->count().' product(s).';
            $notification->href = 'companies/'.$user->company->id;

            $notification->save();
            $notification->instigator = $user;
            event(new AdminNotificationEvent($notification));

            $cabin->products()->delete();
            $cabin->delete();
        }

        return response()->json(['success' => 'Cabin deleted successfully']);
    }
}
