<?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\Company;
use App\Models\Product;
use App\Models\AdminNotification;
use App\Events\AdminNotificationEvent;
use App\Models\EmailQueue;
use App\Models\Admin;


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

        if ($product) {
            $cabin = CabinClass::find($product->cabin_class_id);
            if ($cabin->company_id == $user->company->id)
            {
                $notification = AdminNotification::create(['cta_label' => 'View Folder']);
                $notification->instigator_id = $user->id;
                $notification->message = $user->first_name.' '.$user->last_name.' deleted product '.$product->serial_number.' from '.$cabin->name.'.';
                $notification->href = 'documents/folder/'.$user->company->folder_id;

                $notification->save();

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

                $mail = EmailQueue::create([
                    'label' => 'PN / MCC (s) deleted',
                    'type' => '4',
                    'user_id' => $user->id,
                    'info' => $user->first_name.' '.$user->last_name.' deleted: '.$product->serial_number.' '.$cabin->name.' '.$user->company->name.'.',
                    'to' => $user->email
                ]);

                $product->delete();
            }
        }

        return response()->json(['success' => 'Product deleted successfully']);
    }
    
    public function update($id, Request $request) {
        $user = auth()->guard('api')->user();
        $product = Product::find($id);
        
        if (!$product) {
            return response()->json(['error' => 'Product not found'], 404);
        }
        
        $cabin = CabinClass::find($product->cabin_class_id);
        if (!$cabin || $cabin->company_id != $user->company->id) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        // Validate request
        $validator = Validator::make($request->all(), [
            'serial_number' => 'required|string|max:255',
        ]);
        
        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }
        
        // Store old serial number for notification
        $old_serial_number = $product->serial_number;
        $new_serial_number = $request->serial_number;
        
        // If the serial number hasn't changed, return early
        if ($old_serial_number === $new_serial_number) {
            return response()->json(['info' => 'No changes were made to the product']);
        }
        
        // Update product and set as inactive
        $product->serial_number = $new_serial_number;
        $product->active = 0; // Set to inactive
        $product->save();
        
        // Create notification for admin
        $notification = AdminNotification::create(['cta_label' => 'View Folder']);
        $notification->instigator_id = $user->id;
        $notification->message = $user->first_name.' '.$user->last_name.' modified product from '.$old_serial_number.' to '.$new_serial_number.' in '.$cabin->name.'.';
        $notification->href = 'documents/folder/'.$user->company->folder_id;
        $notification->save();
        
        $notification->instigator = $user;
        event(new AdminNotificationEvent($notification));
        
        // Get admin emails for notification
        $admins = Admin::all();
        $admin_emails = $admins->pluck('email')->toArray();
        
        // Add to email queue for each admin
        foreach ($admin_emails as $admin_email) {
            $mail_info = [
                'user_name' => $user->first_name.' '.$user->last_name,
                'company_name' => $user->company->name,
                'cabin_name' => $cabin->name,
                'old_pn' => $old_serial_number,
                'new_pn' => $new_serial_number
            ];
            
            EmailQueue::create([
                'label' => 'PN Modified',
                'type' => '5', // New type for PN modification
                'user_id' => $user->id,
                'info' => json_encode($mail_info),
                'to' => $admin_email
            ]);
        }
        
        return response()->json([
            'success' => 'Product updated successfully and set to inactive. It will be reviewed by an administrator.',
            'product' => $product
        ]);
    }
}
