<?php

namespace App\Http\Controllers\Admin;

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\Document;

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

        $adminUser = auth()->guard('admin')->user();

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

    }

    public function delete($id, Request $request) {
        # $cabin = CabinClass::find($id);
        $cabin = CabinClass::where('id', $id)->with('products')->first();

        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();
                    }
                }
            }

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

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

}
