<?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\User;
use App\Models\Product;
use App\Models\EmailQueue;


class ProductController 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) {
        $product = Product::find($id);

        if ($product) {
            
            if ($product->user_id != NULL) {
                
                $user = User::find($product->user_id);

                $mail = EmailQueue::create([
                    'label' => 'PN / MCC rejected',
                    'type' => '4',
                    'user_id' => $user->id,
                    'info' => '',
                    'to' => $user->email
                ]);

            }

            $product->delete();


        }

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

    public function activatePN(Request $request)
    {
        $all_pn_to_activate = $request->pn_list;

        foreach ($all_pn_to_activate as $key => $company) {

            foreach ($company['cabin_classes'] as $k => $cabin) {

                foreach ($cabin['products'] as $kk => $product) {

                    $product_obj = Product::find($product['id']);
                    if ($product_obj) {
                        if ($product['active'] != $product_obj->active) {
                            if ($product['active'] == true) {
                                $product_obj->active = 1;
                            }else{
                                $product_obj->active = 0;
                            }
                        }
                    }
                    $product_obj->save();    

                    
                }
            }

        }
        
        return response()->json(['info' => 'Products successfully activated'], 200);
    }


    public function countInactivePn(Request $request)
    {
        $all_inactive = Product::where('active', '<', 1)->get();
        $pn_count = 0;

        foreach ($all_inactive as $key => $value) {
            $pn_count = $pn_count+1;
        }
        return response()->json(['company_count' => count($all_inactive), 'product_count' => $pn_count ], 200);
    }
}
