<?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\User;
use App\Models\CabinClass;
use App\Models\Product;
use App\Models\Folder;
use App\Models\Document;
use App\Models\Company;
use App\Models\AdminNotification;
use App\Events\AdminNotificationEvent;

class CompanyController 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(Request $request) {

        $user = auth()->guard('api')->user();
        $company = Company::find($user->company_id);

        if ($company) {
            $company->delete();
            return response()->json(['success' => 'Company deleted successfully.'], 200);
        }
        else {
            return response()->json(['error' => 'Company not found.'], 404);
        }


    }

    public function show(Request $request) {
        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first();

        foreach ($company->cabinClasses as $cabinClass) {
            $cabinClass->products = Product::where('cabin_class_id', $cabinClass->id)->get();
        }

        if (!$company) {
            return response()->json(['error' => 'Company not found.'], 404);
        }

        return response()->json(['company' => $company], 200);
    }


    public function edit(Request $request) {

        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first();

        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:companies,name,'.$company->id
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        if (!$company) {
            return response()->json(['error' => 'Company not found.'], 404);
        }

        $company->name = $request->name;
        $company->save();

        foreach ($request->cabin_classes as $cabinClass) {
            $cabin = CabinClass::where('id', $cabinClass)->with('products')->first();

            if (!$cabin) {
                $cabin = CabinClass::create(['name' => $cabinClass['name']]);
                $cabin->company_id = $company->id;

                if (!Storage::disk('fake_s3')->exists($company->name.'/'.$cabin->name))
                {
                    Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name);

                    $folder = Folder::create([
                        'path' => $company->name.'/'.$cabin->name
                    ]);

                    $folder->parent_id = $company->folder_id;
                    $folder->company_id = $company->id;

                    $folder->save();
                }
            }

            $cabin->save();


            foreach ($cabinClass['products'] as $cabinProduct) {

                $product = isset($cabinProduct['id']) ? Product::find($cabinProduct['id']) : null;

                if (!$product && $cabinProduct['serial_number'] != '')
                {

                    $check = Product::where([ 
                        ['serial_number', '=', $cabinProduct['serial_number']],
                        ['cabin_class_id', '=', $cabin->id],
                    ])->first();

                    // Check PN duplicato

                    if (!$check || $check) {

                        $p = new Product([
                            'serial_number' => $cabinProduct['serial_number'],
                            'cabin_class_id' => $cabin->id,
                            'user_id' => $user->id,
                            'active' => 0,
                            'user_first_name' => $user->first_name,
                            'user_last_name' => $user->last_name,
                        ]);
                        # $p = Product::create(['serial_number' => $product['serial_number']]);
                        # $p->cabin_class_id = $cabin->id;
                        # $p->save();
                        
                        $cabin->products()->save($p);

                        # $product = Product::create(['serial_number' => $cabinProduct['serial_number']]);
                        # $product->cabin_class_id = $cabin->id;
                        # $product->save();
                    }


                } else {
                    if ($cabinProduct['serial_number'] != '') {
                        $product->serial_number = $cabinProduct['serial_number'];
                        $product->save();
                    }
                }

            }
        }

        $notification = AdminNotification::create(['cta_label' => 'View Company']);
        $notification->instigator_id = $user->id;
        $notification->message = $user->first_name.' '.$user->last_name.' updated company '.$user->company->name.'.';
        $notification->href = 'companies/'.$user->company->id;

        $notification->save();

        $notification = $notification->toArray();
        $notification['instigator'] = $user;

        event(new AdminNotificationEvent($notification));

        return response()->json(['success' => 'Company updated successfully.']);
    }

    public function edit_deprecated(Request $request) {
        $user = auth()->guard('api')->user();
        $company = Company::where('id', $user->company_id)->with('cabinClasses')->with('users')->first();

        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:companies,name,'.$company->id
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        if (!$company) {
            return response()->json(['error' => 'Company not found.'], 404);
        }
        $company->name = $request->name;
        $company->save();

        foreach ($request->cabin_classes as $cabinClass) {
            $cabin = CabinClass::where('id', $cabinClass)->with('products')->first();

            if (!$cabin && $company->cabinClasses->count() < 4) {
                $cabin = CabinClass::create(['name' => $cabinClass['name']]);
                $cabin->company_id = $company->id;

                if (!Storage::disk('fake_s3')->exists($company->name.'/'.$cabin->name))
                {
                    Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name);

                    $folder = Folder::create([
                        'path' => $company->name.'/'.$cabin->name
                    ]);

                    $folder->parent_id = $company->folder_id;

                    $folder->save();
                }

                $cabin->save();
            }

            foreach ($cabinClass['products'] as $cabinProduct) {

                $product = isset($cabinProduct['id']) ? Product::find($cabinProduct['id']) : null;

                if (!$product && $cabinProduct['serial_number'] != '')
                {
                    $product = Product::create(['serial_number' => $cabinProduct['serial_number'], 'user_id' => $user->id, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name]);
                    $product->cabin_class_id = $cabin->id;
                }

                $product->save();
            }
        }
        $notification = AdminNotification::create(['cta_label' => 'View Company']);
        $notification->instigator_id = $user->id;
        $notification->message = $user->first_name.' '.$user->last_name.' updated company '.$user->company->name.'.';
        $notification->href = 'companies/'.$user->company->id;

        $notification->save();

        $notification = $notification->toArray();
        $notification['instigator'] = $user;

        event(new AdminNotificationEvent($notification));

        return response()->json(['success' => 'Company updated successfully.']);
    }

    public function create(Request $request) {

        $validator = Validator::make($request->all(), [
            'name' => 'required|unique:companies'
        ]);

        if ($validator->fails()) {
            throw new ValidationException($validator);
        }

        $company = Company::create([
            'name' => $request->name
        ]);

        Storage::disk('fake_s3')->makeDirectory($company->name);

        $path = $company->name;
        $companyFolder = Folder::create(['path' => $path]);
        $company->folder_id = $companyFolder->id;
        $company->save();

        $cabinClasses = $request->cabin_classes;

        foreach ($cabinClasses as $cabinClass) {
            $cabin = CabinClass::create([
                'name' => $cabinClass['name']
            ]);

            $cabin->company_id = $company->id;

            if (!Storage::disk('fake_s3')->makeDirectory($company->name.'/'.$cabin->name))
            {
                return response()->json(['error' => 'Could not create folder'], 500);
            }

            $folder = Folder::create([
                'path' => $company->name.'/'.$cabin->name
            ]);
            $folder->parent_id = $companyFolder->id;

            $folder->save();
            $cabin->save();


            $products = $cabinClass['products'];

            foreach ($products as $product) {
                if ($product['serial_number'] != '') {
                    
                    $p = Product::create([
                        'serial_number' => $product['serial_number']
                    ]);

                    $p->cabin_class_id = $cabin->id;
                    $p->save();
                }
            }

        }

        $notification = AdminNotification::create(['cta_label' => 'View Folder']);
        $notification->instigator_id = $user->id;
        $notification->message = $user->first_name.' '.$user->last_name.' created company '.$company->name.' with '.$cabinClasses->count().' cabin classes.';
        $notification->href = 'documents/folder/'.$user->company->folder_id;

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

        return response()->json(['success' => 'Company created successfully', 'company' => $company]);

    }

    public function linkUser(Request $request) {
        $company = Company::find($request->company_id);
        $user = User::find($request->user_id);

        if (!$company || !$user) {
            return response()->json(['error' => 'Resource not found.'], 404);
        }

        $user->company_id = $company->id;
        $user->save();

        return response()->json(['success' => 'User linked successfully.'], 200);
    }

    public function unlinkUser(Request $request) {
        $user = User::find($request->user_id);

        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        $user->company_id = null;
        $user->save();

        return response()->json(['success' => 'User unlinked successfully.'], 200);
    }

}
