<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Helpers\onesignalhelper;
use App\Models\IamPrincipal;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use App\Models\ManageRestaurant;
use App\Models\RedeemRestaurant;

class ReinstateRestaurant extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:reinstate-restaurant';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'The Command will reinstate the voucher after 4 hour';

    /**
     * Execute the console command.
     */

 public function handle()
 {
     try {
         $recordsToUpdate = RedeemRestaurant::where('is_redeem', 1)->get();

         foreach ($recordsToUpdate as $record) {
             //find restaurant
             $managerestaurant = ManageRestaurant::where('id', $record->manage_restaurants_xid)->first();

             $customerData = IamPrincipal::where('id', $record->iam_principal_xid)->where('notification_status', 1)->where('principal_type_xid',3)->first(); //fetch customer

             if ($managerestaurant && $managerestaurant->is_active == 1) {
                 $redeemDate = Carbon::parse($record->redeem_date);

                 $fourHourPlusTimeOfRecord = $redeemDate->copy()->addHours(4);

                 $currentTime = Carbon::now();

                 if ($currentTime > $fourHourPlusTimeOfRecord) {
                     $record->update([
                         'is_redeem' => 0,
                         'redeem_date' => null,
                         'count' => $record->count + 1,
                         'is_redeemption_undone' => 0,
                         'redeemption_undone_date' => null,
                     ]);
                     $restImage = ListingImageUrl('restaurant_images',  $managerestaurant->image);
                     $title = "Your " . $managerestaurant->name . " Reinstate  successfully";
                     $message = "Your " . $managerestaurant->name . " Reinstate  successfully";
                     $content_type = 'Restaurant Reinstate';
                     $imageUrl = $restImage;

                     onesignalhelper::sendNotificationApi(
                         $customerData->one_signal_player_id,
                         $title,
                         $message,
                         $content_type,
                         $imageUrl,
                         $id = null
                     );
                     Log::info('Reinstate of record done at ' . now());

                     onesignalhelper::StoreNotificationDetails($customerData->id, $content_type, $title, $restImage);
                 }
             }
         }

         Log::info('Reinstate task ran successfully at ' . now());
     } catch (\Exception $e) {
         Log::error('Reinstate function failed: ' . $e->getMessage());
     }

 }


}
