<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Traits\AdminAuthTrait;
use App\Http\Controllers\Traits\AdminCustomerTrait;
use App\Http\Controllers\Traits\AdminGeneralSettingTrait;
use App\Http\Controllers\Traits\ApplyCouponTrait;
use App\Http\Controllers\Traits\CouponTrait;
use App\Http\Controllers\Traits\CustomDomainRequestTrait;
use App\Http\Controllers\Traits\CustomerProfileTrait;
use App\Http\Controllers\Traits\HelperTrait;
use App\Http\Controllers\Traits\JsonResponseTrait;
use App\Http\Controllers\Traits\ModuleTrait;
use App\Http\Controllers\Traits\PlanTrait;
use App\Http\Controllers\Traits\SubModuleTrait;
use App\Http\Controllers\Traits\HelpDeskCategoryTrait;
use App\Http\Controllers\Traits\HelpDeskTrait;
use App\Http\Controllers\Traits\SearchTrait;
use App\Http\Controllers\Traits\StripeTrait;
use App\Http\Controllers\Traits\ValidationTrait;
use App\Http\Controllers\Traits\PayrollTrait;
use App\Http\Controllers\Traits\WHSQTrait;
use App\Http\Controllers\Traits\EmailTrait;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use GuzzleHttp\Client;
use App\Models\Notification;
use App\Services\NotificationPusherService;
use Illuminate\Support\Facades\Log;



class Controller extends BaseController
{
  use AuthorizesRequests,
    DispatchesJobs,
    ValidatesRequests,
    ValidationTrait,
    JsonResponseTrait,
    AdminAuthTrait,
    ModuleTrait,
    SubModuleTrait,
    PlanTrait,
    AdminCustomerTrait,
    HelpDeskCategoryTrait,
    AdminGeneralSettingTrait,
    SearchTrait,
    CustomDomainRequestTrait,
    HelpDeskTrait,
    CouponTrait,
    StripeTrait,
    ApplyCouponTrait,
    CustomerProfileTrait,
    PayrollTrait,
    WHSQTrait,
    HelperTrait,
    EmailTrait;
    
   
  // public function SendInstantEmail(array $params)
  // {
  //   # Microsoft Graph API endpoint
  //   $graphApiEndpoint = "https://graph.microsoft.com/v1.0";

  //   #--------------------------> Update Always according to Domain
  //   # Application and client credentials
  //   $clientId = '5b16e80a-9e3b-457e-917b-bc9b773119cf';
  //   $clientSecret = 'atA8Q~qipzcPx6tgXibz6Jj71Q9CoxAVsWnLRad9';
  //   $tenantId = '54e4c75f-6f16-4a69-9fea-f7ff38d433cf';
  //   $user_id = '43670095-b120-4f18-a376-a1ec25a1ed33';
  //   #--------------------------< Update Always according to Domain

  //   # Create a Guzzle HTTP client
  //   $client = new Client();

  //   # Get an access token
  //   $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token";
  //   $tokenResponse = $client->post($tokenEndpoint, [
  //     'form_params' => [
  //       'client_id' => $clientId,
  //       'client_secret' => $clientSecret,
  //       'scope' => 'https://graph.microsoft.com/.default',
  //       'grant_type' => 'client_credentials',
  //     ],
  //   ]);

  //   $accessToken = json_decode($tokenResponse->getBody())->access_token;

  //   # Send an email using Microsoft Graph API
  //   $sendEmailEndpoint = "$graphApiEndpoint/users/$user_id/sendMail";
  //   $sendEmailPayload = [
  //     'message' => [
  //       'subject' => $params['subject'],
  //       'body' => [
  //         'contentType' => 'HTML',
  //         'content' => $params['blade'],
  //       ],
  //       'toRecipients' => [
  //         [
  //           'emailAddress' => [
  //             'address' => $params['to'],
  //           ]
  //         ],
  //       ],

  //     ],
  //   ];

  //   try {
  //     $response = $client->post($sendEmailEndpoint, [
  //       'headers' => [
  //         'Authorization' => 'Bearer ' . $accessToken,
  //         'Accept' => 'application/json',
  //         'Content-Type' => 'application/json',
  //       ],
  //       'json' => $sendEmailPayload,
  //     ]);

  //     # Handle the response as needed
  //     return true;
  //   } catch (Exception $ex) {
  //     # Handle the response as needed
  //     return false;
  //   }
  // }

  public function save_notifications($title, $short_description, $sender_type, $sender_id, $receiver_type, $receiver_id, $type, $customer_id = null, $workspace_id = null)
  {
    // Create the notification in database
    $notification = Notification::create([
      'title' =>  $title,
      'short_description' =>  $short_description,
      'sender_id' =>  $sender_id,
      'sender_type' =>  $sender_type,
      'receiver_type' =>  $receiver_type,
      'receiver_id' =>  $receiver_id,
      'type' =>  $type,
      'read' =>  '0',
      'customer_id' => $customer_id,
      'workspace_id' => $workspace_id
    ]);

    // Send real-time push notification via Pusher
    $this->sendPusherNotification($notification);

    return $notification;
  }

  /**
   * Send real-time notification via Pusher
   *
   * @param Notification $notification
   * @return void
   */
  private function sendPusherNotification(Notification $notification)
  {
    try {
      $pusherService = new NotificationPusherService();
      
      $notificationData = [
        'id' => $notification->id,
        'title' => $notification->title,
        'short_description' => $notification->short_description,
        'sender_id' => $notification->sender_id,
        'sender_type' => $notification->sender_type,
        'receiver_id' => $notification->receiver_id,
        'receiver_type' => $notification->receiver_type,
        'type' => $notification->type,
        'customer_id' => $notification->customer_id,
        'workspace_id' => $notification->workspace_id,
        'created_at' => $notification->created_at
      ];

      // Send notification to specific user
      if ($notification->receiver_id && $notification->receiver_type) {
        $pusherService->sendNotificationToUser($notificationData);
      }
      
    } catch (\Exception $e) {
      // Log error but don't break the main flow
      Log::error('Failed to send Pusher notification: ' . $e->getMessage(), [
        'notification_id' => $notification->id,
        'error' => $e->getTraceAsString()
      ]);
    }
  }
}
