<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\User;
use App\Models\EmailQueue;
use App\Models\Company;
use App\Models\CabinClass;
use App\Models\Product;
use App\Models\Folder;
use App\Models\AdminNotification;
use App\Events\AdminNotificationEvent;

class UserController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
        $this->middleware('auth:api');

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

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

    }


    public function create(Request $req) {

        $validator = Validator::make($req->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'company_name' => 'required',
            'email' => 'required|unique:users|email',
            'password' => 'required|min:6|confirmed'
        ]);

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

        $company = Company::where('name', $req->company_name)->first();

        $companyFolder = null;

        $cabinClasses = $req->cabin_classes;

        $user = User::create([
            'first_name' => $req->first_name,
            'last_name' => $req->last_name,
            'email' => $req->email,
            'password' => Hash::make($req->password)
        ]);

        if ($company)
        {
            $user->company_id = $company->id;
        } else {
            $company = Company::create(['name' => $req->company_name]);
            $user->company_id = $company->id;

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

            $path = $company->name;

            $companyFolder = Folder::create(['path' => $path]);

            $company->folder_id = $companyFolder->id;
            $companyFolder->company_id = $company->id;

            $company->save();
        }

        foreach($cabinClasses as $cabinClass) {
            if ($company->cabinClasses->count() <= 4 && array_key_exists('name', $cabinClass))
            {
                if($existing_company == 1){
                    $cabin = CabinClass::where([
                        ['name', $cabinClass['name'] ], 
                        ['company_id', $company->id] ]
                    )->first();
                }else{
                    $cabin = CabinClass::create(['name' => $cabinClass['name']]);
                }
                $cabin->company_id = $company->id;

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

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

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

                $folder->save();

                $cabin->save();

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

                    $p = Product::create(['serial_number' => $product['serial_number'], 'user_id' => $user->id, 'user_first_name' => $user->first_name, 'user_last_name' => $user->last_name]);

                    $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.' was created with company '.$company->name.' and '.$cabinClasses->count().' cabin classes.';
        $notification->href = 'documents/folder/'.$user->company->folder_id;

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

        $mail = EmailQueue::create([
            'label' => 'New Company',
            'type' => '1',
            'user_id' => $user->id,
            'info' => $user->first_name.' '.$user->last_name.' created a company '.$company->name.' and '.$cabinClasses->count().' cabin classes.',
            'to' => $user->email
        ]);

        //$user = User::create($req->only(['name', 'email']));
        $user->save();


        return response()->json($user);

    }

    public function edit(Request $request) {
        $user = auth()->guard('api')->user();

        $validator = Validator::make($request->all(), [
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required|unique:users,email,'.$user->id.'|email',
            'new_password' => 'min:6|confirmed'
        ]);

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

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

        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;

        if ($request->current_password && $request->new_password) {
            if (Hash::check($request->current_password, $user->password))
            {
                $user->password = Hash::make($request->new_password);
            } else {
                return response()->json(['error' => 'Invalid password'], 400);
            }
        }

        $user->save();

        return response()->json(['success' => 'User updated']);

    }

    public function delete($id, Request $request) {

        $user = User::find($id);

        $user->delete();
        return response()->json(['success' => 'User deleted successfully.'], 200);


    }

}
