ÿØÿà JFIF      ÿÛ „ 	 ( %!1!%)+...383-7(-.+



-%%--------------------------------------------------ÿÀ  ·" ÿÄ               ÿÄ 6     !1AQa"q‘±ð¡ÁÑ2Bá#Rb‚ñr ÿÄ              ÿÄ $         !1A2Qaq‘Ñ"ÿÚ   ? óª4¦ù‡;ýÔ­aH6’
¯ëxòPº°pp-LæsÊÿ DÖ7:,ûž«ðwZÃ›-FÈ¨Øðf:‹ß¦šè¸*¹Û”Énó¯¿Âùó†ñ&¶£AiÌ39Ž‡ÙÛ”Ï.«ÜþÆ6³§PT$‚5ê‹žæçKw±Ñµ£¡û÷©a5¡9tDB„ÀAB B„€Lsá<¨ª±*p|à¹Þ8 ÜÅÿ 
C!sÜK"=Jæòï¾—Æ9í‰ŒÄNl×n¹ü[HÒ;÷W¸…Fîá ¼÷ôÕbbñRH6ëÓªÆZÒ¦*¤´óßÞû,ªµãen«š	ÓQ§—%B¸ßšèÌˆèÃˆ(UK«ù‰õ5L™ Æý#ïeàCˆÍ—cßèµx/Ä_,¹ ÎäLÍï~~¥?ê?1¡Ìs€ {·íÔÿ z—šŠ~sgsV8_þZ•n2‡7ôé•àë¾ ž–^³ð§¡@‡Ó€hÜÄÃB¼9ôCC^Òàóvº\"Ý ºßáßâ˜ÐÆºCt%½¬£c~ž«:Íû_å}ó†ŠV¯8øsãºn
ùà´ÿ ÚÇY]ßâ¬&›ƒ‚Öwß¬ë<]BªÀB€„ !	                                                                                                                                                                       
ÿØÿà JFIF      ÿÛ „ 	 ( %!1!%)+...383-7(-.+



-%%--------------------------------------------------ÿÀ  ·" ÿÄ               ÿÄ 6     !1AQa"q‘±ð¡ÁÑ2Bá#Rb‚ñr ÿÄ              ÿÄ $         !1A2Qaq‘Ñ"ÿÚ   ? óª4¦ù‡;ýÔ­aH6’
¯ëxòPº°pp-LæsÊÿ DÖ7:,ûž«ðwZÃ›-FÈ¨Øðf:‹ß¦šè¸*¹Û”Énó¯¿Âùó†ñ&¶£AiÌ39Ž‡ÙÛ”Ï.«ÜþÆ6³§PT$‚5ê‹žæçKw±Ñµ£¡û÷©a5¡9tDB„ÀAB B„€Lsá<¨ª±*p|à¹Þ8 ÜÅÿ 
C!sÜK"=Jæòï¾—Æ9í‰ŒÄNl×n¹ü[HÒ;÷W¸…Fîá ¼÷ôÕbbñRH6ëÓªÆZÒ¦*¤´óßÞû,ªµãen«š	ÓQ§—%B¸ßšèÌˆèÃˆ(UK«ù‰õ5L™ Æý#ïeàCˆÍ—cßèµx/Ä_,¹ ÎäLÍï~~¥?ê?1¡Ìs€ {·íÔÿ z—šŠ~sgsV8_þZ•n2‡7ôé•àë¾ ž–^³ð§¡@‡Ó€hÜÄÃB¼9ôCC^Òàóvº\"Ý ºßáßâ˜ÐÆºCt%½¬£c~ž«:Íû_å}ó†ŠV¯8øsãºn
ùà´ÿ ÚÇY]ßâ¬&›ƒ‚Öwß¬ë<]BªÀB€„ !	                                                                                                                                                                       
PK     u\qF  F    Rules/PhoneLength.phpnu [        <?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class PhoneLength implements ValidationRule
{
    protected $phoneCode;
    protected $phoneLengths;

    public function __construct($phoneCode)
    {
        $this->phoneCode = $phoneCode;
        $this->phoneLengths = $this->getPhoneLengths($phoneCode);
    }

    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $phoneLengths = $this->phoneLengths;

        if (!is_array($phoneLengths)){
            if (strlen($value) != $phoneLengths) {
                $fail("The $attribute length must be " . $phoneLengths . ' digits.');
            }
        } else {
            if (!in_array(strlen($value), $phoneLengths)) {
                $fail("The $attribute length must be one of " . implode(', ', $phoneLengths) . ' digits.');
            }
        }
    }

    private function getPhoneLengths($phoneCode)
    {
        $defaultLength = 15;

        foreach (config('country') as $country) {
            if ($country['phone_code'] == $phoneCode) {
                return $country['phoneLength'];
            }
        }

        return $defaultLength;
    }
}
PK     x\m    !  Rules/AlphaDashWithoutSlashes.phpnu [        <?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;


class AlphaDashWithoutSlashes implements ValidationRule
{
    /**
     * Run the validation rule.
     *
     * @param  \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString  $fail
     */
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        $result = preg_match('/^[a-z0-9_-]+$/i', $value) && !preg_match('/^-|-$/i', $value);

        if($result == false && $value != '/'){
            $fail( "Invalid :attribute. Slugs must consist of lowercase letters, numbers, hyphens, and underscores");
        }

    }

}
PK     x\      Console/Kernel.phpnu [        <?php

namespace App\Console;

use App\Console\Commands\AutoCurrencyUpdate;
use App\Console\Commands\CampaignCheck;
use App\Console\Commands\GatewayCurrencyUpdate;
use App\Console\Commands\PayoutCurrencyUpdateCron;
use App\Console\Commands\ReviewCount;
use App\Models\Deposit;
use App\Models\Order;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{


    protected $commands = [
        ReviewCount::class,
        CampaignCheck::class,
        GatewayCurrencyUpdate::class,
        PayoutCurrencyUpdateCron::class,
    ];

    /**
     * Define the application's command schedule.
     */
    protected function schedule(Schedule $schedule): void
    {
        $schedule->command('app:campaign-check')->everyMinute();
        $schedule->command('app:review-count')->hourly();
        $schedule->command('app:gateway-currency-update')->{basicControl()->currency_layer_auto_update_at}();
        $schedule->command('payout-currency:update')
            ->{basicControl()->currency_layer_auto_update_at}();
        $schedule->command('model:prune', [
            '--model' => [Deposit::class, Order::class],
        ])->daily();
    }

    /**
     * Register the commands for the application.
     */
    protected function commands(): void
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
PK     x\`       Console/Commands/ReviewCount.phpnu [        <?php

namespace App\Console\Commands;

use App\Models\Card;
use App\Models\Review;
use App\Models\TopUp;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Review and average review count';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        // Get all reviewable IDs for TopUp and Card in a single query
        $reviewableIds = DB::table('reviews')->where('status', 1)
            ->where('created_at', '>', Carbon::now()->subHours(2))
            ->whereIn('reviewable_type', [TopUp::class, Card::class])
            ->select('reviewable_id', 'reviewable_type')
            ->get()
            ->groupBy('reviewable_type');

        $topUpIds = isset($reviewableIds[TopUp::class]) ? $reviewableIds[TopUp::class]->pluck('reviewable_id')->toArray() : [];
        $cardIds = isset($reviewableIds[Card::class]) ? $reviewableIds[Card::class]->pluck('reviewable_id')->toArray() : [];

        $reviewStats = Review::selectRaw('reviewable_type, reviewable_id, COUNT(*) as total_reviews, AVG(rating) as average_rating')
            ->where('status', 1)
            ->whereIn('reviewable_type', [TopUp::class, Card::class])
            ->whereIn('reviewable_id', array_merge($topUpIds, $cardIds))
            ->groupBy('reviewable_type', 'reviewable_id')
            ->get()
            ->keyBy(function ($item) {
                return $item->reviewable_type . '_' . $item->reviewable_id;
            });

        DB::table('top_ups')->whereIn('id', $topUpIds)->get()->each(function ($topUp) use ($reviewStats) {
            $key = TopUp::class . '_' . $topUp->id;
            if (isset($reviewStats[$key])) {
                DB::table('top_ups')
                    ->where('id', $topUp->id)
                    ->update([
                        'total_review' => $reviewStats[$key]->total_reviews,
                        'avg_rating' => $reviewStats[$key]->average_rating,
                    ]);
            }
        });

        // Update Card records
        DB::table('cards')->whereIn('id', $cardIds)->get()->each(function ($card) use ($reviewStats) {
            $key = Card::class . '_' . $card->id;
            if (isset($reviewStats[$key])) {
                DB::table('cards')
                    ->where('id', $card->id)
                    ->update([
                        'total_review' => $reviewStats[$key]->total_reviews,
                        'avg_rating' => $reviewStats[$key]->average_rating,
                    ]);
            }
        });
    }
}
PK     x\=ºm  m  *  Console/Commands/GatewayCurrencyUpdate.phpnu [        <?php

namespace App\Console\Commands;

use App\Models\Gateway;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class GatewayCurrencyUpdate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:gateway-currency-update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if (basicControl()->currency_layer_auto_update == 1) {
            $gateways = Gateway::query();
            $paymentCurrencies = $gateways->pluck('currencies');

            $fiatCurrency = [];
            foreach ($paymentCurrencies as $key => $currency) {
                if (isset($currency->{'0'})) {
                    $currencyKeys = array_keys((array)$currency->{'0'});
                    $fiatCurrency = array_merge($fiatCurrency, $currencyKeys);
                }
            }

            $paymentCurrencies = $gateways->pluck('supported_currency')->flatMap(function ($currency) {
                return (array)$currency;
            })->unique()->toArray();

            $currencies = array_unique(array_intersect($fiatCurrency, $paymentCurrencies));

            $endpoint = 'live';
            $source = basicControl()->base_currency;
            $currency_layer_url = "http://api.currencylayer.com";
            $currency_layer_access_key = basicControl()->currency_layer_access_key;

            $currencyLists = array();
            foreach ($currencies as $currency) {
                $currencyLists[] = $currency;
            }

            $currencyLists = array_unique($currencyLists);
            $currencies = implode(',', $currencyLists);

            $CurrencyAPIUrl = "$currency_layer_url/$endpoint?access_key=$currency_layer_access_key&source=$source&currencies=$currencies";

            $response = Http::acceptJson()->get($CurrencyAPIUrl);

            $autoCurrencyUpdate = json_decode($response->body());

            $autoUp = [];
            foreach ($autoCurrencyUpdate->quotes as $key => $quote) {
                $strReplace = str_replace($autoCurrencyUpdate->source, '', $key);
                $autoUp[$strReplace] = $quote;
            }

            $usdToBase = 1.00;
            $currenciesArr = [];
            foreach ($gateways as $gateway) {
                foreach ($gateway->receivable_currencies as $key => $currency) {
                    foreach ($currency as $key1 => $item) {
                        $resRate = $this->getCheck($currency['name'], $autoUp);
                        $curRate = round($resRate / $usdToBase, 2);
                        if ($resRate && $key1 == 'conversion_rate') {
                            $currenciesArr[$key][$key1] = $curRate;
                        } else {
                            $currenciesArr[$key][$key1] = $item;
                        }
                    }
                }
                $gateways->receivable_currencies = $currenciesArr;
                $gateways->save();
            }
            return 0;
        }
    }

    public function getCheck($currency, $autoUp)
    {
        foreach ($autoUp as $key => $auto) {
            if ($key == $currency) {
                return $auto;
            }
        }
    }
}
PK     x\              Console/Commands/index.phpnu [        PK     x\⨏n  n  -  Console/Commands/PayoutCurrencyUpdateCron.phpnu [        <?php

namespace App\Console\Commands;

use App\Models\Currency;
use App\Models\PayoutMethod;
use Facades\App\Services\BasicCurl;
use Illuminate\Console\Command;

class PayoutCurrencyUpdateCron extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payout-currency:update';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'A command to payout fiat currency conversion rate update.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (basicControl()->currency_layer_auto_update == 1) {
            $endpoint = 'live';
            $currency_layer_access_key = basicControl()->currency_layer_access_key;

            $currency_layer_url = "http://api.currencylayer.com";
            $baseCurrency = basicControl()->base_currency_code;

            $source = 'USD';

            $payoutCurrencies = PayoutMethod::where('is_automatic', 1)->where('code', '!=', 'coinbase')->where('is_auto_update', 1)->pluck('supported_currency')->toArray();
            $currencyLists = array();
            foreach ($payoutCurrencies as $currency) {
                foreach ($currency as $singleCurrency) {
                    $currencyLists[] = $singleCurrency;
                }
            }
            $currencyLists = array_unique($currencyLists);
            $currencies = implode(',', $currencyLists);

            $updateForMethods = PayoutMethod::where('code', '!=', 'coinbase')->where('is_automatic', 1)->where('is_auto_update', 1)->get();

            $baseCurrencyAPIUrl = "$currency_layer_url/$endpoint?access_key=$currency_layer_access_key&source=$source&currencies=$baseCurrency";
            $allCurrencyAPIUrl = "$currency_layer_url/$endpoint?access_key=$currency_layer_access_key&source=$source&currencies=$currencies";

            $baseCurrencyConvert = BasicCurl::curlGetRequest($baseCurrencyAPIUrl);
            $allCurrencyConvert = BasicCurl::curlGetRequest($allCurrencyAPIUrl);

            $baseCurrencyConvert = json_decode($baseCurrencyConvert);
            $allCurrencyConvert = json_decode($allCurrencyConvert);

            if ($baseCurrencyConvert->success && $allCurrencyConvert->success) {

                if (empty($baseCurrencyConvert->quotes)) {
                    $usdToBase = 1.00;
                } else {
                    $usdToBase = (array)$baseCurrencyConvert->quotes;
                    $usdToBase = $usdToBase["$source$baseCurrency"];
                }

                foreach ($updateForMethods as $method) {
                    $addField = [];
                    foreach ($allCurrencyConvert->quotes as $key => $rate) {
                        $curCode = substr($key, -3);
                        $curRate = round($rate / $usdToBase, 2);

                        foreach ($method->supported_currency as $key => $currency) {
                            if ($key == 'USD') {
                                $addField['USD'] = round(1 / $usdToBase, 2);
                            }
                            if ($curCode == $key) {
                                $addField[$key] = $curRate;
                                break;
                            }
                        }
                    }
                    $method->convert_rate = $addField;
                    $method->save();
                }
            }
            return 0;
        }
    }
}
PK     x\b    "  Console/Commands/CampaignCheck.phpnu [        <?php

namespace App\Console\Commands;

use App\Models\Campaign;
use App\Models\CardService;
use App\Models\TopUpService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check Campaign is running or not';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $campaign = Campaign::firstOrNew();
        $today = Carbon::now();

        $topUpServices = TopUpService::whereNotNull('old_data')->orWhere('is_offered',1)->get();
        $this->applyCampaign($campaign, $topUpServices, $today);


        $cardServices = CardService::whereNotNull('old_data')->orWhere('is_offered',1)->get();
        $this->applyCampaign($campaign, $cardServices, $today);

    }

    protected function applyCampaign($campaign, $services, $today)
    {
        if ($campaign->status && $campaign->start_date <= $today && $campaign->end_date >= $today) {
            if (!empty($services)) {
                foreach ($services as $service) {
                    if($service->is_offered){
                        $this->oldDataStore($service);

                        if ($service->max_sell >= $service->offered_sell) {
                            $service->price = $service->campaign_data->price ?? $service->price;
                            $service->discount = $service->campaign_data->discount ?? $service->discount;
                            $service->discount_type = $service->campaign_data->discount_type ?? $service->discount_type;
                            $service->max_sell = $service->campaign_data->max_sell ?? $service->max_sell;

                            $service->is_offered = 1;
                            $service->save();
                        } else {
                            $this->setActualData($service);

                            $service->old_data = null;
                            $service->campaign_data = null;
                            $service->is_offered = 0;
                            $service->save();
                        }
                    }else{
                        $this->setActualData($service);

                        $service->old_data = null;
                        $service->campaign_data = null;
                        $service->is_offered = 0;
                        $service->save();
                    }
                }
            }
        } elseif ($campaign->end_date <= $today) {
            if (!empty($services)) {
                foreach ($services as $service) {

                    $this->setActualData($service);

                    $service->offered_sell = 0;
                    $service->old_data = null;
                    $service->campaign_data = null;
                    $service->is_offered = 0;
                    $service->save();
                }
            }
        } else {
            if (!empty($services)) {
                foreach ($services as $service) {
                    $this->setActualData($service);
                }
            }
        }

        return true;
    }

    protected function setActualData($service)
    {
        $service->price = $service->old_data->price ?? $service->price;
        $service->discount = $service->old_data->discount ?? $service->discount;
        $service->discount_type = $service->old_data->discount_type ?? $service->discount_type;
        $service->max_sell = $service->campaign_data->max_sell ?? $service->max_sell;

        $service->save();
    }

    protected function oldDataStore($service): void
    {
        if (!$service->old_data) {
            $oldData = [
                'price' => $service->price,
                'discount' => $service->discount,
                'discount_type' => $service->discount_type,
            ];

            $service->old_data = $oldData;
            $service->save();
        }
    }
}
PK     x\16    !  Events/UpdateUserNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UpdateUserNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $userId;

    public function __construct($userId)
    {
        $this->userId = $userId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return ['user-notification.' . $this->userId];
    }
}
PK     x\*    "  Events/UpdateAdminNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class UpdateAdminNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $adminId;

    /**
     * Create a new event instance.
     */
    public function __construct($adminId)
    {
        $this->adminId = $adminId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return ['admin-notification.' . $this->adminId];
    }
}
PK     x\"  "     Events/OfferChatNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class OfferChatNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $uuid;

    public function __construct($message,$uuid)
    {
        $this->message = $message;
        $this->uuid = $uuid;
    }

    public function broadcastOn()
    {
        return ['offer-chat-notification.' . $this->uuid];
    }

}
PK     x\u|8  8    Events/AdminNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;

class AdminNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $adminId;

    /**
     * Create a new event instance.
     */
    public function __construct($message, $adminId)
    {
        $this->message = $message;
        $this->adminId = $adminId;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn(): array
    {
        return ['admin-notification.' . $this->adminId];
    }
}
PK     x\uil  l    Events/UserNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    public $userId;

    public function __construct($message, $userId)
    {
        $this->message = $message;
        $this->userId = $userId;
    }

    public function broadcastOn()
    {
        return ['user-notification.' . $this->userId];
    }
}
PK     x\$<    &  Events/UpdateOfferChatNotification.phpnu [        <?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UpdateOfferChatNotification implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;


    public $uuid;

    public function __construct($uuid)
    {
        $this->uuid = $uuid;
    }


    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return ['offer-chat-notification.' . $this->uuid];
    }
}
PK     x\>,W      Exceptions/Handler.phpnu [        <?php

namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;

class Handler extends ExceptionHandler
{
    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }
}
PK     x\4  4    Scopes/EnsureCardIdScope.phpnu [        <?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class EnsureCardIdScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->addSelect('card_id');
    }
}
PK     x\c7  7    Scopes/EnsureTopUpIdScope.phpnu [        <?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class EnsureTopUpIdScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->addSelect('top_up_id');
    }
}
PK     x\"<  <     Scopes/EnsureCategoryIdScope.phpnu [        <?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class EnsureCategoryIdScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        $builder->addSelect('category_id');
    }
}
PK     x\Ğ    )  Http/Controllers/Api/CouponController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Order;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CouponController extends Controller
{
    use ApiValidation, Notify;

    public function coupons(){

        $data['coupons']  = Coupon::where(function ($query) {
            $query->whereNull('end_date')
                ->orWhere('end_date', '>', now());
        })->latest()->get();

        return response()->json($this->withSuccess($data));
    }

    public function couponApply(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'utr' => 'required|string|exists:orders,utr',
            'couponCode' => 'required|string|exists:coupons,code',
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }
        $order = Order::own()->with(['orderDetails:id,order_id,parent_id'])
            ->where('payment_status', 0)
            ->where('utr', $request->utr)
            ->latest()->first();

        if (!$order) {
            return response()->json($this->withErrors(
               'Order not found or already paid',
            ));
        }

        if ($order->coupon_code == $request->couponCode) {
            return response()->json($this->withErrors(
                'Coupon already applied',
            ));
        }

        $coupon = Coupon::where('code', $request->couponCode)
            ->where('status', 1)
            ->where('start_date', '<=', Carbon::now())
            ->first();

        if (!$coupon || ($coupon->end_date && $coupon->end_date < Carbon::now())) {
            return response()->json($this->withErrors(
                'Invalid or expired coupon',
            ));
        }

        $parentIds = $order->orderDetails->pluck('parent_id')->toArray();

        if ($order->order_for == 'topup' && empty(array_diff($coupon->top_up_list ?? [], $parentIds))) {
            return response()->json($this->withErrors(
                'You are not eligible to apply this coupon',
            ));
        }

        if ($order->order_for == 'card' && empty(array_diff($coupon->card_list ?? [], $parentIds))) {
            return response()->json($this->withErrors(
                'You are not eligible to apply this coupon',
            ));
        }

        if (!$coupon->is_unlimited && $coupon->used_limit <= $coupon->total_use) {
            return response()->json($this->withErrors(
                'Coupon usage limit reached',
            ));

        }

        $discount = $coupon->discount;
        if ($coupon->discount_type == 'percent') {
            $discount = ($order->amount * $coupon->discount) / 100;
        }

        $order->coupon_id = $coupon->id;
        $order->coupon_code = $coupon->code;
        $order->amount = (($order->amount + $order->discount) - $discount);
        $order->discount = $discount;
        $order->save();
        return response()->json($this->withSuccess([
            'status' => 'success',
            'discount' => getAmount($discount, 2),
            'amount' => getAmount($order->amount, 2),
            'total_amount' => userCurrencyPosition($order->amount),
            'message' => "You get " . userCurrencyPosition($discount) . " discount",
            ]));

    }

}
PK     x\r"  r"  '  Http/Controllers/Api/CardController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\CardService;
use App\Models\Category;
use App\Models\Gateway;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Review;
use App\Traits\ApiValidation;
use App\Traits\MakeOrder;
use App\Traits\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CardController extends Controller
{
    use ApiValidation, MakeOrder, Rating;

    public function getCard(Request $request)
    {
        try {
            $categoryId = $request->category_id;
            $sort_by = $request->sort_by;

            $data['cards'] = Card::select(['id', 'category_id', 'name', 'slug', 'status', 'image'])->where('status', 1)
                ->when($categoryId, function ($query, $categoryId) {
                    return $query->where('category_id', $categoryId);
                })
                ->when($sort_by, function ($query, $sort_by) {

                    if ($sort_by == 'all') {
                        $query->orderBy('sort_by', 'desc');
                    } elseif ($sort_by == 'popular') {
                        $query->orderBy('sell_count', 'desc');
                    } elseif ($sort_by == 'latest') {
                        $query->latest();
                    } elseif ($sort_by == 'trending') {
                        $query->where('trending', 1);
                    }elseif ($sort_by == 'date') {
                        $query->orderBy('created_at', 'asc');
                    }
                })
                ->get()->map(function ($query) {
                    $query->product_image = getFile($query->image->image_driver, $query->image->image);
                    return $query;
                })->makeHidden(['image', 'card_detail_route']);

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }
    public function cardCategories(Request $request)
    {
        try {
            $data['categories'] = Category::query()->where('status', 1)->where('type', 'card')->get();

            return response()->json($this->withSuccess($data));
        }catch (\Exception $e){
            return response()->json($this->withErrors($e->getMessage()));
        }
    }
    public function cardDetails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'card_id' => 'required|numeric',
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $details = Card::with('services')->where('status', 1)->find($request->card_id);
            if (!$details) {
                return response()->json($this->withErrors('Card not found'));
            }
            if (!empty($details->description)) {
                $details->description = strip_tags($details->description);
            }

            if (!empty($details->guide)) {
                $details->guide = strip_tags($details->guide);
            }

            foreach ($details->services as $service) {
                $service->currency = basicControl()->base_currency;
                $service->currency_symbol = basicControl()->currency_symbol;
                $service->discountedAmount = $service->getDiscount();
                $service->discountedPriceWithoutDiscount = $service->price - $service->discountedAmount;

                if (isset($service->campaign_data)) {
                    $service->campaign_data->currency = basicControl()->base_currency;
                    $service->campaign_data->currency_symbol = basicControl()->currency_symbol;
                }
            }

            $details->product_image = getFile($details->image->image_driver, $details->image->image);

            $data['reviewStatic'] = $this->getTopReview(Card::class, $details->id);
            $data['details'] = $details->makeHidden(['card_detail_route', 'image']);

            $data['gateways'] = Gateway::where('status', 1)->get()->map(function ($gateway) {
                $gateway->image = getFile($gateway->driver, $gateway->image);
                unset($gateway->driver);
                return $gateway;
            });


            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }



    public function cardServices(Request $request)
    {
        try {
            $cardId = $request->card_id;

            $data['services'] = CardService::where('status', 1)
                ->when($cardId, function ($query, $cardId) {
                    return $query->where('card_id', $cardId);
                })->get()->makeHidden(['image', 'image_driver']);

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function cardReview(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'card_id' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $reviews = Review::has('user')
                ->with(['user:id,firstname,lastname,image,image_driver'])
                ->where('status', 1)
                ->where('reviewable_type', Card::class)
                ->where('reviewable_id', $request->card_id)
                ->paginate(basicControl()->user_pagination);

            $reviews->getCollection()->transform(function ($review) {
                $review->user->imgPath = getFile($review->user->image_driver, $review->user->image);
                return $review->makeHidden(['reviewable_type', 'reviewable_id']);
            });

            return response()->json($this->withSuccess([
                'reviews' => $reviews->items(),
                'pagination' => [
                    'total' => $reviews->total(),
                    'per_page' => $reviews->perPage(),
                    'current_page' => $reviews->currentPage(),
                    'last_page' => $reviews->lastPage(),
                    'next_page_url' => $reviews->nextPageUrl(),
                    'prev_page_url' => $reviews->previousPageUrl(),
                ],
            ]));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function cardReviewPost(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'card_id' => 'required',
            'rating' => 'required|numeric|min:1|max:5',
            'comment' => 'required|string|max:200',
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $user = $this->user($request->header('publicKey'), $request->header('SecretKey'));

            $cardId = $request->card_id;
            $card = Card::select(['id', 'status', 'name'])->where('status', 1)->find($cardId);

            if (!$card) {
                return response()->json($this->withErrors('Data not found'));
            }

            $isHasOrder = OrderDetail::with(["detailable" => function ($query) use ($cardId) {
                $query->whereHas('card', function ($q) use ($cardId) {
                    $q->where('id', $cardId);
                });
            }])
                ->whereHas('order', function ($qq) {
                    $qq->where('payment_status', 1);
                })
                ->where('user_id', $user->id)
                ->where('detailable_type', CardService::class)
                ->exists();

            if ($isHasOrder) {
                Review::updateOrCreate([
                    'reviewable_type' => Card::class,
                    'reviewable_id' => $cardId,
                    'user_id' => $user->id,
                ], [
                    'rating' => $request->rating,
                    'comment' => $request->comment,
                ]);

                $this->reviewNotifyToAdmin($user, $card->name, $request->rating);
                return response()->json($this->withSuccess('Review Added Successfully'));
            }

            return response()->json($this->withErrors('You are not eligible for review'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }
}
PK     x\\1%  %  '  Http/Controllers/Api/AuthController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Mail\SendMail;
use App\Models\User;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
    use ApiValidation, Notify;

    public function registerUserForm()
    {
        try {
            if (basicControl()->registration == 0) {
                return response()->json($this->withErrors("Registration Has Been Disabled."));
            }

            $info = json_decode(json_encode(getIpInfo()), true);
            $country_code = null;
            if (!empty($info['code'])) {
                $data['country_code'] = @$info['code'][0];
            }
            $data['countries'] = config('country');
            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function registerUser(Request $request)
    {
        $basic = basicControl();
        try {

            if ($basic->strong_password == 0) {
                $rules['password'] = ['required', 'min:6', 'confirmed'];
            } else {
                $rules['password'] = ["required", 'confirmed',
                    Password::min(6)->mixedCase()
                        ->letters()
                        ->numbers()
                        ->symbols()
                        ->uncompromised()];
            }

            $rules['firstname'] = ['required', 'string', 'max:91'];
            $rules['lastname'] = ['required', 'string', 'max:91'];
            $rules['username'] = ['required', 'alpha_dash', 'min:5', 'unique:users,username'];
            $rules['email'] = ['required', 'string', 'email', 'max:255', 'unique:users,email'];
            $rules['country_code'] = ['max:5'];
            $rules['phone_code'] = ['required'];
            $rules['phone'] = ['required'];
            $rules['password'] = ['required', 'min:6', 'confirmed'];

            $validateUser = Validator::make($request->all(), $rules, [
                'firstname.required' => 'First Name Field is required',
                'lastname.required' => 'Last Name Field is required',
            ]);

            if ($validateUser->fails()) {
                return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
            }

            if ($request->sponsor != null) {
                $sponsorId = User::where('username', $request->sponsor)->first();
            } else {
                $sponsorId = null;
            }

            $user = User::create([
                'firstname' => $request->firstname,
                'lastname' => $request->lastname,
                'username' => $request->username,
                'email' => $request->email,
                'country_code' => $request->country_code,
                'phone_code' => $request->phone_code,
                'phone' => $request->phone,
                'password' => Hash::make($request->password),
                'email_verification' => ($basic->email_verification) ? 0 : 1,
                'sms_verification' => ($basic->sms_verification) ? 0 : 1,
            ]);

            $user->last_login = Carbon::now();
            $user->two_fa_verify = ($user->two_fa == 1) ? 0 : 1;
            $user->save();


            return response()->json([
                'status' => 'success',
                'message' => 'User Created Successfully',
                'token' => $user->createToken("API TOKEN")->plainTextToken
            ]);


        } catch (\Throwable $th) {
            return response()->json($this->withErrors($th->getMessage()));
        }
    }

    public function loginUser(Request $request)
    {
        try {
            $validateUser = Validator::make($request->all(),
                [
                    'username' => 'required',
                    'password' => 'required'
                ]);

            if ($validateUser->fails()) {
                return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
            }

            if (!Auth::attempt($request->only(['username', 'password']))) {
                return response()->json($this->withErrors('Username & Password does not match with our record.'));
            }

            $user = User::where('username', $request->username)->first();

            $user->last_login = Carbon::now();
            $user->two_fa_verify = ($user->two_fa == 1) ? 0 : 1;
            $user->save();

            if ($user->status == 0) {
                return response()->json($this->withErrors('You are banned from this application.Please contact with the administration'));
            }

            return response()->json([
                'status' => 'success',
                'message' => 'User Logged In Successfully',
                'token' => $user->createToken("API TOKEN")->plainTextToken
            ]);

        } catch (\Throwable $th) {
            return response()->json($this->withErrors($th->getMessage()));
        }
    }

    public function getEmailForRecoverPass(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'email' => 'required|email',
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {
            $user = User::where('email', $request->email)->first();
            if (!$user) {
                return response()->json($this->withErrors('Email does not exit on record'));
            }

            $code = rand(10000, 99999);
            $data['email'] = $request->email;
            $data['message'] = 'OTP has been send';
            $user->verify_code = $code;
            $user->save();

            $basic = basicControl();
            $message = 'Your Password Recovery Code is ' . $code;
            $email_from = $basic->sender_email;
            @Mail::to($request->email)->send(new SendMail($email_from, "Recovery Code", $message));

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function getCodeForRecoverPass(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'code' => 'required',
                'email' => 'required|email',
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {
            $user = User::where('email', $request->email)->first();
            if (!$user) {
                return response()->json($this->withErrors('Email does not exit on record'));
            }

            if ($user->verify_code == $request->code && $user->updated_at > Carbon::now()->subMinutes(5)) {
                $user->verify_code = null;
                $user->update_password_token = Hash::make(Str::random(10));
                $user->save();

                return response()->json($this->withSuccess($user->update_password_token));
            }

            return response()->json($this->withErrors('Invalid Code'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function updatePass(Request $request)
    {
        if (basicControl()->strong_password == 0) {
            $rules['password'] = ['required', 'min:6', 'confirmed'];
        } else {
            $rules['password'] = ["required", 'confirmed',
                Password::min(6)->mixedCase()
                    ->letters()
                    ->numbers()
                    ->symbols()
                    ->uncompromised()];
        }
        $rules['token'] = ['required'];

        $validateUser = Validator::make($request->all(), $rules);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        $user = User::where('update_password_token', $request->token)->first();
        if (!$user) {
            return response()->json($this->withErrors('You are not authorized to take action'));
        }
        $user->password = Hash::make($request->password);
        $user->save();
        return response()->json($this->withSuccess('Password Updated'));
    }

    public function generateBearer(Request $request)
    {
        $publicKey = $request->header('PublicKey');
        $secretKey = $request->header('SecretKey');

        $user = User::where('public_key', $publicKey)
            ->where('secret_key', $secretKey)
            ->first();

        if (!$user) {
            return response()->json(['message' => 'Invalid API credentials'], 401);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'Token generated successfully',
            'bearer_token' => $user->createToken("API TOKEN")->plainTextToken
        ]);
    }
}
PK     x\,  ,  0  Http/Controllers/Api/SupportTicketController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\SupportTicketMessage;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Facades\App\Http\Controllers\User\SupportTicketController as webTicketController;

class SupportTicketController extends Controller
{
    use ApiValidation, Notify, Upload;

    public function ticketList()
    {
        if (auth()->id() == null) {
            return response()->json($this->withErrors('Something went wrong'));
        }
        try {
            $array = [];
            $tickets = tap(SupportTicket::where('user_id', auth()->id())->latest()
                ->paginate(basicControl()->paginate), function ($paginatedInstance) use ($array) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array) {
                    $array['ticket'] = $query->ticket;
                    $array['subject'] = '[Ticket#' . $query->ticket . ']' . ucfirst($query->subject);
                    if ($query->status == 0) {
                        $array['status'] = trans('Open');
                    } elseif ($query->status == 1) {
                        $array['status'] = trans('Answered');
                    } elseif ($query->status == 2) {
                        $array['status'] = trans('Replied');
                    } elseif ($query->status == 3) {
                        $array['status'] = trans('Closed');
                    }
                    $array['lastReply'] = Carbon::parse($query->last_reply)->diffForHumans();
                    return $array;
                });
            });

            if ($tickets) {
                return response()->json($this->withSuccess($tickets));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function ticketCreate(Request $request)
    {
        try {

            $random = rand(100000, 999999);
            $this->newTicketValidation($request);
            $ticket = webTicketController::saveTicket($request, $random);
            $message = webTicketController::saveMsgTicket($request, $ticket);

            if (!empty($request->attachments)) {
                $numberOfAttachments = count($request->attachments);
                for ($i = 0; $i < $numberOfAttachments; $i++) {
                    if ($request->hasFile('attachments.' . $i)) {
                        $file = $request->file('attachments.' . $i);
                        $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), config('filesystems.default'));
                        if (empty($supportFile['path'])) {
                            throw new \Exception('File could not be uploaded.');
                        }
                        webTicketController::saveAttachment($message, $supportFile['path'], $supportFile['driver']);
                    }
                }
            }

            $msg = [
                'user' => optional($ticket->user)->username,
                'ticket_id' => $ticket->ticket
            ];
            $action = [
                "name" => optional($ticket->user)->firstname . ' ' . optional($ticket->user)->lastname,
                "image" => getFile(optional($ticket->user)->image_driver, optional($ticket->user)->image),
                "link" => route('admin.ticket.view', $ticket->id),
                "icon" => "fas fa-ticket-alt text-white"
            ];
            $this->adminPushNotification('SUPPORT_TICKET_CREATE', $msg, $action);
            $this->adminMail('SUPPORT_TICKET_CREATE', $msg);

            return response()->json($this->withSuccess('Your ticket has been pending.'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function newTicketValidation(Request $request)
    {
        $imgs = $request->file('attachments');
        $allowedExts = array('jpg', 'png', 'jpeg', 'pdf');


        $this->validate($request, [
            'attachments' => [
                'max:10240',
                function ($attribute, $value, $fail) use ($imgs, $allowedExts) {
                    foreach ($imgs as $img) {
                        $ext = strtolower($img->getClientOriginalExtension());
                        if (($img->getSize() / 1000000) > 2) {
                            return response()->json($this->withErrors('Images MAX  10MB ALLOW!'));
                        }

                        if (!in_array($ext, $allowedExts)) {
                            return response()->json($this->withErrors('Only png, jpg, jpeg, pdf images are allowed'));
                        }
                    }
                    if (count($imgs) > 5) {
                        return response()->json($this->withErrors('Maximum 5 images can be uploaded'));
                    }
                }
            ],
            'subject' => 'required|max:100',
            'message' => 'required'
        ]);
    }


    public function ticketView($ticketId)
    {
        try {
            $ticket = SupportTicket::with('messages')->where('ticket', $ticketId)
                ->latest()->with('messages')->first();

            if (!$ticket) {
                return response()->json($this->withErrors('Ticket not found'));
            }
            $user = auth()->user();
            if (!$user) {
                return response()->json($this->withErrors('User Not Found'));
            }

            $data['id'] = $ticket->id;
            $data['page_title'] = "Ticket: #" . $ticketId . ' ' . $ticket->subject;
            $data['userImage'] = getFile(optional($ticket->user)->image_driver, optional($ticket->user)->image);
            $data['userUsername'] = optional($ticket->user)->username;
            if ($ticket->status == 0) {
                $data['status'] = trans('Open');
            } elseif ($ticket->status == 1) {
                $data['status'] = trans('Answered');
            } elseif ($ticket->status == 2) {
                $data['status'] = trans('Replied');
            } elseif ($ticket->status == 3) {
                $data['status'] = trans('Closed');
            }


            if ($ticket->messages) {
                foreach ($ticket->messages as $key => $message) {
                    $data['messages'][$key] = $message;
                    $data['messages'][$key]['adminImage'] = ($message->admin_id != null ? getFile(optional($message->admin)->image_driver, optional($message->admin)->image) : null);

                    $data['messages'][$key]['attachments'] = collect($message->attachments)->map(function ($attach, $key) {
                        $attach->attachment_path = getFile($attach->driver, $attach->file);
                        $attach->attachment_name = trans('File') . ' ' . ($key + 1);
                    });
                }
            }

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function ticketReply(Request $request)
    {
        if ($request->replayTicket == 1) {
            $images = $request->file('attachments');
            if($images){
                $allowedExtensions = array('jpg', 'png', 'jpeg', 'pdf');
                $this->validate($request, [
                    'attachments' => [
                        'max:10240',
                        function ($fail) use ($images, $allowedExtensions) {
                            foreach ($images as $img) {
                                $ext = strtolower($img->getClientOriginalExtension());
                                if (($img->getSize() / 1000000) > 2) {
                                    return response()->json($this->withErrors('Images MAX  10MB ALLOW!'));
                                }
                                if (!in_array($ext, $allowedExtensions)) {
                                    return response()->json($this->withErrors('Only png, jpg, jpeg, pdf images are allowed'));
                                }
                            }
                            if (count($images) > 5) {
                                return response()->json($this->withErrors('Maximum 5 images can be uploaded'));
                            }
                        },
                    ],
                    'message' => 'required',
                ]);
            }

            try {
                $ticket = SupportTicket::findOrFail($request->id);
                $ticket->update([
                    'status' => 2,
                    'last_reply' => Carbon::now()
                ]);

                $message = SupportTicketMessage::create([
                    'support_ticket_id' => $ticket->id,
                    'message' => $request->message
                ]);

                if (!empty($request->attachments)) {
                    $numberOfAttachments = count($request->attachments);
                    for ($i = 0; $i < $numberOfAttachments; $i++) {
                        if ($request->hasFile('attachments.' . $i)) {
                            $file = $request->file('attachments.' . $i);
                            $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), config('filesystems.default'));
                            if (empty($supportFile['path'])) {
                                return response()->json($this->withErrors('File could not be uploaded.'));
                            }
                            webTicketController::saveAttachment($message, $supportFile['path'], $supportFile['driver']);
                        }
                    }
                }

                $msg = [
                    'username' => optional($ticket->user)->username,
                    'ticket_id' => $ticket->ticket
                ];
                $action = [
                    "name" => optional($ticket->user)->firstname . ' ' . optional($ticket->user)->lastname,
                    "image" => getFile(optional($ticket->user)->image_driver, optional($ticket->user)->image),
                    "link" => route('admin.ticket.view', $ticket->id),
                    "icon" => "fas fa-ticket-alt text-white"
                ];

                $this->adminPushNotification('SUPPORT_TICKET_CREATE', $msg, $action);
                return response()->json($this->withSuccess('Ticket has been replied'));
            } catch (\Exception $exception) {
                return response()->json($this->withErrors($exception->getMessage()));
            }

        } elseif ($request->replayTicket == 2) {
            $ticket = SupportTicket::findOrFail($request->id);
            $ticket->update([
                'status' => 3,
                'last_reply' => Carbon::now()
            ]);

            return response()->json($this->withSuccess('Ticket has been closed'));
        }
        return response()->json($this->withErrors('something unexpected'));
    }
}
PK     x\ )  )  *  Http/Controllers/Api/ProfileController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\UserAllRecordDeleteJob;
use App\Models\FireBaseToken;
use App\Models\Kyc;
use App\Models\Language;
use App\Models\User;
use App\Models\UserKyc;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class ProfileController extends Controller
{
    use ApiValidation, Notify, Upload;

    public function profile(Request $request)
    {
        try {
            $user = auth()->user();
            $data['userImage'] = getFile($user->image_driver, $user->image);
            $data['userJoinDate'] = $user->created_at ?? null;
            $data['userFirstName'] = $user->firstname ?? null;
            $data['userLastName'] = $user->lastname ?? null;
            $data['userUsername'] = $user->username ?? null;
            $data['userEmail'] = $user->email ?? null;
            $data['userPhoneCode'] = $user->phone_code ?? null;
            $data['userPhone'] = $user->phone ?? null;
            $data['userLanguageId'] = $user->language_id ?? null;
            $data['userAddress'] = $user->address_one ?? null;
            $data['timezone'] = $user->timezone ?? null;

            $data['languages'] = Language::all()->map(function ($query) {
                $query->flag = getFile($query->flag_driver, $query->flag);
                return $query;
            });

            $data['userKyc'] = UserKyc::where('user_id', Auth::user()->id)->where('status', 1)->pluck('kyc_id');
            $data['kycs'] = Kyc::where('status', 1)->get();
            return response()->json($this->withSuccess($data));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function profileImageUpload(Request $request)
    {
        $allowedExtensions = array('jpg', 'png', 'jpeg');
        $image = $request->image;
        $this->validate($request, [
            'image' => [
                'required',
                'max:10240',
                function ($fail) use ($image, $allowedExtensions) {
                    $ext = strtolower($image->getClientOriginalExtension());
                    if (($image->getSize() / 1000000) > 2) {
                        return response()->json($this->withErrors('Images MAX  10MB ALLOW!'));
                    }
                    if (!in_array($ext, $allowedExtensions)) {
                        return response()->json($this->withErrors('Only png, jpg, jpeg images are allowed'));
                    }
                }
            ]
        ]);
        $user = Auth::user();
        if ($request->hasFile('image')) {
            $image = $this->fileUpload($request->image, config('filelocation.userProfile.path'), null, config('filelocation.userProfile.size'), 'webp', null, $user->image, $user->image_driver);
            if ($image) {
                $profileImage = $image['path'];
                $ImageDriver = $image['driver'];
            }
        }
        $user->image = $profileImage ?? $user->image;
        $user->image_driver = $ImageDriver ?? $user->image_driver;
        $user->save();
        return response()->json($this->withSuccess('Updated Successfully.'));

    }

    public function profileInfoUpdate(Request $request)
    {
        try {
            $languages = Language::all()->map(function ($item) {
                return $item->id;
            });
            $user = auth()->user();
            $validateUser = Validator::make($request->all(),
                [
                    'firstname' => 'required',
                    'lastname' => 'required',
                    'username' => "sometimes|required|alpha_dash|min:5|unique:users,username," . $user->id,
                    'address' => 'required',
                    'language_id' => Rule::in($languages),
                ]);

            if ($validateUser->fails()) {
                return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
            }

            $user->language_id = $request['language_id'];
            $user->firstname = $request['firstname'];
            $user->lastname = $request['lastname'];
            $user->username = $request['username'];
            $user->address_one = $request['address'];
            $user->timezone = $request['timezone'];
            $user->save();

            return response()->json($this->withSuccess('Updated Successfully.'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function profilePassUpdate(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'current_password' => "required",
                'password' => "required|min:5|confirmed",
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        $user = auth()->user();
        try {
            if (Hash::check($request->current_password, $user->password)) {
                $user->password = bcrypt($request->password);
                $user->save();

                return response()->json($this->withSuccess('Password Changes successfully.'));
            } else {
                return response()->json($this->withErrors('Current password did not match'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function kycSubmit(Request $request)
    {
        $kyc = Kyc::where('status', 1)->findOrFail($request->id);
        $oldKyc = UserKyc::where('kyc_id', $kyc->id)->where('user_id', Auth::user()->id)->first();
        try {
            $params = $kyc->input_form;
            $reqData = $request->except('_token', '_method');
            $rules = [];
            if ($params !== null) {
                foreach ($params as $key => $cus) {
                    $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                    if ($cus->type == 'file') {
                        $rules[$key][] = 'image';
                        $rules[$key][] = 'mimes:jpeg,jpg,png';
                        $rules[$key][] = 'max:10240';
                    } elseif ($cus->type == 'text') {
                        $rules[$key][] = 'max:191';
                    } elseif ($cus->type == 'number') {
                        $rules[$key][] = 'integer';
                    } elseif ($cus->type == 'textarea') {
                        $rules[$key][] = 'min:3';
                        $rules[$key][] = 'max:300';
                    }
                }
            }
            $validator = Validator::make($reqData, $rules);
            if ($validator->fails()) {
                return response()->json($this->withErrors(collect($validator->errors())->collapse()));
            }
            $reqField = [];
            foreach ($request->except('_token', '_method', 'type') as $k => $v) {
                foreach ($params as $inKey => $inVal) {
                    if ($k == $inKey) {
                        if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                            try {
                                $file = $this->fileUpload($request[$inKey], config('filelocation.kyc.path'), null, null, 'webp', 60);
                                $reqField[$inKey] = [
                                    'field_label' => $inVal->field_name,
                                    'field_value' => $file['path'],
                                    'field_driver' => $file['driver'],
                                    'validation' => $inVal->validation,
                                    'type' => $inVal->type,
                                ];
                            } catch (\Exception $exp) {
                                return response()->json($this->withErrors('Could not upload your ' . $inKey));
                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_label' => $inVal->field_name,
                                'validation' => $inVal->validation,
                                'field_value' => $v,
                                'type' => $inVal->type,
                            ];
                        }
                    }
                }
            }

            if (isset($oldKyc) && $oldKyc->status == 0) {
                $oldKyc->kyc_info = $reqField;
                $oldKyc->status = 0;
                $oldKyc->save();

                return response()->json($this->withSuccess('KYC Updated Successfully'));
            }else{
                UserKyc::create([
                    'user_id' => auth()->id(),
                    'kyc_id' => $kyc->id,
                    'kyc_type' => $kyc->name,
                    'kyc_info' => $reqField
                ]);

                return response()->json($this->withSuccess('KYC Submitted Successfully'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function accountDelete(Request $request)
    {
        $user = auth()->user();
        if (config('demo.IS_DEMO') == true && $user->id ==1) {
            return response()->json('This feature is not available in demo mode');
        }
        if ($user) {
            UserAllRecordDeleteJob::dispatch($user);
            $user->forceDelete();
            return response()->json($this->withSuccess('Account has been deleted'));
        }

        return response()->json('You are not eligible for take action');
    }

    public function firebaseTokenSave(Request $request)
    {
        if (!$request->fcm_token) {
            return response()->json($this->withErrors('FCM Token is required'));
        }

        try {
            $user = auth()->user();
            FireBaseToken::firstOrCreate(
                [
                    'token' => $request->fcm_token
                ],
                [
                    'tokenable_id' => $user->id,
                    'tokenable_type' => User::class,
                ]
            );
            return response()->json($this->withSuccess('FCM Token saved'));
        } catch (\Exception $exception) {
            return response()->json($this->withErrors($exception->getMessage()));
        }
    }
}
PK     x\
^  ^  )  Http/Controllers/Api/PayoutController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Payout;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use App\Traits\Upload;
use App\Models\PayoutMethod;
use Carbon\Carbon;
use Facades\App\Services\BasicService;
use Facades\App\Http\Controllers\User\PayoutController as UserPayoutController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Intervention\Image\Facades\Image;
use Stevebauman\Purify\Facades\Purify;
use Facades\App\Http\Controllers\User;

class PayoutController extends Controller
{
    use ApiValidation, Upload, Notify;

    public function payout()
    {
        try {
            $data['gateways'] = PayoutMethod::where('is_active', 1)->get()->map(function ($query) {
                $query->logo = getFile($query->driver, $query->logo);
                return $query;
            });

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutGetBankList(Request $request)
    {
        try {
            $currencyCode = $request->currencyCode;
            $methodObj = 'App\\Services\\Payout\\paystack\\Card';
            $data = $methodObj::getBank($currencyCode);
            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutGetBankFrom(Request $request)
    {
        try {
            $bankName = $request->bankName;
            $bankArr = config('banks.' . $bankName);
            $value['bank'] = null;
            if ($bankArr['api'] != null) {

                $methodObj = 'App\\Services\\Payout\\flutterwave\\Card';
                $data = $methodObj::getBank($bankArr['api']);
                $value['bank'] = $data;
            }
            $value['input_form'] = $bankArr['input_form'];
            return response()->json($this->withSuccess($value));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutPaystackSubmit(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'gateway' => 'required|integer',
                'currency' => 'required',
                'amount' => ['required', 'numeric']
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {

            if (!config('withdrawaldays')[date('l')]) {
                return response()->json($this->withErrors('Withdraw processing is off today'));
            }

            $amount = $request->amount;
            $payoutMethod = PayoutMethod::findOrFail($request->gateway);
            $supportedCurrency = $request->currency;

            $checkAmountValidateData = UserPayoutController::checkAmountValidate($amount, $supportedCurrency, $payoutMethod->id);

            if (!$checkAmountValidateData['status']) {
                return response()->json($this->withErrors($checkAmountValidateData['message']));
            }
            $user = Auth::user();

            if ($user->balance < $checkAmountValidateData['net_amount_in_base_currency']) {
                return response()->json($this->withErrors('Insufficient Balance'));
            }

            if (empty($request->bank)) {
                return response()->json($this->withErrors('Bank field is required'));
            }

            $payout = new Payout();
            $payout->user_id = $user->id;
            $payout->payout_method_id = $checkAmountValidateData['payout_method_id'];
            $payout->payout_currency_code = $checkAmountValidateData['currency'];
            $payout->amount = $checkAmountValidateData['amount'];
            $payout->charge = $checkAmountValidateData['payout_charge'];
            $payout->net_amount = $checkAmountValidateData['net_payout_amount'];
            $payout->amount_in_base_currency = $checkAmountValidateData['amount_in_base_currency'];
            $payout->charge_in_base_currency = $checkAmountValidateData['charge_in_base_currency'];
            $payout->net_amount_in_base_currency = $checkAmountValidateData['net_amount_in_base_currency'];
            $payout->information = null;
            $payout->feedback = null;
            $payout->status = 0;
            $payout->save();

            $rules = [];
            if ($payoutMethod->inputForm != null) {
                foreach ($payoutMethod->inputForm as $key => $cus) {
                    $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                    if ($cus->type === 'file') {
                        $rules[$key][] = 'image';
                        $rules[$key][] = 'mimes:jpeg,jpg,png';
                        $rules[$key][] = 'max:10240';
                    } elseif ($cus->type === 'text') {
                        $rules[$key][] = 'max:191';
                    } elseif ($cus->type === 'number') {
                        $rules[$key][] = 'integer';
                    } elseif ($cus->type === 'textarea') {
                        $rules[$key][] = 'min:3';
                        $rules[$key][] = 'max:300';
                    }
                }
            }

            $validate = Validator::make($request->all(), $rules);
            if ($validate->fails()) {
                return response()->json($this->withErrors(collect($validate->errors())->collapse()));
            }

            $params = $payoutMethod->inputForm;
            $reqField = [];
            foreach ($request->except('_token', '_method', 'type', 'currency_code', 'bank') as $k => $v) {
                foreach ($params as $inKey => $inVal) {
                    if ($k == $inVal->field_name) {
                        if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                            try {
                                $file = $this->fileUpload($request[$inKey], config('filelocation.payoutLog.path'));
                                $reqField[$inKey] = [
                                    'field_name' => $inVal->field_name,
                                    'field_value' => $file['path'],
                                    'field_driver' => $file['driver'],
                                    'validation' => $inVal->validation,
                                    'type' => $inVal->type,
                                ];
                            } catch (\Exception $exp) {
                                session()->flash('error', 'Could not upload your ' . $inKey);
                                return back()->withInput();
                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'validation' => $inVal->validation,
                                'field_value' => $v,
                                'type' => $inVal->type,
                            ];
                        }
                    }
                }
            }

            $reqField['type'] = [
                'field_name' => "type",
                'field_value' => $request->type,
                'type' => 'text',
            ];
            $reqField['bank_code'] = [
                'field_name' => "bank_id",
                'field_value' => $request->bank,
                'type' => 'number',
            ];

            $payout->information = $reqField;
            $payout->status = 1;
            $payout->save();

            updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0);
            BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class, $payout->charge_in_base_currency);

            return response()->json($this->withSuccess('Withdraw request Successfully Submitted. Wait For Confirmation.'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }


    public function payoutFlutterwaveSubmit(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'gateway' => 'required|integer',
                'currency' => 'required',
                'amount' => ['required', 'numeric']
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {

            if (!config('withdrawaldays')[date('l')]) {
                return response()->json($this->withErrors('Withdraw processing is off today'));
            }

            $amount = $request->amount;
            $payoutMethod = PayoutMethod::findOrFail($request->gateway);
            $supportedCurrency = $request->currency;

            $checkAmountValidateData = UserPayoutController::checkAmountValidate($amount, $supportedCurrency, $payoutMethod->id);

            if (!$checkAmountValidateData['status']) {
                return response()->json($this->withErrors($checkAmountValidateData['message']));
            }
            $user = Auth::user();

            if ($user->balance < $checkAmountValidateData['net_amount_in_base_currency']) {
                return response()->json($this->withErrors('Insufficient Balance'));
            }

            $purifiedData = $request->all();
            if (empty($purifiedData['transfer_name'])) {
                return response()->json($this->withErrors('Transfer field is required'));
            }

            $validation = config('banks.' . $purifiedData['transfer_name'] . '.validation');

            $rules = [];
            if ($validation != null) {
                foreach ($validation as $key => $cus) {
                    $rules[$key] = 'required';
                }
            }

            if ($request->transfer_name == 'NGN BANK' || $request->transfer_name == 'NGN DOM' || $request->transfer_name == 'GHS BANK'
                || $request->transfer_name == 'KES BANK' || $request->transfer_name == 'ZAR BANK' || $request->transfer_name == 'ZAR BANK') {
                $rules['bank'] = 'required';
            }


            $validate = Validator::make($request->all(), $rules);
            if ($validate->fails()) {
                return response()->json($this->withErrors(collect($validate->errors())->collapse()));
            }

            $payout = new Payout();
            $payout->user_id = $user->id;
            $payout->payout_method_id = $checkAmountValidateData['payout_method_id'];
            $payout->payout_currency_code = $checkAmountValidateData['currency'];
            $payout->amount = $checkAmountValidateData['amount'];
            $payout->charge = $checkAmountValidateData['payout_charge'];
            $payout->net_amount = $checkAmountValidateData['net_payout_amount'];
            $payout->amount_in_base_currency = $checkAmountValidateData['amount_in_base_currency'];
            $payout->charge_in_base_currency = $checkAmountValidateData['charge_in_base_currency'];
            $payout->net_amount_in_base_currency = $checkAmountValidateData['net_amount_in_base_currency'];
            $payout->information = null;
            $payout->feedback = null;
            $payout->status = 0;
            $payout->save();

            $collection = collect($purifiedData);
            $reqField = [];
            $metaField = [];

            if (config('banks.' . $purifiedData['transfer_name'] . '.input_form') != null) {
                foreach ($collection as $k => $v) {
                    foreach (config('banks.' . $purifiedData['transfer_name'] . '.input_form') as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal == 'meta') {
                                $metaField[$inKey] = [
                                    'field_name' => $k,
                                    'field_value' => $v,
                                    'type' => 'text',
                                ];
                            } else {
                                $reqField[$inKey] = [
                                    'field_name' => $k,
                                    'field_value' => $v,
                                    'type' => 'text',
                                ];
                            }
                        }
                    }
                }


                if ($request->transfer_name == 'NGN BANK' || $request->transfer_name == 'NGN DOM' || $request->transfer_name == 'GHS BANK'
                    || $request->transfer_name == 'KES BANK' || $request->transfer_name == 'ZAR BANK' || $request->transfer_name == 'ZAR BANK') {

                    $reqField['account_bank'] = [
                        'field_name' => 'Account Bank',
                        'field_value' => $request->bank,
                        'type' => 'text',
                    ];
                } elseif ($request->transfer_name == 'XAF/XOF MOMO') {
                    $reqField['account_bank'] = [
                        'field_name' => 'MTN',
                        'field_value' => 'MTN',
                        'type' => 'text',
                    ];
                } elseif ($request->transfer_name == 'FRANCOPGONE' || $request->transfer_name == 'mPesa' || $request->transfer_name == 'Rwanda Momo'
                    || $request->transfer_name == 'Uganda Momo' || $request->transfer_name == 'Zambia Momo') {
                    $reqField['account_bank'] = [
                        'field_name' => 'MPS',
                        'field_value' => 'MPS',
                        'type' => 'text',
                    ];
                }

                if ($request->transfer_name == 'Barter') {
                    $reqField['account_bank'] = [
                        'field_name' => 'barter',
                        'field_value' => 'barter',
                        'type' => 'text',
                    ];
                } elseif ($request->transfer_name == 'flutterwave') {
                    $reqField['account_bank'] = [
                        'field_name' => 'barter',
                        'field_value' => 'barter',
                        'type' => 'text',
                    ];
                }

                $payoutCurrencies = $payoutMethod->payout_currencies;
                $currencyInfo = collect($payoutCurrencies)->where('name', $request->currency)->first();

                $reqField['amount'] = [
                    'field_name' => 'amount',
                    'field_value' => $payout->amount * $currencyInfo->conversion_rate,
                    'type' => 'text',
                ];

                $payout->information = $reqField;
                $payout->meta_field = $metaField;


            } else {
                $payout->information = null;
                $payout->meta_field = null;
            }

            $payout->status = 1;
            $payout->payout_currency_code = $request->currency;
            $payout->save();

            updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0);
            BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, $payout->charge_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class);

            return response()->json($this->withSuccess('Withdraw request Successfully Submitted. Wait For Confirmation.'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutSubmit(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'gateway' => 'required|integer',
                'currency_code' => 'required',
                'amount' => ['required', 'numeric']
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {

            if (!config('withdrawaldays')[date('l')]) {
                return response()->json($this->withErrors('Withdraw processing is off today'));
            }

            $amount = $request->amount;
            $payoutMethod = PayoutMethod::findOrFail($request->gateway);
            $supportedCurrency = $request->currency_code;

            $checkAmountValidateData = UserPayoutController::checkAmountValidate($amount, $supportedCurrency, $payoutMethod->id);

            if (!$checkAmountValidateData['status']) {
                return response()->json($this->withErrors($checkAmountValidateData['message']));
            }
            $user = Auth::user();

            if ($user->balance < $checkAmountValidateData['net_amount_in_base_currency']) {
                return response()->json($this->withErrors('Insufficient Balance'));
            }


            $params = $payoutMethod->inputForm;
            $rules = [];
            if ($params !== null) {
                foreach ($params as $key => $cus) {
                    $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                    if ($cus->type === 'file') {
                        $rules[$key][] = 'image';
                        $rules[$key][] = 'mimes:jpeg,jpg,png';
                        $rules[$key][] = 'max:4048';
                    } elseif ($cus->type === 'text') {
                        $rules[$key][] = 'max:191';
                    } elseif ($cus->type === 'number') {
                        $rules[$key][] = 'integer';
                    } elseif ($cus->type === 'textarea') {
                        $rules[$key][] = 'min:3';
                        $rules[$key][] = 'max:300';
                    }
                }
            }

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                return response()->json($this->withErrors(collect($validator->errors())->collapse()));
            }

            $payout = new Payout();
            $payout->user_id = $user->id;
            $payout->payout_method_id = $checkAmountValidateData['payout_method_id'];
            $payout->payout_currency_code = $checkAmountValidateData['currency'];
            $payout->amount = $checkAmountValidateData['amount'];
            $payout->charge = $checkAmountValidateData['payout_charge'];
            $payout->net_amount = $checkAmountValidateData['net_payout_amount'];
            $payout->amount_in_base_currency = $checkAmountValidateData['amount_in_base_currency'];
            $payout->charge_in_base_currency = $checkAmountValidateData['charge_in_base_currency'];
            $payout->net_amount_in_base_currency = $checkAmountValidateData['net_amount_in_base_currency'];
            $payout->information = null;
            $payout->feedback = null;
            $payout->status = 0;
            $payout->save();

            $reqField = [];
            foreach ($request->except('_token', '_method', 'type', 'currency_code', 'bank') as $k => $v) {
                foreach ($params as $inKey => $inVal) {
                    if ($k == $inVal->field_name) {
                        if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                            try {
                                $file = $this->fileUpload($request[$inKey], config('filelocation.payoutLog.path'), null, null, 'webp', 60);
                                $reqField[$inKey] = [
                                    'field_name' => $inVal->field_name,
                                    'field_value' => $file['path'],
                                    'field_driver' => $file['driver'],
                                    'validation' => $inVal->validation,
                                    'type' => $inVal->type,
                                ];
                            } catch (\Exception $exp) {
                                return response()->json($this->withErrors('Could not upload your ' . $inKey));
                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'validation' => $inVal->validation,
                                'field_value' => $v,
                                'type' => $inVal->type,
                            ];
                        }
                    }
                }
            }

            $payoutCurrencies = $payoutMethod->payout_currencies;
            if ($payoutMethod->is_automatic == 1) {
                $currencyInfo = collect($payoutCurrencies)->where('name', $request->currency_code)->first();
            } else {
                $currencyInfo = collect($payoutCurrencies)->where('currency_symbol', $request->currency_code)->first();
            }
            $reqField['amount'] = [
                'field_name' => 'amount',
                'field_value' => currencyPosition($payout->amount / $currencyInfo->conversion_rate),
                'type' => 'text',
            ];


            if ($payoutMethod->code == 'paypal') {
                $reqField['recipient_type'] = [
                    'field_name' => 'receiver',
                    'validation' => $inVal->validation,
                    'field_value' => $request->recipient_type,
                    'type' => 'text',
                ];
            }
            $payout->information = $reqField;
            $payout->status = 1;

            $user = Auth::user();

            updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0); //update user balance
            BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class, $payout->charge_in_base_currency);

            $this->userNotify($user, $payout); // send user notification

            $payout->save();

            return response()->json($this->withSuccess('Withdraw request Successfully Submitted. Wait For Confirmation.'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function userNotify($user, $payout): void
    {
        $params = [
            'sender' => $user->name,
            'amount' => $payout->amount ,
            'currency' => $payout->payout_currency_code ,
            'transaction' => $payout->trx_id,
        ];

        $action = [
            "link" => route('admin.payout.log'),
            "icon" => "fa fa-money-bill-alt text-white",
            "name" => optional($payout->user)->firstname . ' ' . optional($payout->user)->lastname,
            "image" => getFile(optional($payout->user)->image_driver, optional($payout->user)->image),
        ];
        $firebaseAction = route('admin.payout.log');
        $this->adminMail('PAYOUT_REQUEST_TO_ADMIN', $params);
        $this->adminPushNotification('PAYOUT_REQUEST_TO_ADMIN', $params, $action);
        $this->adminFirebasePushNotification('PAYOUT_REQUEST_TO_ADMIN', $params, $firebaseAction);

        $params = [
            'amount' => $payout->amount,
            'currency' => $payout->payout_currency_code,
            'transaction' => $payout->trx_id,
        ];
        $action = [
            "link" => "#",
            "icon" => "fa fa-money-bill-alt text-white"
        ];
        $firebaseAction = "#";
        $this->sendMailSms($user, 'PAYOUT_REQUEST_FROM', $params);
        $this->userPushNotification($user, 'PAYOUT_REQUEST_FROM', $params, $action);
        $this->userFirebasePushNotification($user, 'PAYOUT_REQUEST_FROM', $params, $firebaseAction);
    }
}
PK     x\@4  4  &  Http/Controllers/Api/BuyController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\PaymentController;
use App\Models\Deposit;
use App\Traits\ApiPayment;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use App\Models\Gateway;
use App\Models\SellPost;
use App\Models\SellPostCategory;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Stevebauman\Purify\Facades\Purify;

class BuyController extends Controller
{
    use ApiValidation, Notify, ApiPayment;

    public function buyList(Request $request)
    {
        $data['my_id'] = auth()->id();
        $selectQuery = SellPost::get();

        $max = $selectQuery->max('price');
        $min = $selectQuery->min('price');


        $data['sellPost'] = SellPost::when(request('sortByCategory', false), function ($q, $sortByCategory) {
            $newArr = explode(',', $sortByCategory);
            $q->whereHas('category', function ($q) {
                $q->where('status', 1);
            })->whereIn('category_id', $newArr);

        })->when(request('search', false), function ($q, $search) {
            $q->where('title', 'LIKE', "%$search%");
        })
            ->where('status', 1)
            ->where('payment_status', '!=', 1)
            ->when(request('minPrice', false), function ($q, $minPrice) {
                $maxPrice = \request('maxPrice');
                $q->whereBetween('price', [$minPrice, $maxPrice]);
            })
            ->when(request('sortBy', false), function ($q, $sortBy) {
                if ($sortBy == 'desc') {
                    $q->orderBy('updated_at', 'desc');
                }
                if ($sortBy == 'asc') {
                    $q->orderBy('created_at', 'asc');
                }
                if ($sortBy == 'low_to_high') {
                    $q->orderBy('price', 'asc');
                }
                if ($sortBy == 'high_to_low') {
                    $q->orderBy('price', 'desc');
                }

            })
            ->paginate(basicControl()->paginate);

        $data['max'] = $max;
        $data['min'] = $min;


        $data['categories'] = SellPostCategory::with('details')->whereHas('activePost')->whereStatus(1)->get();
        return response()->json($this->withSuccess($data));
    }

    public function makeOffer(Request $request)
    {
        $purifiedData = $request->all();

        $rules = [
            'sell_post_id' => 'required|numeric',
            'amount' => 'required|numeric|min:1',
            'description' => 'required',
        ];
        $message = [
            'amount.required' => 'Amount field is required',
            'description.required' => 'Description field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $auth = auth()->user();
        $sellPost = SellPost::where('status', 1)->find($request->sell_post_id);
        if (!$sellPost) {
            return response()->json($this->withErrors('Sell Post data not found'));
        }

        if ($sellPost->payment_status == 1) {
            return response()->json($this->withErrors('You can not offer already someone purchases'));
        }

        $sellPostOffer = SellPostOffer::whereUser_id($auth->id)->whereSell_post_id($sellPost->id)->count();

        if ($sellPostOffer > 0) {
            $sellPostOffer = SellPostOffer::whereUser_id($auth->id)->whereSell_post_id($request->sell_post_id)->update(["amount" => $request->amount,
                "description" => $request->description,
                "status" => 3
            ]);

        } else {
            SellPostOffer::create([
                'author_id' => $sellPost->user_id,
                'user_id' => Auth::user()->id,
                'sell_post_id' => $request->sell_post_id,
                'amount' => $request->amount,
                'description' => $request->description,
            ]);
        }

        $user = $sellPost->user;
        if ($sellPostOffer > 0) {
            $this->isReOffer($sellPost, $user, $request);
        } else {
            $msg = [
                'link' => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
                'title' => $sellPost->title,
                'amount' => $request->amount . ' ' . config('basic.currency'),
                'offer_by' => $sellPost->user->firstname . ' ' . $sellPost->user->lastname,
                'description' => $request->description
            ];
            $action = [
                "link" => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_OFFER', $msg, $action);

            $this->sendMailSms($user, 'SELL_OFFER', $msg);
        }

        return response()->json($this->withSuccess('Offer Send'));
    }

    public function isReOffer($sellPost, $user, $request)
    {
        $msg = [
            'link' => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
            'title' => $sellPost->title,
            'amount' => $request->amount . ' ' . config('basic.currency'),
            'offer_by' => $sellPost->user->firstname . ' ' . $sellPost->user->lastname,
            'description' => $request->description
        ];
        $action = [
            "link" => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
            "icon" => "fa fa-money-bill-alt text-white"
        ];
        $this->userPushNotification($user, 'SELL_RE_OFFER', $msg, $action);

        $this->sendMailSms($user, 'SELL_RE_OFFER', $msg);

        return 0;
    }

    public function buyIdDetails(Request $request)
    {
        try {
            $id = $request->query('id');
            $sellPost = SellPost::where('id', $id)
                ->where('status', 1)
                ->first();
            $data['sellPostOffer'] = SellPostOffer::where('sell_post_id', $id)->orderBy('amount', 'desc')->take(3)->get();
            if ($data['sellPostOffer']->isEmpty()) {
                return response()->json($this->withErrors('Sell Post Offer data not found'));
            }
            $data['sellpostStatus'] = [];
            $sellpostPaymentStatus = null;
            if ($sellPost->payment_status == 1) {
                $sellpostPaymentStatus = 'Completed';
            }else {
                if ($sellPost->payment_lock == 1) {
                    if (Auth::check() && Auth::id() == $sellPost->lock_for){
                        $sellpostPaymentStatus = 'Waiting Payment';
                    }elseif (Auth::check() &&  Auth::id() == $sellPost->user_id){
                        $sellpostPaymentStatus = 'Payment Processing';
                    }else{
                        $sellpostPaymentStatus = 'Going to Sell';
                    }
                }
            }
            $data['sellpostStatus'] =[
                'sellpostPaymentStatus' => $sellpostPaymentStatus,
            ];

            $data['price'] = $sellPost->price;
            if (Auth::check()) {
                $user = Auth::user();
                $checkMyProposal = SellPostOffer::where([
                    'user_id' => $user->id,
                    'sell_post_id' => $sellPost->id,
                    'status' => 1,
                    'payment_status' => 0,
                ])->first();
                if ($checkMyProposal) {
                    $data['price'] = (int)$checkMyProposal->amount;
                }
            }
            $data['sellPost'] = $sellPost;

            $data['gateways'] = Gateway::whereStatus(1)->orderBy('sort_by')->get()->map(function ($query) {
                $query->image = getFile($query->driver, $query->image);
                return $query;
            });

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function buyIdMakePayment(Request $request)
    {
        $purifiedData = $request->all();

        $rules = [
            'sellPostId' => ['required', 'numeric'],
            'gateway' => ['nullable'],
            'selectedCurrency' => 'nullable',
        ];
        $message = [
            'gateway.required' => 'Please select a payment method',
            'sellPostId.required' => 'Please select a sell post'
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $sellPost = SellPost::where('id', $request->sellPostId)
            ->where('status', 1)
            ->first();

        if (!$sellPost) {
            return response()->json($this->withErrors('This post already sold or not available to sell'));
        }

        $price = $sellPost->price;
        if (Auth::check()) {
            $user = Auth::user();
            $checkMyProposal = SellPostOffer::where([
                'user_id' => $user->id,
                'sell_post_id' => $sellPost->id,
                'status' => 1,
                'payment_status' => 0,
            ])->first();
            if ($checkMyProposal) {
                $price = (int)$checkMyProposal->amount;
            }
        }

        $discount = 0;
        $user = auth()->user();

        $reqAmount = $price - $discount;

        if ($request->selectedCurrency) {
            $checkAmountValidate = $this->validationCheck($reqAmount, $request->gateway, $request->selectedCurrency, null, 'yes');

            if (!$checkAmountValidate['status']) {
                return response()->json($this->withErrors($checkAmountValidate['message']));
            }
        }

        if (!$request->gateway && $user->balance < $reqAmount) {
            return back()->with('error', 'Insufficient Wallet Balance')->withInput();
        }

        $admin_amount = $reqAmount * $sellPost->sell_charge / 100;
        $seller_amount = $reqAmount - $admin_amount;

        $sellPostPayment = new SellPostPayment();
        $sellPostPayment->user_id = $user->id;
        $sellPostPayment->sell_post_id = $sellPost->id;
        $sellPostPayment->price = $reqAmount;
        $sellPostPayment->seller_amount = $seller_amount;
        $sellPostPayment->admin_amount = $admin_amount;
        $sellPostPayment->discount = $discount;
        $sellPostPayment->transaction = strRandom();

        $sellPostPayment->save();

        if (!$request->gateway) {
            if ($user->balance > $reqAmount) {
                $user->balance -= $reqAmount;
                $user->save();
                $sellPostPayment->payment_status = 1;
                $sellPostPayment->save();

                $sellPost->payment_status = 1;
                $sellPost->lock_for = $user->id;
                $sellPost->save();

                $authorUser = $sellPost->user;

                $checkMyProposal = SellPostOffer::where([
                    'user_id' => $user->id,
                    'sell_post_id' => $sellPost->id,
                    'status' => 1,
                    'payment_status' => 0,
                ])->first();
                if ($checkMyProposal) {
                    $checkMyProposal->payment_status = 1;
                    $checkMyProposal->save();
                }

                SellPostOffer::where('user_id', '!=', $user->id)->where('sell_post_id', $sellPost->id)->get()->map(function ($item) {
                    $item->uuid = null;
                    $item->save();
                });

                $remark = 'Sell Post Payment Via Wallet';
                BasicService::makeTransaction($user->id, $reqAmount, 0, '-',
                    $sellPostPayment->transaction, $remark, $sellPostPayment->id, SellPostPayment::class);

                return response()->json($this->withSuccess('Your order has been processed'));
            } else {
                return response()->json($this->withSuccess('Insufficient Balance'));
            }
        } else {
            $deposit = Deposit::create([
                'user_id' => auth()->id(),
                'payment_method_id' => $checkAmountValidate['gateway_id'],
                'payment_method_currency' => $checkAmountValidate['currency'],
                'amount' => $checkAmountValidate['amount'],
                'percentage_charge' => $checkAmountValidate['percentage_charge'],
                'fixed_charge' => $checkAmountValidate['fixed_charge'],
                'payable_amount' => $checkAmountValidate['payable_amount'],
                'payable_amount_in_base_currency' => $checkAmountValidate['payable_amount_baseCurrency'],
                'charge_base_currency' => $checkAmountValidate['charge_baseCurrency'],
                'status' => 0,
                'depositable_id' => $sellPostPayment->id,
                'depositable_type' => SellPostPayment::class,
            ]);

            $val['trxId'] = $deposit->trx_id;
            return response()->json($this->withSuccess($val));
        }
    }
}
PK     x\ٴ(,  ,  (  Http/Controllers/Api/TopUpController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\UpdateReviewAndRatingJob;
use App\Models\Category;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Review;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\ApiValidation;
use App\Traits\MakeOrder;
use App\Traits\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class TopUpController extends Controller
{
    use ApiValidation, MakeOrder, Rating;

    public function getTopUp(Request $request)
    {
        try {
            $categoryId = $request->category_id;

            $data['topUps'] = TopUp::select(['id', 'category_id', 'name', 'slug', 'status', 'image'])->where('status', 1)
                ->when($categoryId, function ($query, $categoryId) {
                    return $query->where('category_id', $categoryId);
                })->get()->map(function ($query) {
                    $query->product_image = getFile($query->image->image_driver, $query->image->image);
                    return $query;
                })->makeHidden(['image', 'top_up_detail_route']);

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpDetails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'top_up_id' => 'required|numeric',
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $details = TopUp::where('status', 1)->find($request->top_up_id);
            if (!$details) {
                return response()->json($this->withErrors('Top Up not found'));
            }

            $details->product_image = getFile($details->image->image_driver, $details->image->image);

            $data['details'] = $details->makeHidden(['top_up_detail_route', 'image']);
            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpServices(Request $request)
    {
        try {
            $topUpId = $request->top_up_id;

            $data['services'] = TopUpService::where('status', 1)
                ->when($topUpId, function ($query, $topUpId) {
                    return $query->where('top_up_id', $topUpId);
                })->get()->makeHidden(['image', 'image_driver']);

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpReview(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'top_up_id' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $reviews = Review::has('user')
                ->with(['user:id,firstname,lastname,image,image_driver'])
                ->where('status', 1)
                ->where('reviewable_type', TopUp::class)
                ->where('reviewable_id', $request->top_up_id)
                ->latest()
                ->paginate(basicControl()->user_pagination);

            $reviews->getCollection()->transform(function ($review) {
                $review->user->imgPath = getFile($review->user->image_driver, $review->user->image);
                return $review->makeHidden(['reviewable_type', 'reviewable_id', 'user_id']);
            });

            return response()->json($this->withSuccess([
                'reviews' => $reviews->items(),
                'pagination' => [
                    'total' => $reviews->total(),
                    'per_page' => $reviews->perPage(),
                    'current_page' => $reviews->currentPage(),
                    'last_page' => $reviews->lastPage(),
                    'next_page_url' => $reviews->nextPageUrl(),
                    'prev_page_url' => $reviews->previousPageUrl(),
                ],
            ]));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpReviewPost(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'topUpId' => 'required',
            'rating' => 'required|numeric|min:1|max:5',
            'comment' => 'required|string|max:200',
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        try {
            $user = $this->user($request->header('publicKey'), $request->header('SecretKey'));

            $topUpId = $request->topUpId;
            $topUp = TopUp::select(['id', 'status', 'name'])->where('status', 1)->find($topUpId);

            if (!$topUp) {
                return response()->json($this->withErrors('Data not found'));
            }

            $isHasOrder = OrderDetail::with(["detailable" => function ($query) use ($topUpId) {
                $query->whereHas('topUp', function ($q) use ($topUpId) {
                    $q->where('id', $topUpId);
                });
            }])
                ->whereHas('order', function ($qq) {
                    $qq->where('payment_status', 1);
                })
                ->where('user_id', $user->id)
                ->where('detailable_type', TopUpService::class)
                ->exists();

            if ($isHasOrder) {
                $review = Review::updateOrCreate([
                    'reviewable_type' => TopUp::class,
                    'reviewable_id' => $topUpId,
                    'user_id' => $user->id,
                ], [
                    'rating' => $request->rating,
                    'comment' => $request->comment,
                ]);

                UpdateReviewAndRatingJob::dispatch($review->id, TopUp::class, $topUpId);

                $this->reviewNotifyToAdmin($user, $topUp->name, $request->rating);
                return response()->json($this->withSuccess('Review Added Successfully'));
            }

            return response()->json($this->withErrors('You are not eligible for review'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpOrder(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'topUpId' => ['required', 'numeric'],
            'serviceId' => ['required', 'numeric']
        ]);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->errors())->collapse()));
        }

        DB::beginTransaction();
        try {
            $service = TopUpService::whereHas('topUp', function ($query) {
                $query->where('status', 1);
            })->where('status', 1)->find($request->serviceId);

            if (!$service) {
                return response()->json($this->withErrors('Data not found'));
            }

            $topUp = $service->topUp;

            $rules = [];
            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    $rules[$cus->field_name] = ['required'];
                    if ($cus->field_type == 'select') {
                        $options = implode(',', array_keys((array)$cus->option));
                        array_push($rules[$cus->field_name], 'in:' . $options);
                    }
                }
            }

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                return response()->json($this->withErrors(collect($validator->errors())->collapse()));
            }

            $info = [];

            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    if (isset($request->{$cus->field_name})) {
                        $info[$cus->field_name] = [
                            'field' => $cus->field_value,
                            'value' => $request->{$cus->field_name},
                        ];
                    }
                }
            }

            $user = $this->user($request->header('publicKey'), $request->header('SecretKey'));
            $order = $this->orderCreate(showActualPrice($service), 'topup', $info, 'API', $user);
            $this->orderDetailsCreate($order, $service, TopUpService::class);

            $payByWallet = $this->payByWallet($order, $user);
            if (!$payByWallet['status']) {
                DB::rollBack();
                return response()->json($this->withErrors($payByWallet['message']));
            }
            DB::commit();
            return response()->json($this->withSuccess('Order has been placed successfully'));
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function getTopUpOrder(Request $request)
    {
        try {
            $user = $this->user($request->header('publicKey'), $request->header('SecretKey'));
            $orders = [];
            $data['orders'] = Order::with(['orderDetails', 'orderDetails.detailable',
                'orderDetails.detailable.topUp'])
                ->where('user_id', $user->id)
                ->payment()
                ->type('topup')
                ->orderBy('id', 'desc')
                ->get()->map(function ($query) use ($orders) {
                    $orders['orderId'] = $query->utr;
                    $orders['amount'] = $query->amount;
                    $orders['currency'] = basicControl()->base_currency;
                    $orders['currency_symbol'] = basicControl()->currency_symbol;
                    $orders['status'] = $query->status;
                    $orders['date'] = $query->created_at;
                    $orders['info'] = $query->info;

                    if (!empty($query->orderDetails)) {
                        foreach ($query->orderDetails as $detail) {
                            $orders['order_details'][] = [
                                'name' => $detail->name,
                                'image' => $detail->image_path,
                                'currency' => basicControl()->base_currency,
                                'currency_symbol' => basicControl()->currency_symbol,
                                'price' => $detail->price,
                                'qty' => $detail->qty,
                                'topUp_name' => $detail->detailable?->topUp?->name,
                                'rating' => $detail->detailable?->topUp?->avg_rating,
                            ];
                        }
                    }
                    return $orders;
                });

            return response()->json($this->withSuccess($data));
        }catch (\Exception $e){
            return response()->json($this->withErrors('Something went wrong'));
        }
    }
}
PK     x\{  {  +  Http/Controllers/Api/SellPostController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Admin;
use App\Models\SellPost;
use App\Models\SellPostCategory;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Models\User;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class SellPostController extends Controller
{
    use ApiValidation, Upload, Notify;

    public function sellPostCategory(Request $request)
    {
        if ($request->has('category_id')) {
            $data['category'] = SellPostCategory::with('details')->whereStatus(1)->find($request->category_id);
            if (!$data['category']) {
                return response()->json($this->withErrors('Data not found'));
            }
            $data['category']['image'] = getFile($data['category']->image_driver, $data['category']->image);
        } else {
            $data['categoryList'] = SellPostCategory::with('details')
                ->whereStatus(1)
                ->get()->map(function ($query) {
                    $query->image = getFile($query->image_driver, $query->image);
                    return $query;
                });
        }
        return response()->json($this->withSuccess($data));
    }

    public function sellPostCreate(Request $request)
    {
        $validate = Validator::make($request->all(),
            [
                'category' => 'required',
                'price' => 'required|numeric|min:1',
                'title' => 'required',
                'comments' => 'required',
                'image' => 'required'
            ]);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $category = SellPostCategory::whereStatus(1)->find($request->category);
        if (!$category) {
            return response()->json($this->withErrors('Category not found'));
        }

        $rules = [];
        $inputFieldSpecification = [];
        if ($category->form_field != null) {
            foreach ($category->form_field as $key => $cus) {
                $rules[$key] = [$cus->validation];
                $inputFieldSpecification[$key . '.' . $cus->validation] = "The $key field is required.";

                if ($cus->type == 'file') {
                    array_push($rules[$key], 'image');
                    array_push($rules[$key], 'mimes:jpeg,jpg,png');
                    array_push($rules[$key], 'max:10240');

                    $inputFieldSpecification[$key . '.image'] = "The $key must be an image.";
                    $inputFieldSpecification[$key . '.mimes'] = "The $key must be type of png, jpeg, jpg.";
                    $inputFieldSpecification[$key . '.max'] = "The $key  may not be greater than 10240kb characters.";
                }
                if ($cus->type == 'text') {
                    array_push($rules[$key], 'max:191');
                    $inputFieldSpecification[$key . '.max'] = "The $key  may not be greater than 191 characters.";
                }
                if ($cus->type == 'textarea') {
                    array_push($rules[$key], 'max:3000');
                    $inputFieldSpecification[$key . '.max'] = "The $key  may not be greater than 3000 characters.";
                }
            }
        }

        $rulesSpecification = [];
        if ($category->post_specification_form != null) {
            foreach ($category->post_specification_form as $key => $cus) {
                $rulesSpecification[$key] = [$cus->validation];
                $inputFieldSpecification[$key . '.' . $cus->validation] = "The $key field is required.";

                if ($cus->type == 'file') {
                    array_push($rulesSpecification[$key], 'image');
                    array_push($rulesSpecification[$key], 'mimes:jpeg,jpg,png');
                    array_push($rulesSpecification[$key], 'max:10240');

                    $inputFieldSpecification[$key . '.image'] = "The $key must be an image.";
                    $inputFieldSpecification[$key . '.mimes'] = "The $key must be type of png, jpeg,10240kb characters.";

                }
                if ($cus->type == 'text') {
                    array_push($rulesSpecification[$key], 'max:191');
                    $inputFieldSpecification[$key . '.max'] = "The $key  may not be greater than 191 characters.";
                }
                if ($cus->type == 'textarea') {
                    array_push($rulesSpecification[$key], 'max:3000');
                    $inputFieldSpecification[$key . '.max'] = "The $key  may not be greater than 3000 characters.";
                }
            }
        }

        $purifiedData = $request->all();

        $newRules = array_merge($rules, $rulesSpecification);
        $validate = Validator::make($purifiedData, $newRules, $inputFieldSpecification);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }


            $gameSell = new SellPost();
            $gameSell->user_id = Auth()->user()->id;
            $gameSell->category_id = $purifiedData['category'];
            $gameSell->sell_charge = $category->sell_charge;


            $images = array();
            $imagesDriver = null;
            if ($request->hasFile('image')) {
                try {
                    $gameImage = $purifiedData['image'];
                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver = $imageUp['driver'];
                    }
                } catch (\Exception $exp) {
                    return response()->json($this->withErrors('Image could not be uploaded.'));
                }
                $gameSell->image = $images;
                $gameSell->image_driver = $imagesDriver;
            }

            if (isset($purifiedData['title'])) {
                $gameSell->title = $request->title;
            }
            if (isset($purifiedData['price'])) {
                $gameSell->price = $request->price;
            }

            if (isset($purifiedData['credential'])) {
                $gameSell->credential = $request->credential;
            }

            if (isset($purifiedData['details'])) {
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['comments'])) {
                $gameSell->comments = $request->comments;
            }

            if (isset($purifiedData['status'])) {
                $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
            }


            $collection = collect($request);
            $reqField = [];
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {

                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);;
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return response()->json($this->withErrors('Image could not be uploaded.'));
                                    }
                                }
                            } else {
                                $reqField[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                            }
                        }
                    }
                }
                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }

            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {

                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return response()->json($this->withErrors('Image could not be uploaded.'));
                                    }

                                }
                            } else {
                                $reqFieldSpecification[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                            }
                        }
                    }
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }

            $gameSell->save();
            return response()->json($this->withSuccess('Game Successfully Saved'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function sellPostList(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $sellLists = tap(SellPost::whereUser_id(Auth()->user()->id)->orderBy('id', 'DESC')
                ->when(@$search['title'], function ($query) use ($search) {
                    return $query->where('title', 'LIKE', "%{$search['title']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->paginate($basic->paginate), function ($paginatedInstance) use ($basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($basic) {
                    $array['id'] = $query->id;
                    $array['title'] = $query->title ?? null;
                    $array['paymentStatus'] = $query->payment_status ? 'sold' : 'unsold';
                    $array['category'] = optional(optional($query->category)->details)->name;
                    $array['price'] = getAmount($query->price, $basic->fraction_number);
                    $array['currency'] = $basic->base_currency ?? null;
                    $array['symbol'] = $basic->currency_symbol ?? null;
                    if ($query->status == 1) {
                        $array['status'] = 'Approved';
                    } elseif ($query->status == 0) {
                        $array['status'] = 'Pending';
                    } elseif ($query->status == 2) {
                        $array['status'] = 'Re Submission';
                    } elseif ($query->status == 3) {
                        $array['status'] = 'Hold';
                    } elseif ($query->status == 4) {
                        $array['status'] = 'Soft Rejected';
                    } elseif ($query->status == 5) {
                        $array['status'] = 'Hard Rejected';
                    }
                    $array['dateTime'] = $query->created_at ?? null;
                    return $array;
                });
            });

            if ($sellLists) {
                return response()->json($this->withSuccess($sellLists));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }



    public function sellPostEdit(Request $request)
    {
        $data['sellPost'] = SellPost::where('user_id', auth()->id())->find($request->id);
        if (!$data['sellPost']) {
            return response()->json($this->withErrors('Data not found'));
        }

        $images = is_array($data['sellPost']->image) ? $data['sellPost']->image : (array) json_decode($data['sellPost']->image, true);

        if (!empty($images)) {
            $imagePath = [];
            foreach ($images as $key => $img) {
                $imagePath[$key] = getFile($data['sellPost']->image_driver, $img);
            }

            $data['sellPost']->imagePath = (object) $imagePath;
        }

        return response()->json($this->withSuccess($data));
    }


    public function sellPostUpdate(Request $request)
    {
        $purifiedData = $request->all();
        if ($request->has('image')) {
            $purifiedData['image'] = $request->image;
        }

        $rules = [
            'id' => 'required|numeric',
            'title' => 'required|max:40',
            'price' => 'required|numeric|min:1',
            'details' => 'required',
            'comments' => 'required',
            'image' => 'sometimes|required'
        ];
        $message = [
            'id.required' => 'Id field is required',
            'name.required' => 'Name field is required',
            'price.required' => 'Price field is required',
            'details.required' => 'Details field is required',
            'comments.required' => 'Comments field is required',
            'image.required' => 'Image field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        DB::beginTransaction();
        try {

            $gameSell = SellPost::find($request->id);
            if (!$gameSell) {
                return response()->json($this->withErrors('sell post not found'));
            }

            $gameSell->user_id = Auth()->user()->id;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'file') {
                        array_push($rules[$key], 'image');
                        array_push($rules[$key], 'mimes:jpeg,jpg,png');
                        array_push($rules[$key], 'max:10240');
                    }
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'file') {
                        array_push($rulesSpecification[$key], 'image');
                        array_push($rulesSpecification[$key], 'mimes:jpeg,jpg,png');
                        array_push($rulesSpecification[$key], 'max:10240');
                    }
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }


            $newRules = array_merge($rules, $rulesSpecification);


            $validate = Validator::make($purifiedData, $newRules);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $collection = collect($request);
            $reqField = [];
            $credentialChanges = '';
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {
                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);;
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return back()->with('error', 'Image could not be uploaded.')->withInput();
                                    }

                                }
                            } else {
                                $reqField[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                            }
                            if ($gameSell->credential->$inKey->field_value != $v) {
                                $credentialChanges .= "$inKey : " . $v . "<br>";
                            }
                        }
                    }
                }
                if (0 < strlen($credentialChanges)) {
                    $credentialChanges = "Changes Credentials <br>" . $credentialChanges;
                }


                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }

            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            $specificationChanges = '';
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {

                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);;
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return back()->with('error', 'Image could not be uploaded.')->withInput();
                                    }

                                }
                            } else {
                                $reqFieldSpecification[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                                if ($gameSell->post_specification_form->$inKey->field_value != $v) {
                                    $specificationChanges .= "$inKey : " . $v . "<br>";
                                }
                            }
                        }
                    }
                }
                if (0 < strlen($specificationChanges)) {
                    $specificationChanges = "Changes Specification <br>" . $specificationChanges;
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }

            $changeImage = '';
            $images = array();

            if ($request->hasFile('image')) {
                if ($gameSell->image != $request->image) {
                    $changeImage = ' Image has been updated ' . "<br>";
                }
                try {
                    $gameImage = $purifiedData['image'];
                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $imageOld) {
                            $this->fileDelete($gameSell->image_driver, $imageOld);
                        }
                    }
                    $oldImages = $request->oldImage ?? [];
                    $mergedImages = array_merge($images, $oldImages);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver;

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }


            $changesTitle = '';
            if (isset($purifiedData['title'])) {
                if ($gameSell->title != $request->title) {
                    $changesTitle = 'Title ' . $gameSell->title . ' updated to ' . $request->title . "<br>";
                }
                $gameSell->title = $request->title;

            }

            $changesPrice = '';
            if (isset($purifiedData['price'])) {
                if ($gameSell->price != $request->price) {
                    $changesPrice = 'Price ' . $gameSell->price . ' updated to ' . $request->price . "<br>";
                }
                $gameSell->price = $request->price;
            }


            $changesDetails = '';
            if (isset($purifiedData['details'])) {
                if ($gameSell->details != $request->details) {
                    $changesDetails = "Details has been Updated <br>";
                }
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['comments'])) {
                $gameSell->comments = $request->comments;
            }

            $gameSell->status = 2;
            $gameSell->save();


            $user = Auth::user();

            if ($changesTitle . $changesPrice . $credentialChanges . $specificationChanges . $changesDetails . $changeImage != '') {
                $activity = new ActivityLog();
                $activity->sell_post_id = $request->id;
                $activity->title = "Resubmission";
                $activity->description = $changesTitle . $changesPrice . $changeImage . $credentialChanges . $specificationChanges . $changesDetails;
                $user->activities()->save($activity);
            }

            DB::commit();
            return response()->json($this->withSuccess('Successfully Updated'));
        } catch (\Exception$e) {
            DB::rollBack();
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function offerList(Request $request)
    {
        $data['sellPostAll'] = SellPost::whereUser_id(Auth::id())->whereStatus(1)->get();
        $dateTrx = $request->datetrx ?? null;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateTrx);

        $query = SellPostOffer::query();
        $data['sellPostOffer'] = $query->with([
            'user:id,firstname,lastname,email,image,image_driver',
            'sellPost' => function ($query) {
                $query->select('id', 'user_id', 'category_id', 'title', 'price', 'details', 'comments', 'sell_charge', 'image', 'image_driver', 'status', 'lock_for', 'lock_at', 'payment_lock', 'payment_status', 'payment_uuid')
                    ->addSelect(\DB::raw("
                CASE
                    WHEN status = 0 THEN 'Not Approved'
                    WHEN status = 1 THEN 'Approved'
                    WHEN status = 2 THEN 'Re-submission'
                    WHEN status = 3 THEN 'Hold'
                    WHEN status = 4 THEN 'Soft Rejected'
                    WHEN status = 5 THEN 'Hard Rejected'
                    ELSE 'Unknown'
                END as status
            "));
            }
        ])
            ->where('author_id', Auth::id())
            ->orWhere('user_id', auth()->id())
            ->whereHas('sellPost')
            ->whereHas('user')
            ->when(request('postId', false), function ($q, $postId) {
                $q->where('sell_post_id', $postId);
            })
            ->when(request('remark', false), function ($q, $remark) {
                $q->where('description', 'like', "%$remark%")
                    ->orWhereHas('user', function ($subQuery) use ($remark) {
                        $subQuery->where('firstname', 'like', "%$remark%")->orWhere('lastname', 'like', "%$remark%");
                    });
            })
            ->when($date == 1, function ($query) use ($dateTrx) {
                return $query->whereDate("created_at", $dateTrx);
            })
            ->when(!request('sortBy', false), function ($query, $sortBy) {
                $query->orderBy('updated_at', 'desc');
            })
            ->when(request('sortBy', false), function ($query, $sortBy) {
                if ($sortBy == 'latest') {
                    $query->orderBy('updated_at', 'desc');
                }
                if ($sortBy == 'processing') {
                    $query->whereHas('sellPost', function ($qq) {
                        $qq->where('payment_lock', 1)->where('payment_status', 0)->whereNotNull('lock_at')->whereDate('lock_at', '<=', Carbon::now()->subMinutes(config('basic.payment_expired')));
                    })
                        ->where('status', 1)->where('payment_status', 0)->orderBy('amount', 'desc');
                }
                if ($sortBy == 'complete') {
                    $query->whereHas('sellPost', function ($qq) {
                        $qq->where('payment_lock', 1)->where('payment_status', 1);
                    })
                        ->where('status', 1)->where('payment_status', 1)->orderBy('amount', 'desc');
                }
                if ($sortBy == 'low_to_high') {
                    $query->orderBy('amount', 'asc');
                }
                if ($sortBy == 'high_to_low') {
                    $query->orderBy('amount', 'desc');
                }
                if ($sortBy == 'pending') {
                    $query->whereStatus(0)->orderBy('amount', 'desc');
                }

                if ($sortBy == 'rejected') {
                    $query->whereStatus(2)->orderBy('amount', 'desc');
                }
                if ($sortBy == 'resubmission') {
                    $query->whereStatus(3)->orderBy('amount', 'desc');
                }
            })->paginate(basicControl()->paginate)
            ->through(function ($offer) {
                $statusLabels = [
                    0 => 'Pending',
                    1 => 'Accepted',
                    2 => 'Rejected',
                    3 => 'Resubmission',
                ];

                $sellPost = optional($offer->sellPost);

                if ($sellPost->payment_lock == 1 && $sellPost->lock_for == $offer->user_id && $sellPost->payment_status == 0
                    && \Carbon\Carbon::now() < \Carbon\Carbon::parse($sellPost->lock_at)->addMinutes(basicControl()->payment_expired)) {
                    $offer->status = 'Payment Processing';
                } elseif ($sellPost->payment_lock == 1 && $sellPost->lock_for == $offer->user_id && $sellPost->payment_status == 1) {
                    $offer->status = 'Payment Completed';
                } else {
                    $offer->status = $statusLabels[$offer->status] ?? 'Unknown';
                }

                return $offer;
            });

        return response()->json($this->withSuccess($data));
    }

    public function offerAccept(Request $request)
    {
        $purifiedData = $request->all();
        $rules = [
            'offer_id' => 'required',
            'description' => 'required',
        ];
        $message = [
            'description.required' => 'Description field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);
        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        DB::beginTransaction();
        try {

            $offerDetails = SellPostOffer::find($request->offer_id);
            if (!$offerDetails) {
                return response()->json($this->withErrors('Offer record not found'));
            }

            if ($offerDetails->uuid != '') {
                return response()->json($this->withErrors('Offer Can not be accepted'));
            }
            if ($offerDetails->sell_post_id) {
                if (!$offerDetails->uuid) {
                    $offerDetails->uuid = Str::uuid();
                }
                $offerDetails->status = 1;
                $offerDetails->attempt_at = Carbon::now();
                $offerDetails->save();

                $user = Auth::user();
                $sellPostChat = new SellPostChat();
                $sellPostChat->sell_post_id = $offerDetails->sell_post_id;
                $sellPostChat->offer_id = $request->offer_id;
                $sellPostChat->description = $request->description;
                $user->sellChats()->save($sellPostChat);

                DB::commit();

                $user = $offerDetails->user;
                $msg = [
                    'title' => $offerDetails->sellPost->title,
                    'amount' => $offerDetails->amount . ' ' . basicControl()->base_currency,
                ];
                $action = [
                    "link" => route('user.offerChat', $offerDetails->uuid),
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $this->userPushNotification($user, 'OFFER_ACCEPTED', $msg, $action);

                $this->sendMailSms($user, 'OFFER_ACCEPTED', [
                    'link' => route('user.offerChat', $offerDetails->uuid),
                    'title' => $offerDetails->sellPost->title,
                    'amount' => $offerDetails->amount . ' ' . basicControl()->base_currency,
                ]);

                return response()->json($this->withSuccess('Accepted Offer'));
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function offerReject(Request $request)
    {
        $purifiedData = $request->all();
        $rules = [
            'offer_id' => 'required',
        ];
        $validate = Validator::make($purifiedData, $rules);
        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $sellPostOffer = SellPostOffer::findOrFail($request->offer_id);
        if (!$sellPostOffer) {
            return response()->json($this->withErrors('Offer record not found'));
        }
        if ($sellPostOffer->status != 2) {
            $sellPostOffer->update([
                'status' => 2
            ]);

            $user = $sellPostOffer->user;
            $msg = [
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $sellPostOffer->amount . ' ' . basicControl()->base_currency,
            ];
            $action = [
                "link" => route('sellPost.details', [@slug($sellPostOffer->sellPost->title), $sellPostOffer->sellPost->id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'OFFER_REJECT', $msg, $action);

            $this->sendMailSms($user, 'OFFER_REJECT', [
                'link' => route('sellPost.details', [@slug($sellPostOffer->sellPost->title), $sellPostOffer->sellPost->id]),
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $sellPostOffer->amount . ' ' . basicControl()->base_currency,
            ]);

            return response()->json($this->withSuccess('Reject Offer'));
        }
        return response()->json($this->withErrors('Already Rejected'));
    }

    public function offerRemove(Request $request)
    {
        $purifiedData = $request->all();
        $rules = [
            'offer_id' => 'required',
        ];
        $validate = Validator::make($purifiedData, $rules);
        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $sellPostOffer = SellPostOffer::with('sellPost')->find($request->offer_id);
        if (!$sellPostOffer) {
            return response()->json($this->withErrors('Offer record not found'));
        }
        if ($sellPostOffer) {
            $sellPostOffer->delete();
        }
        return response()->json($this->withSuccess('Remove Offer'));
    }

    public function offerConversation(Request $request)
    {
        $rules = [
            'uuid' => 'required',
        ];
        $validate = Validator::make($request->all(), $rules);
        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $auth = Auth::user();
        $data['loginUserId'] = $auth->id;

        $offerRequest = SellPostOffer::where('uuid', $request->uuid)
            ->firstOrFail();

        $siteNotifications = SellPostChat::whereHasMorph(
            'chatable',
            [
                User::class,
                Admin::class,
            ],
            function ($query) use ($offerRequest) {
                $query->where([
                    'offer_id' => $offerRequest->id,
                    'sell_post_id' => $offerRequest->sell_post_id
                ]);
            }
        )->with('chatable:id,username,phone,image,image_driver,firstname,lastname')->get();

        $offerRequest = SellPostOffer::where('uuid', $request->uuid)
            ->whereHas('user')
            ->whereHas('author')
            ->where(function ($query) use ($auth) {
                $query->where('user_id', $auth->id)
                    ->orWhere('author_id', $auth->id);
            })
            ->with('sellPost')
            ->first();


        if (!$offerRequest) {
            return response()->json($this->withErrors('Offer record not found'));
        }

        if (Auth::check() && $offerRequest->author_id == Auth::id()) {
            $data['isAuthor'] = true;
        } else {
            $data['isAuthor'] = false;
        }

        $data['offerRequest'] = $offerRequest;
        $data['siteNotifications'] = $siteNotifications;
        return response()->json($this->withSuccess($data));
    }

    public function offerNewMessage(Request $request)
    {
        $rules = [
            'offer_id' => ['required'],
            'sell_post_id' => ['required'],
            'message' => ['required']
        ];

        $req = $request->all();
        $validator = Validator::make($req, $rules);
        if ($validator->fails()) {
            return response()->json($this->withErrors(collect($validator->messages())->collapse()));
        }
        $user = Auth::user();

        $sellPostOffer = SellPostOffer::where('id', $request->offer_id)
            ->where('sell_post_id', $request->sell_post_id)
            ->first();

        if (!$sellPostOffer) {
            return response()->json($this->withErrors('Offer record not found'));
        }

        $chat = new SellPostChat();
        $chat->description = $req['message'];
        $chat->sell_post_id = $sellPostOffer->sell_post_id;
        $chat->offer_id = $sellPostOffer->id;
        $log = $user->chatable()->save($chat);


        $data['id'] = $log->id;
        $data['chatable_id'] = $log->chatable_id;
        $data['chatable_type'] = $log->chatable_type;
        $data['chatable'] = [
            'fullname' => $log->chatable->fullname,
            'id' => $log->chatable->id,
            'image' => $log->chatable->image,
            'mobile' => $log->chatable->mobile,
            'imgPath' => $log->chatable->imgPath,
            'username' => $log->chatable->username,
        ];
        $data['description'] = $log->description;
        $data['is_read'] = $log->is_read;
        $data['is_read_admin'] = $log->is_read_admin;
        $data['formatted_date'] = $log->formatted_date;
        $data['created_at'] = $log->created_at;
        $data['updated_at'] = $log->updated_at;

        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->author, $data, $sellPostOffer->uuid);
        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->user, $data, $sellPostOffer->uuid);

        event(new \App\Events\OfferChatNotification($data, $sellPostOffer->uuid));

        return response()->json($this->withSuccess('Message Send'));
    }


    public function paymentLock(Request $request)
    {
        $purifiedData = $request->all();
        $rules = [
            'offer_id' => 'required|numeric',
            'amount' => 'required|numeric|min:1',
        ];
        $message = ['amount.required' => 'Amount field is required',];

        $validate = Validator::make($purifiedData, $rules, $message);
        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        try {
            $sellPostOffer = SellPostOffer::with('sellPost')->find($request->offer_id);
            if (!$sellPostOffer) {
                return response()->json($this->withErrors('Offer record not found'));
            }

            if ($sellPostOffer->sellPost->payment_uuid != '') {
                return response()->json($this->withErrors('Payment can not be lock'));
            }

            if ($sellPostOffer->author_id != Auth::id()) {
                return response()->json($this->withErrors('404 not found'));
            }
            if ($sellPostOffer->sellPost->payment_lock == 1) {
                return response()->json($this->withErrors('Payment Allready Lock'));
            }

            $sellPostOffer->amount = $request->amount;
            $sellPostOffer->save();
            $sellPost = $sellPostOffer->sellPost;
            $sellPost->payment_lock = 1;
            $sellPost->lock_for = $sellPostOffer->user_id;
            $sellPost->lock_at = Carbon::now();
            $sellPost->payment_uuid = str::uuid();
            $sellPost->save();

            $user = $sellPostOffer->user;

            $msg = [
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $request->amount . ' ' . basicControl()->base_currency,
            ];
            $action = [
                "link" => route('user.sellPost.payment.url', $sellPostOffer->sellPost->payment_uuid),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'PAYMENT_LOCK', $msg, $action);

            $this->sendMailSms($user, 'PAYMENT_LOCK', [
                'link' => route('user.sellPost.payment.url', $sellPostOffer->sellPost->payment_uuid),
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $request->amount . ' ' . basicControl()->base_currency,
            ]);

            return response()->json($this->withSuccess('Payment Lock'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function sellPostDelete(Request $request)
    {
        $sellPost = SellPost::findOrFail($request->id);
        $old_images = $sellPost->image;

        if (!empty($old_images) && count($old_images) > 0) {
            foreach ($old_images as $img) {
                $this->fileDelete($sellPost->image_driver, $img);
            }
        }

        $sellPost->delete();
        return response()->json($this->withSuccess('Successfully Deleted'));
    }
}
PK     x\f    0  Http/Controllers/Api/TwoFASecurityController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Helpers\UserSystemInfo;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use PragmaRX\Google2FA\Google2FA;

class TwoFASecurityController extends Controller
{
    use ApiValidation, Notify;

    public function twoFASecurity()
    {
        $basic = basicControl();
        $user = auth()->user();
        try {
            $data['twoFactorEnable'] = auth()->user()->two_fa == 0 ? false : true;
            $google2fa = new Google2FA();
            $secret = $user->two_fa_code ?? $this->generateSecretKeyForUser($user);

            $data['qrCodeUrl'] = $google2fa->getQRCodeUrl(
                auth()->user()->username,
                $basic->site_title,
                $secret
            );
            $data['downloadApp'] = 'https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en';
            $data['secret'] = $secret;
            return response()->json($this->withSuccess($data));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    private function generateSecretKeyForUser(User $user)
    {
        $google2fa = new Google2FA();
        $secret = $google2fa->generateSecretKey();
        $user->update(['two_fa_code' => $secret]);

        return $secret;
    }

    public function twoFASecurityEnable(Request $request)
    {

        $user = auth()->user();
        $secret = auth()->user()->two_fa_code;
        $google2fa = new Google2FA();
        $valid = $google2fa->verifyKey($secret, $request->code);
        if ($valid) {
            $user['two_fa'] = 1;
            $user['two_fa_verify'] = 1;
            $user->save();

            $this->mail($user, 'TWO_STEP_ENABLED', [
                'action' => 'Enabled',
                'code' => $request->code,
                'ip' => request()->ip(),
                'browser' => UserSystemInfo::get_browsers() . ', ' . UserSystemInfo::get_os(),
                'time' => date('d M, Y h:i:s A'),
            ]);

            return response()->json($this->withSuccess('Google Authenticator Has Been Enabled.'));
        } else {
            return response()->json($this->withErrors('Wrong Verification Code.'));
        }
    }

    public function twoFASecurityDisable(Request $request)
    {
        if (!$request->password || !Hash::check($request->password, auth()->user()->password)) {
            return response()->json($this->withErrors('Incorrect password. Please try again.'));
        }

        // Disable two-factor authentication for the user
        auth()->user()->update([
            'two_fa' => 0,
            'two_fa_verify' => 1,
            //   'two_fa_code' => null, // Optionally clear the stored secret
        ]);
        return response()->json($this->withSuccess('Two-step authentication disabled successfully.'));
    }
}
PK     x\\_7  _7  *  Http/Controllers/Api/MyOrderController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use App\Models\User;
use App\Traits\ApiValidation;
use Illuminate\Http\Request;

class MyOrderController extends Controller
{
    use ApiValidation;

    public function topUpOrder(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $topUpOrders = tap(Order::with(['orderDetails', 'orderDetails.detailable'])
                ->with([
                    'orderDetails.detailable' => function ($query) {
                        $query->when(method_exists($query->getModel(), 'topUp'), function ($query) {
                            $query->with(['topUp.reviewByReviewer']);
                        });
                    }
                ])
                ->own()
                ->payment()
                ->type('topup')
                ->orderBy('id', 'DESC')
                ->when(@$search['transaction_id'], function ($query) use ($search) {
                    return $query->where('transaction', 'LIKE', "%{$search['transaction_id']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->paginate($basic->paginate), function ($paginatedInstance) use ($basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($basic) {
                    $array = [
                        'utr' => $query->utr ?? null,
                        'price' => getAmount($query->amount, $basic->fraction_number),
                        'currency' => $basic->base_currency ?? null,
                        'symbol' => $basic->currency_symbol ?? null,
                        'status' => $query->status == 1 ? 'Complete' : (($query->status == 2) ? 'Refunded' : 'Wait Sending'),
                        'dateTime' => $query->created_at ?? null,
                        'order_details' => [],
                    ];

                    foreach ($query->orderDetails as $detail) {
                        $array['order_details'][] = [
                            'utr' => $query->utr ?? null,
                            'rating' => $detail->detailable?->topUp?->reviewByReviewer?->rating ?? 0,
                            'image' => $detail->detailable?->image ? getFile($detail->detailable->image_driver, $detail->detailable->image) : null,
                            'discount' => getAmount($detail->discount, $basic->fraction_number),
                            'quantity' => $detail->qty,
                            'name' => $detail->detailable?->topUp?->name,
                            'service' => $detail->detailable?->name,
                            'base_price' => $detail->detailable?->price,
                            'currency' => $basic->base_currency ?? null,
                            'symbol' => $basic->currency_symbol ?? null,
                            'slug' => $detail->detailable->topUp->slug,
                        ];

                        $array['review_user_info'][] = [
                            'review' => [
                                'comment' => $detail->detailable->topUp->reviewByReviewer->comment ?? null,
                                'rating' => $detail->detailable->topUp->reviewByReviewer->rating ?? 0,
                                'status' => ($detail->detailable->topUp->reviewByReviewer->status ?? null) == 1 ? 'active' : 'inactive',
                            ],
                        ];

                    }
                    $array['informations'] = [];
                    if (!empty($query->info)) {
                        foreach ($query->info as $info) {
                            $array['informations'][$info->field] = $info->value;
                        }
                    }

                    return $array;
                });
            });


            if ($topUpOrders) {
                return response()->json($this->withSuccess($topUpOrders));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }
    public function cardOrder(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $topUpOrders = tap(Order::with(['orderDetails', 'orderDetails.detailable'])
                ->with([
                    'orderDetails.detailable' => function ($query) {
                        $query->when(method_exists($query->getModel(), 'card'), function ($query) {
                            $query->with(['card.reviewByReviewer']);
                        });
                    }
                ])
                ->own()
                ->payment()
                ->type('card')
                ->orderBy('id', 'DESC')
                ->when(@$search['transaction_id'], function ($query) use ($search) {
                    return $query->where('transaction', 'LIKE', "%{$search['transaction_id']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->paginate($basic->paginate), function ($paginatedInstance) use ($basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($basic) {
                    $array = [
                        'utr' => $query->utr ?? null,
                        'price' => getAmount($query->amount, $basic->fraction_number),
                        'currency' => $basic->base_currency ?? null,
                        'symbol' => $basic->currency_symbol ?? null,
                        'status' => $query->status == 1 ? 'Complete' : (($query->status == 2) ? 'Refunded' : 'Wait Sending'),
                        'dateTime' => $query->created_at ?? null,
                        'order_details' => [],
                    ];

                    foreach ($query->orderDetails as $detail) {
                        $array['order_details'][] = [
                            'utr' => $query->utr ?? null,
                            'id' => $detail->detailable?->card?->id ?? null,
                            'rating' => $detail->detailable?->card?->avg_rating ?? null,
                            'image' => $detail->detailable?->image ? getFile($detail->detailable->image_driver, $detail->detailable->image) : null,
                            'card' => $detail->detailable->card->name ?? null,
                            'slug' => $detail->detailable->card->slug ?? null,
                            'service' => $detail->detailable->name ?? null,
                            'base_price' => $detail->detailable->price ?? null,
                            'currency' => $basic->base_currency ?? null,
                            'symbol' => $basic->currency_symbol ?? null,
                            'discount' => getAmount($detail->discount, $basic->fraction_number),
                            'quantity' => $detail->qty,
                            'card_codes' => empty($detail->card_codes)
                                ? []
                                : (json_decode($detail->card_codes, true) ?: []),
                            'stock_short' => "You have {$detail->stock_short} more code in wait sending list" ,
                        ];



                        $array['review_user_info'][] = [
                            'review' => [
                                'comment' => $detail->detailable->card->reviewByReviewer->comment ?? null,
                                'rating' => $detail->detailable->card->reviewByReviewer->rating ?? null,
                                'status' => ($detail->detailable->card->reviewByReviewer->status ?? null) == 1 ? 'active' : 'inactive',
                            ],
                        ];
                    }
                    $array['informations'] = [];
                    if (!empty($query->info)) {
                        foreach ($query->info as $info) {
                            $array['informations'][$info->field] = $info->value;
                        }
                    }

                    return $array;
                });
            });


            if ($topUpOrders) {
                return response()->json($this->withSuccess($topUpOrders));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }
    public function idPurchase(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $idPurchases = tap(SellPostPayment::with('sellPost')->where('user_id', auth()->id())
                ->wherePayment_status(1)->orderBy('id', 'DESC')
                ->when(@$search['transaction_id'], function ($query) use ($search) {
                    return $query->where('transaction', 'LIKE', "%{$search['transaction_id']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->paginate($basic->paginate), function ($paginatedInstance) use ($basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($basic) {
                    $array['trx'] = $query->transaction ?? null;
                    $array['category'] = optional(optional(optional($query->sellPost)->category)->details)->name;
                    $array['title'] = optional($query->sellPost)->title;
                    $array['amount'] = getAmount($query->price, $basic->fraction_number);
                    $array['discount'] = getAmount($query->discount, $basic->fraction_number);
                    $array['currency'] = $basic->base_currency ?? null;
                    $array['symbol'] = $basic->currency_symbol ?? null;
                    $array['dateTime'] = $query->created_at ?? null;
                    $array['moreInformation'] = optional($query->sellPost)->credential ?? [];
                    return $array;
                });
            });

            if ($idPurchases) {
                return response()->json($this->withSuccess($idPurchases));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function myOrder(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $myOffers = tap(SellPostPayment::with(['sellPost', 'sellPost.category.details'])
                ->whereUser_id(auth()->id())
                ->wherePayment_status(1)
                ->orderBy('id', 'DESC')
                ->when(@$search['transaction_id'], function ($query) use ($search) {
                    return $query->where('transaction', 'LIKE', "%{$search['transaction_id']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->paginate($basic->paginate), function ($paginatedInstance) use ($basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($basic) {
                    $array['id'] = $query->id ?? null;
                    $array['category'] = optional(optional($query->sellPost)->category)->details->name ?? null;
                    $array['title'] = optional($query->sellPost)->title;
                    $array['sellingStatus'] = optional($query->sellPost)->payment_status == 1 ? 'sold' : 'unsold';
                    $array['price'] = getAmount(optional($query->sellPost)->price, $basic->fraction_number);
                    $array['offerPrice'] = getAmount($query->amount, $basic->fraction_number);
                    $array['currency'] = $basic->base_currency ?? null;
                    $array['symbol'] = $basic->currency_symbol ?? null;
                    if ($query->status) {
                        $array['status'] = 'Accept';
                    } elseif ($query->status == 0) {
                        $array['status'] = 'Pending';
                    } elseif ($query->status == 2) {
                        $array['status'] = 'Reject';
                    } elseif ($query->status == 3) {
                        $array['status'] = 'Resubmission';
                    }
                    $array['dateTime'] = $query->created_at ?? null;
                    $array['sellPostId'] = $query->sell_post_id;
                    $array['credential'] = $query->sellPost?->credential;
                    $array['post_specification_form'] = $query->sellPost?->post_specification_form;
                    return $array;
                });
            });

            if ($myOffers) {
                return response()->json($this->withSuccess($myOffers));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }
}
PK     x\F=nA  nA  '  Http/Controllers/Api/ShopController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\PaymentController;
use App\Models\Card;
use App\Models\CardService;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\ApiPayment;
use App\Traits\ApiValidation;
use App\Traits\MakeOrder;
use App\Traits\Rating;
use App\Traits\Upload;
use App\Models\Category;
use App\Models\Gateway;
use Facades\App\Services\BasicService;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class ShopController extends Controller
{
    use ApiValidation, Upload, ApiPayment, Rating, MakeOrder;

    public function addFund(Request $request)
    {
        $rules = [
            'amount' => 'required',
            'gateway' => 'required', 'numeric',
            'selectedCurrency' => 'required',
        ];

        $message = [
            'gateway.required' => 'Please select a gateway',
            'selectedCurrency.required' => 'Please select a currency',
        ];

        $validate = Validator::make($request->all(), $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $checkAmountValidate = $this->validationCheck($request->amount, $request->gateway, $request->selectedCurrency);

        if (!$checkAmountValidate['status']) {
            return response()->json($this->withErrors($checkAmountValidate['message']));
        }

        $deposit = Deposit::create([
            'user_id' => auth()->id(),
            'payment_method_id' => $checkAmountValidate['gateway_id'],
            'payment_method_currency' => $checkAmountValidate['currency'],
            'amount' => $checkAmountValidate['amount'],
            'percentage_charge' => $checkAmountValidate['percentage_charge'],
            'fixed_charge' => $checkAmountValidate['fixed_charge'],
            'payable_amount' => $checkAmountValidate['payable_amount'],
            'amount_in_base' => $checkAmountValidate['payable_amount_baseCurrency'],
            'charge_base_currency' => $checkAmountValidate['charge_baseCurrency'],
            'status' => 0,
        ]);

        $val['trxId'] = $deposit->trx_id;
        return response()->json($this->withSuccess($val));
    }

    public function topUpList(Request $request)
    {
        $basic = basicControl();

        $topUp = $basic->top_up
            ? TopUp::query()->with(['services'])->whereStatus(1)->get()
            : collect();

        if ($request->has('sortByCategory') || $request->has('search') || $request->has('category_id')) {
            if ($request->filled('sortByCategory')) {
                $category = (int)$request->sortByCategory;
                $topUp = $topUp->filter(function ($item) use ($category) {
                    return $item->category_id == $category;
                });
            }

            if ($request->has('search')) {
                $search = strtolower($request->search);
                $topUp = $topUp->filter(function ($item) use ($search) {
                    return str_contains(strtolower($item->name), $search);
                });
            }
            if ($request->has('sort_by')) {
                $topUp = $topUp->when($request->has('sort_by') && !empty($request->sort_by), function ($query) use ($request) {
                    if ($request->sort_by == 'all') {
                        $query->orderBy('sort_by', 'desc');
                    } elseif ($request->sort_by == 'top_rated') {
                        $query->orderBy('avg_rating', 'desc');
                    } elseif ($request->sort_by == 'desc') {
                        $query->latest();
                    } elseif ($request->sort_by == 'asc') {
                        $query->orderBy('created_at', 'asc');
                    }
                });
            }

            if ($request->has('offered')) {
                $offered = (int)$request->offered;
                $topUp = $topUp->filter(function ($item) use ($offered) {
                    return $item->services->contains(fn($service) => $service->offered_sell == $offered);
                });
            }

            if ($request->filled('category_id')) {
                $category = (int)$request->category_id;

                $topUp = $topUp->filter(function ($item) use ($category) {
                    return $item->category_id == $category;
                });
            }
        }

        $perPage = config(basicControl()->paginate, 10);
        $currentPage = LengthAwarePaginator::resolveCurrentPage();
        $totalItems = $topUp->count();

        $paginatedItems = new LengthAwarePaginator(
            $topUp->forPage($currentPage, $perPage),
            $totalItems,
            $perPage,
            $currentPage,
            ['path' => LengthAwarePaginator::resolveCurrentPath()]
        );

        $data = [
            "current_page" => $paginatedItems->currentPage(),
            "items" => array_values($paginatedItems->items()),
            "first_page_url" => $paginatedItems->url(1),
            "from" => ($currentPage - 1) * $perPage + 1,
            "last_page" => $paginatedItems->lastPage(),
            "last_page_url" => $paginatedItems->url($paginatedItems->lastPage()),
            "links" => $paginatedItems->linkCollection(),
            "next_page_url" => $paginatedItems->nextPageUrl(),
            "path" => $paginatedItems->path(),
            "per_page" => $perPage,
            "prev_page_url" => $paginatedItems->previousPageUrl(),
            "to" => min($currentPage * $perPage, $totalItems),
            "total" => $totalItems
        ];

        return response()->json($this->withSuccess($data));
    }

    public function topUpCategories(Request $request)
    {
        try {
            $data['categories'] = Category::query()->where('status', 1)->where('type', 'top_up')->get();

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function topUpDetails(Request $request)
    {
        try {
            $slug = $request->query('slug');

            if (!$slug) {
                return response()->json($this->withErrors('Slug is required.'));
            }

            $topUp = TopUp::with('activeServices')
                ->where('status', 1)
                ->where('slug', $slug)
                ->firstOrFail();

            if (!empty($topUp->order_information)) {
                $topUp->order_information = array_values((array)$topUp->order_information);
            }

            if (!empty($topUp->description)) {
                $topUp->description = strip_tags($topUp->description);
            }

            if (!empty($topUp->guide)) {
                $topUp->guide = strip_tags($topUp->guide);
            }

            foreach ($topUp->activeServices as $service) {
                $service->currency = basicControl()->base_currency;
                $service->currency_symbol = basicControl()->currency_symbol;
                $service->discountedAmount = $service->getDiscount();
                $service->discountedPriceWithoutDiscount = $service->price - $service->discountedAmount;

                if (isset($service->campaign_data)) {
                    $service->campaign_data->currency = basicControl()->base_currency;
                    $service->campaign_data->currency_symbol = basicControl()->currency_symbol;
                }
            }

            $reviewStatic = $this->getTopReview(TopUp::class, $topUp->id);

            $gateways = Gateway::where('status', 1)
                ->orderBy('sort_by')
                ->get()
                ->map(function ($gateway) {
                    $gateway->image = getFile($gateway->driver, $gateway->image);
                    return $gateway;
                });

            return response()->json($this->withSuccess([
                'topUp' => $topUp,
                'reviewStatic' => $reviewStatic,
                'gateways' => $gateways,
            ]));
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return response()->json($this->withErrors('Top-up not found.'), 404);
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()), 500);
        }
    }

    public function topUpOrder(Request $request)
    {
        $rules = [
            'topUpId' => ['required', 'numeric'],
            'serviceId' => ['required', 'numeric'],
        ];

        $message = [
            'serviceId.required' => 'Please select a recharge option',
        ];

        $validate = Validator::make($request->all(), $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        try {
            $service = TopUpService::whereHas('topUp', function ($query) {
                $query->where('status', 1);
            })->where('status', 1)->findOrFail($request->serviceId);
            $topUp = $service->topUp;

            $rules = [];
            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    $rules[$cus->field_name] = ['required'];
                    if ($cus->field_type == 'select') {
                        $options = implode(',', array_keys((array)$cus->option));
                        array_push($rules[$cus->field_name], 'in:' . $options);
                    }
                }
            }

            $validate = Validator::make($request->all(), $rules, $message);
            if ($validate->fails()) {
                return response()->json($this->withErrors(collect($validate->errors())->collapse()));
            }

            $info = [];

            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    if (isset($request->{$cus->field_name})) {
                        $info[$cus->field_name] = [
                            'field' => $cus->field_value,
                            'value' => $request->{$cus->field_name},
                        ];
                    }
                }
            }

            $order = $this->orderCreate(showActualPrice($service), 'topup', $info);
            $this->orderDetailsCreate($order, $service, TopUpService::class);


            return response()->json($this->withSuccess(['utr' => $order->utr]));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function topUpMakePayment(Request $request)
    {
        $rules = [
            'gateway_id' => ['nullable', 'numeric'],
            'supported_currency' => 'nullable',
        ];

        $message = [
            'gateway_id.required' => 'Please select a gateway',
        ];

        $validate = Validator::make($request->all(), $rules, $message);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        DB::beginTransaction();
        try {
            $order = Order::where('utr', $request->utr)->first();
            if (!$order) {
                return response()->json($this->withErrors('Order not found.'));
            }

            if ($order->amount > 0) {
                if (isset($request->gateway_id) && $request->gateway_id == '-1') {

                    $payByWallet = $this->payByWallet($order);

                    if (!$payByWallet['status']) {
                        return response()->json($this->withErrors($payByWallet['message']));
                    }
                    DB::commit();
                    return response()->json($this->withSuccess(['Order has been placed successfully']));
                }

                $gateway = Gateway::select(['id', 'status'])->where('status', 1)->find($request->gateway_id);
                if (!$gateway) {
                    return response()->json($this->withErrors('Gateway not found.'));
                }
                $checkAmountValidate = $this->validationCheck($order->amount, $gateway->id, $request->supported_currency, null, 'yes');

                if (!$checkAmountValidate['status']) {
                    return response()->json($this->withErrors($checkAmountValidate['message']));
                }

                $deposit = $this->depositCreate($checkAmountValidate, Order::class, $order->id);
                DB::commit();
                return response()->json($this->withSuccess(['id' => $deposit->id]));
            } else {
                return response()->json($this->withErrors('Unable to processed order'));
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function cardOrder(Request $request)
    {
        $rules = [
            'serviceIds' => ['required'],
            'quantity' => ['required'],
        ];

        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        try {
            $services = CardService::whereHas('card', function ($query) {
                $query->where('status', 1);
            })->where('status', 1)->whereIn('id', $request->serviceIds)->get();

            $totalAmount = 0;
            if (!empty($services)) {
                foreach ($services as $key => $service) {
                    $totalAmount += (showActualPrice($service) * $request->quantity[$key]);
                }
            }

            $order = $this->orderCreate($totalAmount, 'card', null, 'API', auth()->user());

            $this->orderDetailsCreate($order, $services, CardService::class, $request->quantity);

            return response()->json($this->withSuccess(['utr' => $order->utr]));

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function cardMakePayment(Request $request)
    {
        $rules = [
            'utr' => ['required'],
            'gateway_id' => ['nullable', 'numeric'],
            'selectedCurrency' => 'nullable',
        ];

        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        DB::beginTransaction();
        try {

            $order = Order::where('utr', $request->utr)->first();
            if (!$order) {
                return response()->json($this->withErrors('Order not found.'));
            }

            if ($order->amount > 0) {
                if (isset($request->gateway_id) && $request->gateway_id == '-1') {
                    $payByWallet = $this->payByWallet($order);
                    if (!$payByWallet['status']) {
                        return response()->json($this->withErrors($payByWallet['message']));
                    }

                    DB::commit();
                    return response()->json($this->withSuccess(['Order has been placed successfully']));
                }

                $gateway = Gateway::select(['id', 'status'])->where('status', 1)->findOrFail($request->gateway_id);
                if (!$gateway) {
                    return response()->json($this->withErrors('Gateway not found.'));
                }

                $checkAmountValidate = $this->validationCheck($order->amount, $gateway->id, $request->supported_currency, null, 'yes');

                if (!$checkAmountValidate['status']) {
                    return response()->json($this->withErrors($checkAmountValidate['message']));
                }

                $deposit = $this->depositCreate($checkAmountValidate, Order::class, $order->id);
                DB::commit();
                return response()->json($this->withSuccess(['id' => $deposit->id]));
            } else {
                return response()->json($this->withErrors('Unable to processed order'));
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

}
PK     x\#\  #\  '  Http/Controllers/Api/HomeController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Jobs\UserTrackingJob;
use App\Models\Campaign;
use App\Models\CardService;
use App\Models\Category;
use App\Models\ContentDetails;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\Language;
use App\Models\Order;
use App\Models\Payout;
use App\Models\SellPost;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use App\Models\SupportTicket;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Models\Transaction;
use App\Traits\ApiValidation;
use App\Traits\MakeOrder;
use App\Traits\Notify;
use App\Traits\PaymentValidationCheck;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class HomeController extends Controller
{
    use ApiValidation, Notify;

    public function language(Request $request)
    {
        try {
            if (!$request->id) {
                $data['languages'] = Language::select(['id', 'name', 'short_name'])->where('status', 1)->get();
                return response()->json($this->withSuccess($data));
            }
            $lang = Language::where('status', 1)->find($request->id);
            if (!$lang) {
                return response()->json($this->withErrors('Record not found'));
            }

            $json = file_get_contents(resource_path('lang/') . $lang->short_name . '.json');
            if (empty($json)) {
                return response()->json($this->withErrors('File Not Found.'));
            }

            $json = json_decode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
            return response()->json($this->withSuccess($json));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function appConfig()
    {
        try {
            $basic = basicControl();
            $data['baseColor'] = $basic['app_color'];
            $data['version'] = $basic['app_version'];
            $data['appBuild'] = $basic['app_build'];
            $data['isMajor'] = $basic['is_major'];
            $data['paymentSuccessUrl'] = route('success');
            $data['paymentFailedUrl'] = route('failed');

            $data['top_up_module'] = $basic['top_up'] ? 'on' : 'off';
            $data['card_module'] = $basic['card'] ? 'on' : 'off';
            $data['sell_post_module'] = $basic['sell_post'] ? 'on' : 'off';

            return response()->json($this->withSuccess($data));
        } catch (\Exception $exception) {
            return response()->json($this->withErrors($exception->getMessage()));
        }
    }

    public function transaction()
    {
        $basic = basicControl();
        try {
            $array = [];
            $transactions = tap(auth()->user()->transaction()->orderBy('id', 'DESC')
                ->paginate($basic->paginate), function ($paginatedInstance) use ($array, $basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                    if ($query->transactional_type == \App\Models\Deposit::class){
                        $type = 'deposit';
                    }elseif ($query->transactional_type == \App\Models\Order::class){
                        $type = 'order';
                    }elseif ($query->transactional_type == \App\Models\Payout::class){
                        $type = 'payout';
                    }elseif ($query->transactional_type == \App\Models\SellPostPayment::class){
                        $type = 'Sell Post';
                    }else{
                        $type = '-';
                    }

                    $array['transactionId'] = $query->trx_id ?? null;
                    $array['color'] = ($query->trx_type == '+') ? 'success' : 'danger';
                    $array['amount'] = $query->amount_in_base;
                    $array['remarks'] = $query->remarks ?? null;
                    $array['trx_type'] = $query->trx_type;
                    $array['type'] = $type;
                    $array['currency'] = basicControl()->base_currency;
                    $array['currency_symbol'] = basicControl()->currency_symbol;



                    $array['time'] = $query->created_at ?? null;
                    return $array;
                });
            });

            if ($transactions) {
                return response()->json($this->withSuccess($transactions));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function campaign()
    {
        $data['campaign'] = Campaign::firstOrNew();
        $data['trendingTopUpServices'] = TopUpService::has('topUp')->with(['topUp:id,slug,avg_rating,total_review'])
            ->where('status', 1)
            ->where('is_offered', 1)->orderBy('sort_by', 'ASC')->get();

        return response()->json($this->withSuccess($data));
    }

    public function transactionSearch(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $array = [];
            $transactions = tap(Transaction::where('user_id', auth()->id())->with('user')
                ->when(@$search['transaction_id'], function ($query) use ($search) {
                    return $query->where('trx_id', 'LIKE', "%{$search['transaction_id']}%");
                })
                ->when(@$search['remark'], function ($query) use ($search) {
                    return $query->where('remarks', 'LIKE', "%{$search['remark']}%");
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->orderBy('id', 'DESC')
                ->paginate(basicControl()->paginate), function ($paginatedInstance) use ($array, $basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                    if ($query->transactional_type == \App\Models\Deposit::class){
                        $type = 'deposit';
                    }elseif ($query->transactional_type == \App\Models\Order::class){
                        $type = 'order';
                    }elseif ($query->transactional_type == \App\Models\Payout::class){
                        $type = 'payout';
                    }elseif ($query->transactional_type == \App\Models\SellPostPayment::class){
                        $type = 'Sell Post';
                    }else{
                        $type = '-';
                    }
                    $array['transactionId'] = $query->trx_id ?? null;
                    $array['color'] = ($query->trx_type == '+') ? 'success' : 'danger';
                    $array['amount'] = $query->amount_in_base  ?? null;
                    $array['remarks'] = $query->remarks ?? null;
                    $array['time'] = $query->created_at ?? null;
                    $array['trx_type'] = $query->trx_type;
                    $array['type'] = $type;
                    $array['currency'] = basicControl()->base_currency;
                    $array['currency_symbol'] = basicControl()->currency_symbol;

                    return $array;
                });
            });

            if ($transactions) {
                return response()->json($this->withSuccess($transactions));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function paymentHistory()
    {
        $basic = basicControl();
        try {
            $array = [];
            $funds = tap(Deposit::query()->where('user_id', auth()->id())->where('status', '!=', 0)->orderBy('id', 'DESC')
                ->with('gateway')
                ->latest()
                ->paginate($basic->paginate), function ($paginatedInstance) use ($array, $basic) {
                    return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                        $array['transactionId'] = $query->trx_id ?? null;
                        $array['gateway'] = optional($query->gateway)->name ?? null;
                        $array['gatewayimage'] = getFile($query->gateway->driver, $query->gateway->image) ?? null;
                        $array['currency_symbol'] = basicControl()->currency_symbol ?? null;
                        $array['currency'] = basicControl()->base_currency ?? null;
                        $array['amount'] = $query->amount_in_base;
                        $array['status'] = match ($query->status) {
                            1 => 'Successful',
                            2 => 'Pending',
                            3 => 'Rejected',
                            default => 'Unknown',
                        };
                        $array['time'] = $query->created_at;
                        return $array;
                    });
                });

            if ($funds) {
                return response()->json($this->withSuccess($funds));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function paymentHistorySearch(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();

        $dateSearch = $request->date_time;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $array = [];
            $funds = tap(Deposit::query()->where('user_id', auth()->id())->where('status', '!=', 0)
                ->when(isset($search['name']), function ($query) use ($search) {
                    return $query->where('trx_id', 'LIKE', $search['name']);
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->when(isset($search['status']), function ($query) use ($search) {
                    return $query->where('status', $search['status']);
                })
                ->with('gateway')
                ->latest()
                ->paginate($basic->paginate), function ($paginatedInstance) use ($array, $basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                    $array['transactionId'] = $query->trx_id ?? null;
                    $array['gateway'] = optional($query->gateway)->name ?? null;
                    $array['gatewayimage'] = getFile($query->gateway->driver, $query->gateway->image) ?? null;
                    $array['currency_symbol'] = basicControl()->currency_symbol ?? null;
                    $array['currency'] = basicControl()->base_currency ?? null;
                    $array['amount'] = $query->amount_in_base;
                    $array['status'] = match ($query->status) {
                        1 => 'Successful',
                        2 => 'Pending',
                        3 => 'Rejected',
                        default => 'Unknown',
                    };
                    $array['time'] = $query->created_at;
                    return $array;
                });
            });

            if ($funds) {
                return response()->json($this->withSuccess($funds));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutHistory()
    {
        $basic = basicControl();
        try {
            $array = [];
            $payoutLogs = tap(Payout::whereUser_id(auth()->id())->where('status', '!=', 0)->latest()
                ->with('user', 'method')
                ->paginate(basicControl()->paginate), function ($paginatedInstance) use ($array, $basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                    $array['transactionId'] = $query->trx_id ?? null;
                    $array['gateway'] = getFile(optional($query->method)->driver, optional($query->method)->logo)  ?? null;
                    $array['gatewayImage'] = optional($query->method)->name ?? null;
                    $array['amount'] = getAmount($query->amount, $basic->fraction_number);
                    $array['payoutCurrency'] = $query->payout_currency_code;
                    $array['amountInBase'] = currencyPosition($query->amount_in_base_currency);
                    $array['currency'] = $basic->base_currency ?? null;
                    $array['symbol'] = $basic->currency_symbol ?? null;
                    $array['status'] = ($query->status == 1) ? 'Pending' : (($query->status == 2) ? 'Complete' : 'Cancel');
                    $array['time'] = $query->created_at ?? null;
                    $array['adminFeedback'] = $query->feedback ?? null;
                    $array['paymentInformation'] = [];
                    if ($query->information) {
                        foreach ($query->information as $key => $info) {
                            if ($info->type == 'file') {
                                $array['paymentInformation'][$key] = getFile($info->field_driver, $info->field_value);
                            } else {
                                $array['paymentInformation'][$key] = $info->field_value ?? $info->field_name;
                            }
                        }
                    }
                    return $array;
                });
            });

            if ($payoutLogs) {
                return response()->json($this->withSuccess($payoutLogs));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function payoutHistorySearch(Request $request)
    {
        $basic = basicControl();
        $search = $request->all();

        $dateSearch = $request->date_time;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        try {
            $array = [];
            $payoutLogs = tap(Payout::orderBy('id', 'DESC')->where('user_id', auth()->id())
                ->where('status', '!=', 0)
                ->when(isset($search['name']), function ($query) use ($search) {
                    return $query->where('trx_id', 'LIKE', $search['name']);
                })
                ->when($date == 1, function ($query) use ($dateSearch) {
                    return $query->whereDate("created_at", $dateSearch);
                })
                ->when(isset($search['status']), function ($query) use ($search) {
                    return $query->where('status', $search['status']);
                })
                ->with('user', 'method')
                ->paginate($basic->paginate), function ($paginatedInstance) use ($array, $basic) {
                return $paginatedInstance->getCollection()->transform(function ($query) use ($array, $basic) {
                    $array['transactionId'] = $query->trx_id ?? null;
                    $array['gatewayImage'] = getFile(optional($query->method)->driver, optional($query->method)->logo)  ?? null;
                    $array['gateway'] = optional($query->method)->name ?? null;
                    $array['amount'] = getAmount($query->amount, $basic->fraction_number) ?? 0;
                    $array['payoutCurrency'] = $query->payout_currency_code;
                    $array['amountInBase'] = currencyPosition($query->amount_in_base_currency);
                    $array['currency'] = $basic->base_currency ?? null;
                    $array['symbol'] = $basic->currency_symbol ?? null;
                    $array['status'] = ($query->status == 1) ? 'Pending' : (($query->status == 2) ? 'Complete' : 'Cancel');
                    $array['time'] = $query->created_at ?? null;
                    $array['adminFeedback'] = $query->feedback ?? null;
                    $array['paymentInformation'] = [];
                    if ($query->information) {
                        foreach ($query->information as $key => $info) {
                            if ($info->type == 'file') {
                                $array['paymentInformation'][$key] = getFile($info->field_driver, $info->field_value);
                            } else {
                                $array['paymentInformation'][$key] = $info->field_value ?? $info->field_name;
                            }
                        }
                    }
                    return $array;
                });
            });

            if ($payoutLogs) {
                return response()->json($this->withSuccess($payoutLogs));
            } else {
                return response()->json($this->withErrors('No data found'));
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function paymentView($deposit_id)
    {
        $deposit = Deposit::latest()->find($deposit_id);
        try {
            if ($deposit) {
                $getwayObj = 'App\\Services\\Gateway\\' . $deposit->gateway->code . '\\Payment';
                $data = $getwayObj::prepareData($deposit, $deposit->gateway);
                $data = json_decode($data);

                if (isset($data->error)) {
                    $result['status'] = false;
                    $result['message'] = $data->message;
                    return response($result, 200);
                }

                if (isset($data->redirect)) {
                    return redirect($data->redirect_url);
                }

                if ($data->view) {
                    $parts = explode(".", $data->view);
                    $desiredValue = end($parts);
                    $newView = 'mobile-payment.' . $desiredValue;
                    return view($newView, compact('data', 'deposit'));
                }

                abort(404);
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function getGateways()
    {
        $gateways = Gateway::where('status', 1)->get()->map(function ($query) {
            $query->image = getFile($query->driver, $query->image );
            if ($query->id < 1000) {
                $query->makeHidden(['extra_parameters']);
            }
            return $query;
        });

        $data['gateways'] = $gateways;
        return response()->json($this->withSuccess($data));
    }

    public function pusherConfig()
    {
        try {
            $data['apiKey'] = env('PUSHER_APP_KEY');
            $data['cluster'] = env('PUSHER_APP_CLUSTER');
            $data['channel'] = 'user-notification.' . Auth::id();
            $data['event'] = 'UserNotification';

            $data['chattingChannel'] = 'offer-chat-notification.' . Auth::id();

            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function dashboard()
    {
        $banner = ContentDetails::whereHas('content', function ($query) {
            $query->where('name', 'app_page');
        })->first();

        if ($banner) {
            $data['banner'] = $banner->description;
            $data['banner']->image = getFile(@$banner->content->media->image->driver, @$banner->content->media->image->path);
        }

        $user = auth()->user();
        $basic = basicControl();
        $data['orderInfo'] = Order::payment()->own()
            ->selectRaw('COUNT(CASE WHEN order_for = "topup" THEN id END) AS totalTopUpOrder')
            ->selectRaw('COUNT(CASE WHEN order_for = "card" THEN id END) AS totalCardOrder')
            ->first();

        $data['baseCurrency'] = $basic->base_currency;
        $data['baseCurrencySymbol'] = $basic->currency_symbol;
        $data['walletBalance'] = $user->balance;
        $data['sellingPost'] = SellPost::tobase()->where('user_id', $user->id)->where('status', 1)->count();
        $data['soldPost'] = SellPost::tobase()->where('user_id', $user->id)->where('status', 1)->where('payment_status', 1)->count();
        $data['buyPost'] = SellPostPayment::tobase()->where('user_id', $user->id)->where('payment_status', 1)->count();
        $data['supportTickets'] = SupportTicket::tobase()->where('user_id', $user->id)->count();
        $data['payoutBalance'] = Payout::tobase()->where('user_id', $user->id)->where('status', 2)->sum('amount_in_base_currency');
        $data['myProposal'] = SellPostOffer::tobase()->where('user_id', $user->id)->count();


        $data['upcoming'] = collect(SellPostPayment::where('payment_status', 1)->where('payment_release', 0)
            ->selectRaw('SUM(price) as upComingAmount')
            ->selectRaw('COUNT(id) AS upComingPayment')
            ->get()->toArray())->collapse();

        return response()->json($this->withSuccess($data));
    }

    public function getCategory()
    {
        try {
            $data['categories'] = Category::active()->sort()->get()
                ->makeHidden(['status','sort_by','deleted_at','created_at','updated_at']);
            return response()->json($this->withSuccess($data));
        } catch (\Exception $e) {
            return response()->json($this->withErrors('Something went wrong'));
        }
    }

    public function getCampaign()
    {
        $data['campaign'] = Campaign::firstOrNew();

        $data['campaign']['topups'] = TopUpService::where('status',1)->where('is_offered',1)
            ->get()->makeHidden(['image','image_driver','is_offered','sort_by']);

        $data['campaign']['cards'] = CardService::where('status',1)->where('is_offered',1)
            ->get()->makeHidden(['image','image_driver','is_offered','sort_by']);

        return response()->json($this->withSuccess($data));
    }

    public function apiKey(Request $request)
    {
        $user = auth()->user();
        $public_key = $user->public_key;
        $secret_key = $user->secret_key;
        if (!$public_key || !$secret_key) {
            $user->public_key = 'pk' . bin2hex(random_bytes(20));
            $user->secret_key = 'sk' . bin2hex(random_bytes(20));
            $user->save();
        }

        return response()->json($this->withSuccess(['public_key' => $public_key, 'secret_key' => $secret_key]));
    }
    public function apiKeyUpdate(Request $request)
    {
        $user = auth()->user();
        $user->public_key = 'pk' . bin2hex(random_bytes(20));
        $user->secret_key = 'sk' . bin2hex(random_bytes(20));
        $user->save();

        $remark = 'Generated API key';
        UserTrackingJob::dispatch($user->id, request()->ip(), $remark);

        return response()->json($this->withSuccess(['Api key generated successfully']));
    }

}
PK     x\>E    /  Http/Controllers/Api/VerificationController.phpnu [        <?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Traits\ApiValidation;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use PragmaRX\Google2FA\Google2FA;

class VerificationController extends Controller
{
    use ApiValidation, Notify;

    public function twoFAverify(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'code' => 'required',
            ]);

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }

        try {
            $user = Auth::user();
            $secret = auth()->user()->two_fa_code;

            $google2fa = new Google2FA();
            $valid = $google2fa->verifyKey($secret, $request->code);

            if ($valid) {
                $user->two_fa_verify = 1;
                $user->save();
                return response()->json($this->withSuccess('Verified Successfully.'));
            }

            return response()->json($this->withErrors('Wrong Verification Code.'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function mailVerify(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'code' => 'required',
            ],
            [
                'code.required' => 'Email verification code is required',
            ]
        );

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }
        try {
            $user = auth()->user();
            if ($this->checkValidCode($user, $request->code)) {
                $user->email_verification = 1;
                $user->verify_code = null;
                $user->sent_at = null;
                $user->save();
                return response()->json($this->withSuccess('Verified Successfully.'));
            }
            return response()->json($this->withErrors('Verification code didn\'t match!'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function smsVerify(Request $request)
    {
        $validateUser = Validator::make($request->all(),
            [
                'code' => 'required',
            ],
            [
                'code.required' => 'Sms verification code is required',
            ]
        );

        if ($validateUser->fails()) {
            return response()->json($this->withErrors(collect($validateUser->errors())->collapse()));
        }
        try {
            $user = Auth::user();
            if ($this->checkValidCode($user, $request->code)) {
                $user->sms_verification = 1;
                $user->verify_code = null;
                $user->sent_at = null;
                $user->save();

                return response()->json($this->withSuccess('Verified Successfully.'));
            }
            return response()->json($this->withErrors('Verification code didn\'t match!'));
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function checkValidCode($user, $code, $add_min = 10000)
    {
        if (!$code) return false;
        if (!$user->sent_at) return false;
        if (Carbon::parse($user->sent_at)->addMinutes($add_min) < Carbon::now()) return false;
        if ($user->verify_code !== $code) return false;
        return true;
    }

    public function resendCode()
    {
        $type = request()->type;
        $user = auth()->user();
        if ($this->checkValidCode($user, $user->verify_code, 2)) {
            $target_time = Carbon::parse($user->sent_at)->addMinutes(2)->timestamp;
            $delay = $target_time - time();
            return response()->json($this->withErrors('Please Try after ' . gmdate("i:s", $delay) . ' minutes'));
        }
        if (!$this->checkValidCode($user, $user->verify_code)) {
            $user->verify_code = code(6);
            $user->sent_at = Carbon::now();
            $user->save();
        } else {
            $user->sent_at = Carbon::now();
            $user->save();
        }


        if ($type === 'email') {
            $this->verifyToMail($user, 'VERIFICATION_CODE', [
                'code' => $user->verify_code
            ]);
            return response()->json($this->withSuccess('Email verification code has been sent'));
        } elseif ($type === 'mobile') {
            $this->verifyToSms($user, 'VERIFICATION_CODE', [
                'code' => $user->verify_code
            ]);
            return response()->json($this->withSuccess('SMS verification code has been sent'));
        } else {
            return response()->json($this->withErrors('Sending Failed'));
        }
    }
}
PK     x\3+  +    Http/Controllers/Controller.phpnu [        <?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;

class Controller extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;
}
PK     x\2&E
  E
  0  Http/Controllers/InAppNotificationController.phpnu [        <?php

namespace App\Http\Controllers;

use App\Events\UpdateAdminNotification;
use App\Events\UpdateUserNotification;
use App\Models\Admin;
use App\Models\InAppNotification;
use App\Models\User;
use Illuminate\Support\Facades\Auth;

class InAppNotificationController extends Controller
{
    public function showByAdmin()
    {
        $siteNotifications = InAppNotification::whereHasMorph(
            'inAppNotificationable',
            [Admin::class],
            function ($query) {
                $query->where([
                    'in_app_notificationable_id' => Auth::id()
                ]);
            }
        )->latest()->get();

        return $siteNotifications;
    }

    public function show()
    {
        $siteNotifications = InAppNotification::whereHasMorph(
            'inAppNotificationable',
            [User::class],
            function ($query) {
                $query->where([
                    'in_app_notificationable_id' => Auth::id()
                ]);
            }
        )->latest()->get();
        return $siteNotifications;
    }

    public function readAt($id)
    {
        $siteNotification = InAppNotification::find($id);
        if ($siteNotification) {
            $siteNotification->delete();
            if (Auth::guard('admin')->check()) {
                event(new UpdateAdminNotification(Auth::id()));
            }
            else {
                event(new UpdateUserNotification(Auth::id()));
            }
            $data['status'] = true;
        } else {
            $data['status'] = false;
        }
        return $data;
    }

    public function readAllByAdmin()
    {
        $siteNotification = InAppNotification::whereHasMorph(
            'inAppNotificationable',
            [Admin::class],
            function ($query) {
                $query->where([
                    'in_app_notificationable_id' => Auth::id()
                ]);
            }
        )->delete();

        if ($siteNotification) {
            event(new UpdateAdminNotification(Auth::id()));
        }
        $data['status'] = true;
        return $data;
    }

    public function readAll()
    {

        $siteNotification = InAppNotification::whereHasMorph(
            'inAppNotificationable',
            [User::class],
            function ($query) {
                $query->where([
                    'in_app_notificationable_id' => Auth::id()
                ]);
            }
        )->delete();
        if ($siteNotification) {
            event(new UpdateUserNotification(Auth::id()));
        }

        $data['status'] = true;
        return $data;
    }
}
PK     x\	ïJ      .  Http/Controllers/ManualRecaptchaController.phpnu [        <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ManualRecaptchaController extends Controller
{
    public function reCaptCha()
    {
        renderCaptCha(request()->rand);
    }
}
PK     x\0>B=  =  '  Http/Controllers/FrontendController.phpnu [        <?php

namespace App\Http\Controllers;

use App\Mail\SendMail;
use App\Models\Card;
use App\Models\CardService;
use App\Models\Currency;
use App\Models\Gateway;
use App\Models\Language;
use App\Models\PageDetail;
use App\Models\SellPost;
use App\Models\SellPostCategory;
use App\Models\SellPostOffer;
use App\Models\Subscriber;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\Frontend;
use App\Traits\PaymentValidationCheck;
use App\Traits\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;


class FrontendController extends Controller
{
    use Frontend, Rating, PaymentValidationCheck;


    public function page($slug = '/')
    {
        $selectedTheme = getTheme() ?? 'light';
        $existingSlugs = collect([]);
        DB::table('pages')->select('slug')->get()->map(function ($item) use ($existingSlugs) {
            $existingSlugs->push($item->slug);
        });
        if (!in_array($slug, $existingSlugs->toArray())) {
            abort(404);
        }
        try {
            $pageDetails = PageDetail::with(['page'])
                ->whereHas('page', function ($query) use ($slug, $selectedTheme) {
                    $query->where(['slug' => $slug, 'template_name' => $selectedTheme]);
                })->first();

            $pageSeo = [
                'page_title' => optional($pageDetails->page)->page_title,
                'meta_title' => optional($pageDetails->page)->meta_title,
                'meta_keywords' => implode(',', optional($pageDetails->page)->meta_keywords ?? []),
                'meta_description' => optional($pageDetails->page)->meta_description,
                'og_description' => optional($pageDetails->page)->og_description,
                'meta_robots' => optional($pageDetails->page)->meta_robots,
                'meta_image' => getFile(optional($pageDetails->page)->meta_image_driver, optional($pageDetails->page)->meta_image),
                'breadcrumb_image' => optional($pageDetails->page)->breadcrumb_status ?
                    getFile(optional($pageDetails->page)->breadcrumb_image_driver, optional($pageDetails->page)->breadcrumb_image) : null,
            ];

            $sectionsData = $this->getSectionsData($pageDetails->sections, $pageDetails->content, $selectedTheme);
            return view("themes.{$selectedTheme}.page", compact('sectionsData', 'pageSeo'));
        } catch (\Exception $exception) {

            \Cache::forget('ConfigureSetting');
            if ($exception->getCode() == 404) {
                abort(404);
            }
            if ($exception->getCode() == 403) {
                abort(403);
            }
            if ($exception->getCode() == 401) {
                abort(401);
            }
            if ($exception->getCode() == 503) {
                return redirect()->route('maintenance');
            }
            if ($exception->getCode() == "42S02") {
                die($exception->getMessage());
            }
            if ($exception->getCode() == 1045) {
                die("Access denied. Please check your username and password.");
            }
            if ($exception->getCode() == 1044) {
                die("Access denied to the database. Ensure your user has the necessary permissions.");
            }
            if ($exception->getCode() == 1049) {
                die("Unknown database. Please verify the database name exists and is spelled correctly.");
            }
            if ($exception->getCode() == 2002) {
                die("Unable to connect to the MySQL server. Check the database host and ensure the server is running.");
            }
            return redirect()->route('instructionPage');

        }
    }

    public function reviewList(Request $request)
    {
        $type = $request->type;
        $id = $request->id;
        if (!$type || !$id) {
            abort(404);
        }

        if ($type == 'topup') {
            $class = TopUp::class;
        } elseif ($type == 'card') {
            $class = Card::class;
        } else {
            abort(404);
        }

        $data['game'] = $class::select(['id', 'status', 'name', 'region', 'image', 'total_review', 'avg_rating'])
            ->where('status', 1)->findOrFail($id);
        $data['reviewStatic'] = $this->getAllReviews($class, $id);
        return view(template() . 'frontend.review', $data);
    }

    public function contactSend(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|max:50',
            'con_email' => 'required|email|max:91',
            'subject' => 'required|max:100',
            'message' => 'required|max:1000',
        ]);
        $requestData = $request->except('_token', '_method');

        $name = $requestData['name'];
        $email_from = $requestData['con_email'];
        $subject = $requestData['subject'];
        $message = $requestData['message'] . "<br>Regards<br>" . $name;
        $from = $email_from;

        Mail::to(basicControl()->sender_email)->send(new SendMail($from, $subject, $message));
        return back()->with('success', 'Mail has been sent');
    }

    public function subscribe(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|email|min:8|max:100|unique:subscribers',
        ]);

        $purifiedData = $request->all();
        $purifiedData = (object)$purifiedData;

        $subscribe = new Subscriber();
        $subscribe->email = $purifiedData->email;
        $subscribe->save();

        return back()->with('success', 'Subscribed successfully');
    }

    public function navSearch(Request $request)
    {
        $query = $request->input('query');

        $topUpResult = TopUp::where('name', 'LIKE', '%' . $query . '%')->where('status', 1)->get();
        foreach ($topUpResult as $topUp) {
            $topUp->typeOf = 'topUp';
            $topUp->details_route = $topUp->top_up_detail_route;
            $topUp->preview = $topUp->preview_image;
        }

        $topUpServiceResult = TopUpService::with('topUp')->where('name', 'LIKE', '%' . $query . '%')->where('status', 1)->get();
        foreach ($topUpServiceResult as $topUpSerVice) {
            $topUpSerVice->typeOf = 'topUp Service';
            $topUpSerVice->details_route = optional($topUpSerVice->topUp)->top_up_detail_route;
            $topUpSerVice->preview = $topUpSerVice->image_path;
        }

        $cardResult = Card::where('name', 'LIKE', '%' . $query . '%')->where('status', 1)->get();
        foreach ($cardResult as $card) {
            $card->typeOf = 'card';
            $card->details_route = $card->card_detail_route;
            $card->preview = $card->preview_image;
        }
        $cardServiceResult = CardService::with('card')->where('name', 'LIKE', '%' . $query . '%')->where('status', 1)->get();
        foreach ($cardServiceResult as $cardService) {
            $cardService->typeOf = 'card Service';
            $cardService->details_route = optional($cardService->card)->card_detail_route;
            $cardService->preview = $cardService->image_path;
        }
        $results = collect();

        $results = $results->merge($topUpResult)->merge($topUpServiceResult)->merge($cardResult)->merge($cardServiceResult);

        return response()->json($results);
    }

    public function sellPost(Request $request)
    {
        $data['category'] = SellPostCategory::with('details')
            ->withCount([
                'activePost' => function ($query) {
                    $query->where('payment_status', '!=', '1')->where('status', 1);
                }
            ])
            ->where('status', 1)
            ->get();

        $baseQuery = SellPost::where('status', 1)
            ->where('payment_status', '!=', 1);
        $prices = $baseQuery->pluck('price');

        $rangeMin = $prices->min() ?? 10;
        $rangeMax = $prices->max() ?? 1000;

        list($min, $max) = array_pad(explode(';', $request->my_range, 2), 2, 0);

        $data['max'] = $request->has('my_range') ? $max : $rangeMax;
        $data['min'] = $request->has('my_range') ? $min : $rangeMin;
        $data['rangeMin'] = $rangeMin;
        $data['rangeMax'] = $rangeMax;

        $data['sellPost'] = $baseQuery
            ->when($request->has('category'), function ($query) use ($request) {
                $categories = collect($request->category)->map(function ($category) {
                    return Str::of($category)->replace('-', ' ')->title();
                });

                $query->whereHas('category.details', function ($query) use ($categories) {
                    $query->where(function ($query) use ($categories) {
                        foreach ($categories as $category) {
                            $query->orWhere('name', 'like', '%' . $category . '%');
                        }
                    });
                });
            })
            ->when($request->has('search'), function ($query) use ($request) {
                $query->where('title', 'like', '%' . $request->search . '%');
            })
            ->when($request->has('my_range'), function ($q) use ($min, $max) {
                $q->whereBetween('price', [$min, $max]);
            })
            ->when($request->has('sort'), function ($q) use ($request) {
                if ($request->sort == 'ltoh') {
                    $q->orderBy('price', 'asc');
                } elseif ($request->sort == 'htol') {
                    $q->orderBy('price', 'desc');
                } else {
                    $q->orderBy('updated_at', 'desc');
                }
            })
            ->paginate(9);

        return view(template() . 'frontend.sell_post.sell-post', $data);
    }

    public function sellPostDetails($slug = 'sell-post-details', $id)
    {
        $loginUser = SellPost::whereId($id)->pluck('user_id');

        if (Auth::check() == true && Auth::id() == $loginUser[0]) {
            $sellPost = SellPost::whereId($id)->first();
        } else {
            $sellPost = SellPost::where('id', $id)
                ->where('status', 1)
                ->first();
        }

        $data['sellPostOffer'] = SellPostOffer::has('user')->with('user')
            ->whereSell_post_id($id)->orderBy('amount', 'desc')->take(3)->get();
        $data['price'] = $sellPost->price;
        if (Auth::check()) {
            $user = Auth::user();
            $checkMyProposal = SellPostOffer::where([
                'user_id' => $user->id,
                'sell_post_id' => $sellPost->id,
                'status' => 1,
                'payment_status' => 0,
            ])->first();
            if ($checkMyProposal) {
                $data['price'] = (int)$checkMyProposal->amount;
            }
        }
        $data['sellPost'] = $sellPost;

        return view(template() . 'frontend.sell_post.sell-post-details', $data);
    }

    public function ajaxCheckSellPostCalc(Request $request)
    {
        $validator = validator()->make($request->all(), [
            'sellPostId' => 'required',
            'gatewayId' => 'required',
            'selectedCurrency' => 'nullable|required_unless:gatewayId,0'
        ]);
        if ($validator->fails()) {
            return response($validator->messages(), 422);
        }

        $sellPostId = $request->sellPostId;
        $sellPost = SellPost::where('id', $sellPostId)
            ->where('status', 1)
            ->first();

        if (!$sellPost) {
            return response()->json(['error' => 'This post already sold or not available to sell'], 422);
        }


        $price = $sellPost->price;
        if (Auth::check()) {
            $user = Auth::user();
            $checkMyProposal = SellPostOffer::where([
                'user_id' => $user->id,
                'sell_post_id' => $sellPost->id,
                'status' => 1,
                'payment_status' => 0,
            ])->first();
            if ($checkMyProposal) {
                $price = (int)$checkMyProposal->amount;
            }
        }

        $basic = basicControl();
        $discount = 0;

        $reqAmount = $price;
        $payable = $reqAmount - $discount;

        if ($request->gatewayId == '0') {
            return [
                'amount' => getAmount($reqAmount, 2),
                'discount' => getAmount($discount, 2),
                'subtotal' => getAmount($payable, 2),
                'charge' => 0 . ' ' . $basic->base_currency,
                'payable' => getAmount($payable, 2),
                'gateway_currency' => null,
                'baseCurrency' => $basic->base_currency,
                'isCrypto' => false,
                'gatewayId' => 0,
                'in' => trans("You need to pay ") . getAmount($payable, 2) . ' ' . $basic->base_currency . ' By ' . 'Wallet',
            ];
        } else {
            $gate = Gateway::where('id', $request->gatewayId)->where('status', 1)->first();
            if (!$gate) {
                return response()->json(['error' => 'Invalid Gateway'], 422);
            }
        }

        if (1000 > $gate->id) {
            $method_currency = (checkTo($gate->currencies, $gate->currency) == 1) ? 'USD' : $gate->currency;
            $isCrypto = (checkTo($gate->currencies, $gate->currency) == 1) ? true : false;
        } else {
            $method_currency = $gate->currency;
            $isCrypto = false;
        }

        $checkAmountValidate = $this->validationCheck($payable, $gate->id, $request->selectedCurrency, null, 'yes');
        if (!$checkAmountValidate['status']) {
            return response()->json(['error' => 'This currency is not available for this transaction'], 422);
        }

        return [
            'amount' => getAmount($reqAmount, 2),
            'discount' => getAmount($discount, 2),
            'subtotal' => getAmount($checkAmountValidate['amount'], 2),
            'charge' => getAmount($checkAmountValidate['charge'], 2),
            'payable' => getAmount($checkAmountValidate['payable_amount'], 2),
            'gateway_currency' => trans($gate->currency),
            'isCrypto' => $isCrypto,
            'gatewayId' => $request->gatewayId,
            'selectedCurrency' => $checkAmountValidate['currency'],
            'baseCurrency' => $basic->base_currency,
            'in' => trans("You need to pay ") . getAmount($checkAmountValidate['payable_amount'], 2) . ' ' . $checkAmountValidate['currency'] . ' By ' . $gate->name,
        ];

    }

    public function settingChange(Request $request)
    {
        $request->validate([
            'language' => 'required|exists:languages,short_name',
            'currency' => 'sometimes|exists:currencies,id',
        ]);


        $language = Language::where('short_name', $request->language)->firstOrFail();
        Artisan::call('cache:clear');
        session()->forget(['lang', 'rtl']);
        session()->put('lang', $language->short_name);
        session()->put('rtl', $language->rtl);

        $currency = Currency::where('status', 1)->find($request->currency);
        if ($currency) {
            session()->forget(['currency_code', 'currency_symbol', 'currency_rate']);
            session()->put('currency_code', $currency->code ?? basicControl()->base_currency);
            session()->put('currency_symbol', $currency->symbol ?? basicControl()->currency_symbol);
            session()->put('currency_rate', $currency->rate ?? 1);
        }

        return back()->with('success', 'Update Successfully');
    }
}
PK     x\[D!'  '  1  Http/Controllers/User/SupportTicketController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Jobs\UserTrackingJob;
use App\Models\Admin;
use App\Models\SupportTicket;
use App\Models\SupportTicketAttachment;
use App\Models\SupportTicketMessage;
use App\Traits\Notify;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class SupportTicketController extends Controller
{
    use Upload, Notify;


    public function index()
    {
        $tickets = SupportTicket::where('user_id', auth()->id())
            ->latest()
            ->paginate(basicControl()->paginate);

        return view(template() . "user.".getDash().".support_ticket.index", compact('tickets'));
    }

    public function create()
    {
        return view(template() . "user.".getDash().".support_ticket.create");
    }

    public function store(Request $request)
    {
        $random = rand(100000, 999999);
        $this->newTicketValidation($request);
        $ticket = $this->saveTicket($request, $random);
        $message = $this->saveMsgTicket($request, $ticket);

        if (!empty($request->attachments)) {
            $numberOfAttachments = count($request->attachments);
            for ($i = 0; $i < $numberOfAttachments; $i++) {
                if ($request->hasFile('attachments.' . $i)) {
                    $file = $request->file('attachments.' . $i);
                    $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), null, null, 'webp');
                    if (empty($supportFile['path'])) {
                        throw new \Exception('File could not be uploaded.');
                    }
                    $this->saveAttachment($message, $supportFile['path'], $supportFile['driver']);
                }
            }
        }

        $remark = 'Create new support ticket <a href="' . route('admin.ticket.view', $ticket->id) . '">Click here</a> to see details';
        UserTrackingJob::dispatch($ticket->user_id, request()->ip(), $remark);

        $msg = [
            'username' => optional($ticket->user)->fullname,
            'ticket_id' => $ticket->ticket
        ];
        $action = [
            "name" => optional($ticket->user)->firstname . ' ' . optional($ticket->user)->lastname,
            "image" => getFile(optional($ticket->user)->image_driver, optional($ticket->user)->image),
            "link" => route('admin.ticket.view', $ticket->id),
            "icon" => "fas fa-ticket-alt text-white"
        ];
        $this->adminPushNotification('SUPPORT_TICKET_CREATE', $msg, $action);
        $this->adminMail('SUPPORT_TICKET_CREATE', $msg);
        return redirect()->route('user.ticket.list')->with('success', 'Your ticket has been pending.');
    }

    public function ticketView($ticketId)
    {
        $ticket = SupportTicket::where('ticket', $ticketId)->latest()->with('messages')->firstOrFail();
        $user = Auth::user();
        $admin = Admin::firstOrNew();
        return view(template() . 'user.'.getDash().'.support_ticket.view', compact('ticket', 'user', 'admin'));
    }

    public function reply(Request $request, $id)
    {
        if ($request->reply_ticket == 1) {
            $images = $request->file('attachments');
            $allowedExtensions = array('jpg', 'png', 'jpeg', 'pdf');
            $this->validate($request, [
                'attachments' => [
                    'max:10240',
                    function ($fail) use ($images, $allowedExtensions) {
                        foreach ($images as $img) {
                            $ext = strtolower($img->getClientOriginalExtension());
                            if (($img->getSize() / 1000000) > 2) {
                                throw ValidationException::withMessages(['attachments' => "Images MAX  10MB ALLOW!"]);
                            }
                            if (!in_array($ext, $allowedExtensions)) {
                                throw ValidationException::withMessages(['attachments' => "Only png, jpg, jpeg, pdf images are allowed"]);
                            }
                        }
                        if (count($images) > 5) {
                            throw ValidationException::withMessages(['attachments' => "Maximum 5 images can be uploaded"]);
                        }
                    },
                ],
                'message' => 'required',
            ]);

            try {
                $ticket = SupportTicket::findOrFail($id);
                $ticket->update([
                    'status' => 2,
                    'last_reply' => Carbon::now()
                ]);

                $message = SupportTicketMessage::create([
                    'support_ticket_id' => $ticket->id,
                    'message' => $request->message
                ]);

                if (!empty($request->attachments)) {
                    $numberOfAttachments = count($request->attachments);
                    for ($i = 0; $i < $numberOfAttachments; $i++) {
                        if ($request->hasFile('attachments.' . $i)) {
                            $file = $request->file('attachments.' . $i);
                            $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), null, null, 'webp');
                            if (empty($supportFile['path'])) {
                                throw new \Exception('File could not be uploaded.');
                            }
                            $this->saveAttachment($message, $supportFile['path'], $supportFile['driver']);
                        }
                    }
                }

                $msg = [
                    'username' => optional($ticket->user)->username,
                    'ticket_id' => $ticket->ticket
                ];
                $action = [
                    "name" => optional($ticket->user)->firstname . ' ' . optional($ticket->user)->lastname,
                    "image" => getFile(optional($ticket->user)->image_driver, optional($ticket->user)->image),
                    "link" => route('admin.ticket.view', $ticket->id),
                    "icon" => "fas fa-ticket-alt text-white"
                ];

                $this->adminPushNotification('SUPPORT_TICKET_CREATE', $msg, $action);
                return back()->with('success', 'Ticket has been replied');
            } catch (\Exception $exception) {
                return back()->with('error', $exception->getMessage());
            }

        } elseif ($request->reply_ticket == 2) {
            $ticket = SupportTicket::findOrFail($id);
            $ticket->update([
                'status' => 3,
                'last_reply' => Carbon::now()
            ]);

            $remark = 'Support ticket closed <a href="' . route('admin.ticket.view', $ticket->id) . '">Click here</a> to see details';
            UserTrackingJob::dispatch($ticket->id, request()->ip(), $remark);

            return back()->with('success', 'Ticket has been closed');
        }
        return back();
    }


    public function newTicketValidation(Request $request): void
    {
        $images = $request->file('attachments');
        $allowedExtension = array('jpg', 'png', 'jpeg', 'pdf');

        $this->validate($request, [
            'attachments' => [
                'max:10240',
                function ($attribute, $value, $fail) use ($images, $allowedExtension) {
                    foreach ($images as $img) {
                        $ext = strtolower($img->getClientOriginalExtension());
                        if (($img->getSize() / 1000000) > 2) {
                            throw ValidationException::withMessages(['attachments' => "Images MAX  10MB ALLOW!"]);
                        }
                        if (!in_array($ext, $allowedExtension)) {
                            throw ValidationException::withMessages(['attachments' => "Only png, jpg, jpeg, pdf images are allowed"]);
                        }
                    }
                    if (count($images) > 5) {
                        throw ValidationException::withMessages(['attachments' => "Maximum 5 images can be uploaded"]);
                    }
                },
            ],
            'subject' => 'required|max:100',
            'message' => 'required'
        ]);
    }


    public function saveTicket(Request $request, $random)
    {
        try {
            $ticket = SupportTicket::create([
                'user_id' => auth()->id(),
                'ticket' => $random,
                'subject' => $request->subject,
                'status' => 0,
                'last_reply' => Carbon::now(),
            ]);

            if (!$ticket) {
                throw new \Exception('Something went wrong when creating the ticket.');
            }
            return $ticket;
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function saveMsgTicket(Request $request, $ticket)
    {
        try {
            $message = SupportTicketMessage::create([
                'support_ticket_id' => $ticket->id,
                'message' => $request->message
            ]);

            if (!$message) {
                throw new \Exception('Something went wrong when creating the ticket.');
            }
            return $message;
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function saveAttachment($message, $path, $driver)
    {
        try {
            $attachment = SupportTicketAttachment::create([
                'support_ticket_message_id' => $message->id,
                'file' => $path ?? null,
                'driver' => $driver ?? 'local',
            ]);

            if (!$attachment) {
                throw new \Exception('Something went wrong when creating the ticket.');
            }
            return true;
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

}
PK     x\&e=i  i  *  Http/Controllers/User/PayoutController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Traits\Notify;
use App\Traits\Upload;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Stevebauman\Purify\Facades\Purify;

class PayoutController extends Controller
{

    use Upload, Notify;


    public function index(Request $request)
    {
        $search = $request->all();
        $dateSearch = $request->date_time;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $payouts = Payout::with('method')->where('status', '!=', 0)
            ->where(['user_id' => Auth::id()])
            ->when(isset($search['name']), function ($query) use ($search) {
                return $query->where('trx_id', 'LIKE', $search['name']);
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->when(isset($search['status']), function ($query) use ($search) {
                return $query->where('status', $search['status']);
            })
            ->orderBy('id', 'desc')->paginate(basicControl()->paginate);
        return view(template() . 'user.'.getDash().'.payout.index', compact('payouts'));
    }

    public function payout()
    {
        $data['basic'] = basicControl();
        $data['payoutMethod'] = PayoutMethod::where('is_active', 1)->get();
        return view(template() . 'user.'.getDash().'.payout.request', $data);
    }

    public function payoutSupportedCurrency(Request $request)
    {
        $gateway = PayoutMethod::where('id', $request->gateway)->firstOrFail();
        return $gateway->supported_currency;
    }

    public function checkAmount(Request $request)
    {
        if ($request->ajax()) {
            $amount = $request->amount;
            $selectedCurrency = $request->selected_currency;
            $selectedPayoutMethod = $request->selected_payout_method;
            $data = $this->checkAmountValidate($amount, $selectedCurrency, $selectedPayoutMethod);
            return response()->json($data);
        }
        return response()->json(['error' => 'Invalid request'], 400);
    }

    public function checkAmountValidate($amount, $selectedCurrency, $selectedPayoutMethod)
    {

        $selectedPayoutMethod = PayoutMethod::where('id', $selectedPayoutMethod)->where('is_active', 1)->first();

        if (!$selectedPayoutMethod) {
            return ['status' => false, 'message' => "Payment method not available for this transaction"];
        }

        $selectedCurrency = array_search($selectedCurrency, $selectedPayoutMethod->supported_currency);

        if ($selectedCurrency !== false) {
            $selectedPayCurrency = $selectedPayoutMethod->supported_currency[$selectedCurrency];
        } else {
            return ['status' => false, 'message' => "Please choose the currency you'd like to use for payment"];
        }

        if ($selectedPayoutMethod) {
            $payoutCurrencies = $selectedPayoutMethod->payout_currencies;
            if (is_array($payoutCurrencies)) {
                if ($selectedPayoutMethod->is_automatic == 1) {
                    $currencyInfo = collect($payoutCurrencies)->where('name', $selectedPayCurrency)->first();
                } else {
                    $currencyInfo = collect($payoutCurrencies)->where('currency_symbol', $selectedPayCurrency)->first();
                }
            } else {
                return null;
            }
        }

        $currencyType = $selectedPayoutMethod->currency_type;
        $limit = $currencyType == 0 ? 8 : 2;

        $status = false;
        $amount = getAmount($amount, $limit);

        if ($currencyInfo) {
            $percentage = getAmount($currencyInfo->percentage_charge, $limit);
            $percentage_charge = getAmount(($amount * $percentage) / 100, $limit);
            $fixed_charge = getAmount($currencyInfo->fixed_charge, $limit);
            $min_limit = getAmount($currencyInfo->min_limit, $limit);
            $max_limit = getAmount($currencyInfo->max_limit, $limit);
            $charge = getAmount($percentage_charge + $fixed_charge, $limit);
        }
        $payout_amount = getAmount($amount + $charge, $limit);
        $payout_amount_in_base_currency = getAmount($amount / $currencyInfo->conversion_rate ?? 1, $limit);
        $charge_in_base_currency = getAmount($charge / $currencyInfo->conversion_rate ?? 1, $limit);
        $net_amount_in_base_currency = $payout_amount_in_base_currency + $charge_in_base_currency;


        $basicControl = basicControl();
        if ($amount < $min_limit || $amount > $max_limit) {
            $message = "minimum payment $min_limit and maximum payment limit $max_limit";
        } else {
            $status = true;
            $message = "Amount : $amount" . " " . $selectedPayCurrency;
        }

        $data['status'] = $status;
        $data['message'] = $message;
        $data['payout_method_id'] = $selectedPayoutMethod->id;
        $data['fixed_charge'] = $fixed_charge;
        $data['percentage'] = $percentage;
        $data['percentage_charge'] = $percentage_charge;
        $data['min_limit'] = $min_limit;
        $data['max_limit'] = $max_limit;
        $data['charge'] = $charge;
        $data['amount'] = $amount;
        $data['payout_charge'] = $charge;
        $data['net_payout_amount'] = $payout_amount;
        $data['amount_in_base_currency'] = $payout_amount_in_base_currency;
        $data['charge_in_base_currency'] = $charge_in_base_currency;
        $data['net_amount_in_base_currency'] = $net_amount_in_base_currency;
        $data['conversion_rate'] = getAmount($currencyInfo->conversion_rate) ?? 1;
        $data['currency'] = $currencyInfo->name ?? $currencyInfo->currency_symbol;
        $data['base_currency'] = $basicControl->base_currency;
        $data['currency_limit'] = $limit;

        return $data;

    }

    public function payoutRequest(Request $request)
    {
        $request->validate([
            'amount' => ['required', 'numeric'],
            'payout_method_id' => ['required'],
            'supported_currency' => ['required'],
        ]);
        try {
            if (!config('withdrawaldays')[date('l')]) {
                return back()->with('error', 'Withdraw processing is off today');
            }
            $amount = $request->amount;
            $payoutMethod = $request->payout_method_id;
            $supportedCurrency = $request->supported_currency;

            $checkAmountValidateData = $this->checkAmountValidate($amount, $supportedCurrency, $payoutMethod);

            if (!$checkAmountValidateData['status']) {
                return back()->withInput()->with('error', $checkAmountValidateData['message']);
            }
            $user = Auth::user();

            if ($user->balance < $checkAmountValidateData['net_amount_in_base_currency']) {
                throw new  \Exception('Insufficient Balance');
            }

            $payout = new Payout();
            $payout->user_id = $user->id;
            $payout->payout_method_id = $checkAmountValidateData['payout_method_id'];
            $payout->payout_currency_code = $checkAmountValidateData['currency'];
            $payout->amount = $checkAmountValidateData['amount'];
            $payout->charge = $checkAmountValidateData['payout_charge'];
            $payout->net_amount = $checkAmountValidateData['net_payout_amount'];
            $payout->amount_in_base_currency = $checkAmountValidateData['amount_in_base_currency'];
            $payout->charge_in_base_currency = $checkAmountValidateData['charge_in_base_currency'];
            $payout->net_amount_in_base_currency = $checkAmountValidateData['net_amount_in_base_currency'];
            $payout->information = null;
            $payout->feedback = null;
            $payout->status = 0;
            $payout->save();
            return redirect(route('user.payout.confirm', $payout->trx_id))->with('success', 'Payout initiated successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function confirmPayout(Request $request, $trx_id)
    {
        $payout = Payout::where('trx_id', $trx_id)->first();
        $payoutMethod = PayoutMethod::findOrFail($payout->payout_method_id);
        $basic = basicControl();

        if ($request->isMethod('get')) {
            if ($payoutMethod->code == 'flutterwave') {
                return view(template() . 'user.'.getDash().'.payout.gateway.' . $payoutMethod->code, compact('payout', 'payoutMethod', 'basic'));
            } elseif ($payoutMethod->code == 'paystack') {
                return view(template() . 'user.'.getDash().'.payout.gateway.' . $payoutMethod->code, compact('payout', 'payoutMethod', 'basic'));
            }
            return view(template() . 'user.'.getDash().'.payout.confirm', compact('payout', 'payoutMethod'));

        } elseif ($request->isMethod('post')) {

            $params = $payoutMethod->inputForm;
            $rules = [];
            if ($params !== null) {
                foreach ($params as $key => $cus) {
                    $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                    if ($cus->type === 'file') {
                        $rules[$key][] = 'image';
                        $rules[$key][] = 'mimes:jpeg,jpg,png';
                        $rules[$key][] = 'max:10240';
                    } elseif ($cus->type === 'text') {
                        $rules[$key][] = 'max:191';
                    } elseif ($cus->type === 'number') {
                        $rules[$key][] = 'integer';
                    } elseif ($cus->type === 'textarea') {
                        $rules[$key][] = 'min:3';
                        $rules[$key][] = 'max:300';
                    }
                }
            }

            $validator = Validator::make($request->all(), $rules);
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }

            $checkAmountValidate = $this->checkAmountValidate($payout->amount_in_base_currency, $payout->payout_currency_code, $payout->payout_method_id);
            if (!$checkAmountValidate['status']) {
                return back()->withInput()->with('error', $checkAmountValidate['message']);
            }
            $params = $payoutMethod->inputForm;
            $reqField = [];
            foreach ($request->except('_token', '_method', 'type', 'currency_code', 'bank') as $k => $v) {
                foreach ($params as $inKey => $inVal) {
                    if ($k == $inVal->field_name) {
                        if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                            try {
                                $file = $this->fileUpload($request[$inKey], config('filelocation.payoutLog.path'), null, null, 'webp', 60);
                                $reqField[$inKey] = [
                                    'field_name' => $inVal->field_name,
                                    'field_value' => $file['path'],
                                    'field_driver' => $file['driver'],
                                    'validation' => $inVal->validation,
                                    'type' => $inVal->type,
                                ];
                            } catch (\Exception $exp) {
                                session()->flash('error', 'Could not upload your ' . $inKey);
                                return back()->withInput();
                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'validation' => $inVal->validation,
                                'field_value' => $v,
                                'type' => $inVal->type,
                            ];
                        }
                    }
                }
            }


            $payoutMethod = PayoutMethod::find($payout->payout_method_id);


            $payoutCurrencies = $payoutMethod->payout_currencies;
            if ($payoutMethod->is_automatic == 1) {
                $currencyInfo = collect($payoutCurrencies)->where('name', $request->currency_code)->first();
            } else {
                $currencyInfo = collect($payoutCurrencies)->where('currency_symbol', $request->currency_code)->first();
            }
            $reqField['amount'] = [
                'field_name' => 'amount',
                'field_value' => currencyPosition($payout->amount / $currencyInfo->conversion_rate),
                'type' => 'text',
            ];


            if ($payoutMethod->code == 'paypal') {
                $reqField['recipient_type'] = [
                    'field_name' => 'receiver',
                    'validation' => $inVal->validation,
                    'field_value' => $request->recipient_type,
                    'type' => 'text',
                ];
            }
            $payout->information = $reqField;
            $payout->status = 1;

            $user = Auth::user();
            if ($payout->net_amount_in_base_currency > $user->balance) {
                return back()->with('error', 'Insufficient Balance to deducted.');
            }
            updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0);

            BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class, $payout->charge_in_base_currency);

            $this->userNotify($user, $payout);

            $payout->save();
            return redirect(route('user.payout.index'))->with('success', 'Payout generated successfully');

        }
    }

    public function paystackPayout(Request $request, $trx_id)
    {
        $basicControl = basicControl();
        $payout = Payout::where('trx_id', $trx_id)->first();
        $payoutMethod = PayoutMethod::findOrFail($payout->payout_method_id);

        if (empty($request->bank)) {
            return back()->with('error', 'Bank field is required')->withInput();
        }

        $checkAmountValidate = $this->checkAmountValidate($payout->amount_in_base_currency, $payout->payout_currency_code, $payout->payout_method_id);
        if (!$checkAmountValidate['status']) {
            return back()->withInput()->with('error', $checkAmountValidate['message']);
        }


        $rules = [];
        if ($payoutMethod->inputForm != null) {
            foreach ($payoutMethod->inputForm as $key => $cus) {
                $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                if ($cus->type === 'file') {
                    $rules[$key][] = 'image';
                    $rules[$key][] = 'mimes:jpeg,jpg,png';
                    $rules[$key][] = 'max:10240';
                } elseif ($cus->type === 'text') {
                    $rules[$key][] = 'max:191';
                } elseif ($cus->type === 'number') {
                    $rules[$key][] = 'integer';
                } elseif ($cus->type === 'textarea') {
                    $rules[$key][] = 'min:3';
                    $rules[$key][] = 'max:300';
                }
            }
        }

        $validate = Validator::make($request->all(), $rules);
        if ($validate->fails()) {
            return back()->withErrors($validate)->withInput();
        }

        $params = $payoutMethod->inputForm;
        $reqField = [];
        foreach ($request->except('_token', '_method', 'type', 'currency_code', 'bank') as $k => $v) {
            foreach ($params as $inKey => $inVal) {
                if ($k == $inVal->field_name) {
                    if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                        try {
                            $file = $this->fileUpload($request[$inKey], config('filelocation.payoutLog.path'));
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'field_value' => $file['path'],
                                'field_driver' => $file['driver'],
                                'validation' => $inVal->validation,
                                'type' => $inVal->type,
                            ];
                        } catch (\Exception $exp) {
                            session()->flash('error', 'Could not upload your ' . $inKey);
                            return back()->withInput();
                        }
                    } else {
                        $reqField[$inKey] = [
                            'field_name' => $inVal->field_name,
                            'validation' => $inVal->validation,
                            'field_value' => $v,
                            'type' => $inVal->type,
                        ];
                    }
                }
            }
        }

        $reqField['type'] = [
            'field_name' => "type",
            'field_value' => $request->type,
            'type' => 'text',
        ];
        $reqField['bank_code'] = [
            'field_name' => "bank_id",
            'field_value' => $request->bank,
            'type' => 'number',
        ];

        $payout->information = $reqField;
        $payout->status = 1;
        $payout->save();

        updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0); //update user balance
        BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class);



        if (optional($payout->payoutMethod)->is_automatic == 1 && $basicControl->automatic_payout_permission) {
            $this->automaticPayout($payout);
            return redirect()->route('user.payout.index');
        }

        return redirect()->route('user.payout.index')->with('success', 'Payout generated successfully');
    }


    public function flutterwavePayout(Request $request, $trx_id)
    {;
        $payout = Payout::with('method')->where('trx_id', $trx_id)->first();
        $purifiedData = $request->all();
        if (empty($purifiedData['transfer_name'])) {
            return back()->with('error', 'Transfer field is required');
        }
        $validation = config('banks.' . $purifiedData['transfer_name'] . '.validation');


        $rules = [];
        if ($validation != null) {
            foreach ($validation as $key => $cus) {
                $rules[$key] = 'required';
            }
        }

        if ($request->transfer_name == 'NGN BANK' || $request->transfer_name == 'NGN DOM' || $request->transfer_name == 'GHS BANK'
            || $request->transfer_name == 'KES BANK' || $request->transfer_name == 'ZAR BANK' || $request->transfer_name == 'ZAR BANK') {
            $rules['bank'] = 'required';
        }

        $rules['currency_code'] = 'required';


        $validate = Validator::make($request->all(), $rules);
        if ($validate->fails()) {

            return back()->withErrors($validate)->withInput();
        }

        $checkAmountValidate = $this->checkAmountValidate($payout->amount, $payout->payout_currency_code, $payout->payout_method_id);

        if (!$checkAmountValidate['status']) {
            return back()->withInput()->with('error', $checkAmountValidate['message']);
        }


        $collection = collect($purifiedData);
        $reqField = [];
        $metaField = [];

        if (config('banks.' . $purifiedData['transfer_name'] . '.input_form') != null) {
            foreach ($collection as $k => $v) {
                foreach (config('banks.' . $purifiedData['transfer_name'] . '.input_form') as $inKey => $inVal) {
                    if ($k != $inKey) {
                        continue;
                    } else {
                        if ($inVal == 'meta') {
                            $metaField[$inKey] = [
                                'field_name' => $k,
                                'field_value' => $v,
                                'type' => 'text',
                            ];
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $k,
                                'field_value' => $v,
                                'type' => 'text',
                            ];
                        }
                    }
                }
            }


            if ($request->transfer_name == 'NGN BANK' || $request->transfer_name == 'NGN DOM' || $request->transfer_name == 'GHS BANK'
                || $request->transfer_name == 'KES BANK' || $request->transfer_name == 'ZAR BANK' || $request->transfer_name == 'ZAR BANK') {

                $reqField['account_bank'] = [
                    'field_name' => 'Account Bank',
                    'field_value' => $request->bank,
                    'type' => 'text',
                ];
            } elseif ($request->transfer_name == 'XAF/XOF MOMO') {
                $reqField['account_bank'] = [
                    'field_name' => 'MTN',
                    'field_value' => 'MTN',
                    'type' => 'text',
                ];
            } elseif ($request->transfer_name == 'FRANCOPGONE' || $request->transfer_name == 'mPesa' || $request->transfer_name == 'Rwanda Momo'
                || $request->transfer_name == 'Uganda Momo' || $request->transfer_name == 'Zambia Momo') {
                $reqField['account_bank'] = [
                    'field_name' => 'MPS',
                    'field_value' => 'MPS',
                    'type' => 'text',
                ];
            }

            if ($request->transfer_name == 'Barter') {
                $reqField['account_bank'] = [
                    'field_name' => 'barter',
                    'field_value' => 'barter',
                    'type' => 'text',
                ];
            } elseif ($request->transfer_name == 'flutterwave') {
                $reqField['account_bank'] = [
                    'field_name' => 'barter',
                    'field_value' => 'barter',
                    'type' => 'text',
                ];
            }


            $payoutMethod = PayoutMethod::find($payout->payout_method_id);
            $payoutCurrencies = $payoutMethod->payout_currencies;
            $currencyInfo = collect($payoutCurrencies)->where('name', $request->currency_code)->first();

            $reqField['amount'] = [
                'field_name' => 'amount',
                'field_value' => $payout->amount * $currencyInfo->conversion_rate,
                'type' => 'text',
            ];

            $payout->information = $reqField;
            $payout->meta_field = $metaField;


        } else {
            $payout->information = null;
            $payout->meta_field = null;
        }

        $payout->status = 1;
        $payout->payout_currency_code = $request->currency_code;
        $payout->save();

        updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 0); //update user balance
        BasicService::makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '-', $payout->trx_id, 'Amount debited for payout', $payout->id, Payout::class);

        return redirect()->route('user.payout.index')->with('success', 'Payout generated successfully');

    }

    public function getBankList(Request $request)
    {
        $currencyCode = $request->currencyCode;
        $methodObj = 'App\\Services\\Payout\\paystack\\Card';
        $data = $methodObj::getBank($currencyCode);
        return $data;
    }

    public function getBankForm(Request $request)
    {
        $bankName = $request->bankName;
        $bankArr = config('banks.' . $bankName);

        if ($bankArr['api'] != null) {

            $methodObj = 'App\\Services\\Payout\\flutterwave\\Card';
            $data = $methodObj::getBank($bankArr['api']);
            $value['bank'] = $data;
        }
        $value['input_form'] = $bankArr['input_form'];
        return $value;
    }

    public function automaticPayout($payout)
    {
        $methodObj = 'App\\Services\\Payout\\' . optional($payout->payoutMethod)->code . '\\Card';
        $data = $methodObj::payouts($payout);

        if (!$data) {
            return back()->with('error', 'Method not available or unknown errors occur');
        }

        if ($data['status'] == 'error') {
            $payout->last_error = $data['data'];
            $payout->status = 3;
            $payout->save();
            return back()->with('error', $data['data']);
        }
    }

    public function userNotify($user, $payout)
    {
        $params = [
            'sender' => $user->name,
            'currency' => $payout->payout_currency_code,
            'amount' => number_format($payout->amount, 2),
            'transaction' => $payout->trx_id,
        ];

        $action = [
            "link" => route('admin.payout.log'),
            "icon" => "fa fa-money-bill-alt text-white",
            "name" => optional($payout->user)->firstname . ' ' . optional($payout->user)->lastname,
            "image" => getFile(optional($payout->user)->image_driver, optional($payout->user)->image),
        ];
        $firebaseAction = route('admin.payout.log');
        $this->adminMail('PAYOUT_REQUEST_TO_ADMIN', $params);
        $this->adminPushNotification('PAYOUT_REQUEST_TO_ADMIN', $params, $action);
        $this->adminFirebasePushNotification('PAYOUT_REQUEST_TO_ADMIN', $params, $firebaseAction);

        $params = [
            'amount' => number_format($payout->amount, 2),
            'currency' => $payout->payout_currency_code,
            'transaction' => $payout->trx_id,
        ];
        $action = [
            "link" => "#",
            "icon" => "fa fa-money-bill-alt text-white"
        ];
        $firebaseAction = "#";
        $this->sendMailSms($user, 'PAYOUT_REQUEST_FROM', $params);
        $this->userPushNotification($user, 'PAYOUT_REQUEST_FROM', $params, $action);
        $this->userFirebasePushNotification($user, 'PAYOUT_REQUEST_FROM', $params, $firebaseAction);
    }

}
PK     x\"    -  Http/Controllers/User/DashboardController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\CardService;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\TopUpService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }


    public function getOrderMovement()
    {
        $orderRecords = DB::table('orders')
            ->where('user_id', auth()->id())
            ->where('payment_status', 1)
            ->selectRaw('
        MONTH(created_at) as month,
        COUNT(CASE WHEN order_for = "topup" THEN 1 END) AS topUpOrder,
        COUNT(CASE WHEN order_for = "card" THEN 1 END) AS cardOrder
    ')
            ->whereYear('created_at', date('Y'))  // Optional: Filter by current year
            ->groupBy(DB::raw('MONTH(created_at)'))
            ->orderBy(DB::raw('MONTH(created_at)'))
            ->get();


        // Initialize monthly data arrays with zeros
        $monthlyData = [
            'topUp' => array_fill(0, 12, 0),
            'card' => array_fill(0, 12, 0),
        ];

        foreach ($orderRecords as $record) {
            $monthIndex = $record->month - 1; // Adjust month to zero-based index for JavaScript
            $monthlyData['topUp'][$monthIndex] = $record->topUpOrder;
            $monthlyData['card'][$monthIndex] = $record->cardOrder;
        }

        return response()->json([
            'orderFigures' => [
                'horizontalBarChatInbox' => $monthlyData
            ]
        ]);
    }
}
PK     x\A  A  ,  Http/Controllers/User/SellPostController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\SellPost;
use App\Models\SellPostCategory;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use App\Traits\Notify;
use App\Traits\PaymentValidationCheck;
use App\Traits\Upload;
use Facades\App\Services\BasicService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;

class SellPostController extends Controller
{
    use Upload, Notify, PaymentValidationCheck;

    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
    }

    public function sellPostOrder(Request $request)
    {
        $user = $this->user;
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $data['sellPostOrders'] = SellPostPayment::with(['sellPost', 'sellPost.category.details'])
            ->whereUser_id($user->id)
            ->wherePayment_status(1)
            ->orderBy('id', 'DESC')
            ->when(@$search['transaction_id'], function ($query) use ($search) {
                return $query->where('transaction', 'LIKE', "%{$search['transaction_id']}%");
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->paginate(basicControl()->paginate);

        return view(template() . 'user.'.getDash().'.gameSell.orderList', $data);
    }

    public function sellPostOfferList()
    {
        $user = $this->user;
        $data['sellPostOffer'] = SellPostOffer::with('sellPost')->whereUser_id($user->id)->orderBy('id', 'DESC')->paginate(basicControl()->paginate);


        return view(template() . 'user.'.getDash().'.gameSell.offerList', $data);
    }

    public function sellCreate(Request $request)
    {
        $data['categoryList'] = SellPostCategory::with('details')
            ->whereHas('details')->whereStatus(1)
            ->get();

        if ($request->has('category')) {
            $data['category'] = SellPostCategory::with('details')
                ->whereHas('details')->whereStatus(1)->findOrFail($request->category);
            return view(template() . 'user.'.getDash().'.gameSell.create', $data);
        }
        return view(template() . 'user.'.getDash().'.gameSell.create', $data);
    }

    public function sellStore(Request $request)
    {
        $request->validate([
            'category' => 'required',
            'price' => 'required|numeric|min:1',
            'title' => 'required',
            'comments' => 'required',
            'image' => 'required'
        ]);
        $category = SellPostCategory::whereStatus(1)->findOrFail($request->category);


        $rules = [];
        $inputField = [];
        if ($category->form_field != null) {
            foreach ($category->form_field as $key => $cus) {
                $rules[$key] = [$cus->validation];
                if ($cus->type == 'file') {
                    array_push($rules[$key], 'image');
                    array_push($rules[$key], 'mimes:jpeg,jpg,png');
                    array_push($rules[$key], 'max:10240');
                }
                if ($cus->type == 'text') {
                    array_push($rules[$key], 'max:191');
                }
                if ($cus->type == 'textarea') {
                    array_push($rules[$key], 'max:300');
                }
                $inputField[] = $key;
            }
        }

        $rulesSpecification = [];
        $inputFieldSpecification = [];
        if ($category->post_specification_form != null) {
            foreach ($category->post_specification_form as $key => $cus) {
                $rulesSpecification[$key] = [$cus->validation];
                if ($cus->type == 'file') {
                    array_push($rulesSpecification[$key], 'image');
                    array_push($rulesSpecification[$key], 'mimes:jpeg,jpg,png');
                    array_push($rulesSpecification[$key], 'max:10240');
                }
                if ($cus->type == 'text') {
                    array_push($rulesSpecification[$key], 'max:191');
                }
                if ($cus->type == 'textarea') {
                    array_push($rulesSpecification[$key], 'max:300');
                }
                $inputFieldSpecification[] = $key;
            }
        }

        $purifiedData = $request->all();

        $newRules = array_merge($rules, $rulesSpecification);


        $validate = Validator::make($purifiedData, $newRules);

        if ($validate->fails()) {
            return back()->withInput()->withErrors($validate);
        }

        if ($request->has('image')) {
            $purifiedData['image'] = $request->image;
        }

        $gameSell = new SellPost();
        $gameSell->user_id = Auth()->user()->id;
        $gameSell->category_id = $purifiedData['category'];
        $gameSell->sell_charge = $category->sell_charge;

        $images = array();
        if ($request->hasFile('image')) {
            try {
                $gameImage = $purifiedData['image'];
                foreach ($gameImage as $file) {
                    $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                    $images[] = $imageUp['path'];
                    $imagesDriver = $imageUp['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
            $gameSell->image = $images;
            $gameSell->image_driver = $imagesDriver;
        }


        if (isset($purifiedData['title'])) {
            $gameSell->title = $request->title;
        }
        if (isset($purifiedData['price'])) {
            $gameSell->price = $request->price;
        }

        if (isset($purifiedData['credential'])) {
            $gameSell->credential = $request->credential;
        }

        if (isset($purifiedData['details'])) {
            $gameSell->details = $request->details;
        }

        if (isset($purifiedData['comments'])) {
            $gameSell->comments = $request->comments;
        }

        if (isset($purifiedData['status'])) {
            $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
        }


        $collection = collect($request);
        $reqField = [];
        if ($category->form_field != null) {
            foreach ($collection as $k => $v) {
                foreach ($category->form_field as $inKey => $inVal) {
                    if ($k != $inKey) {
                        continue;
                    } else {
                        if ($inVal->type == 'file') {
                            if ($request->hasFile($inKey)) {

                                try {
                                    $image = $request->file($inKey);
                                    $location = config('location.sellingPost.path');
                                    $filename = $this->uploadImage($image, $location);;
                                    $reqField[$inKey] = [
                                        'field_name' => $inKey,
                                        'field_value' => $filename,
                                        'type' => $inVal->type,
                                        'validation' => $inVal->validation,
                                    ];

                                } catch (\Exception $exp) {
                                    return back()->with('error', 'Image could not be uploaded.')->withInput();
                                }

                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
            }
            $gameSell['credential'] = $reqField;
        } else {
            $gameSell['credential'] = null;
        }

        $collectionSpecification = collect($request);
        $reqFieldSpecification = [];
        if ($category->post_specification_form != null) {
            foreach ($collectionSpecification as $k => $v) {
                foreach ($category->post_specification_form as $inKey => $inVal) {
                    if ($k != $inKey) {
                        continue;
                    } else {
                        if ($inVal->type == 'file') {
                            if ($request->hasFile($inKey)) {

                                try {
                                    $image = $request->file($inKey);
                                    $location = config('location.sellingPost.path');
                                    $filename = $this->uploadImage($image, $location);;
                                    $reqField[$inKey] = [
                                        'field_name' => $inKey,
                                        'field_value' => $filename,
                                        'type' => $inVal->type,
                                        'validation' => $inVal->validation,
                                    ];

                                } catch (\Exception $exp) {
                                    return back()->with('error', 'Image could not be uploaded.')->withInput();
                                }

                            }
                        } else {
                            $reqFieldSpecification[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
            }
            $gameSell['post_specification_form'] = $reqFieldSpecification;
        } else {
            $gameSell['post_specification_form'] = null;
        }

        $gameSell->save();
        return back()->with('success', 'Game Successfully Saved');
    }

    public function sellList(Request $request)
    {
        $search = $request->all();
        $dateSearch = $request->date;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $sellPost = SellPost::whereUser_id(Auth()->user()->id)
            ->with('category.details')
            ->when($request->title, function ($query) use($request){
                return $query->where('title', 'LIKE', '%' . $request->title . '%');
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->orderBy('id', 'DESC')->paginate(basicControl()->paginate);

        $data['sellPost'] = $sellPost->appends($search);

        return view(template() . 'user.'.getDash().'.gameSell.list', $data);
    }

    public function sellPostEdit($id)
    {
        $data['sellPost'] = SellPost::findOrFail($id);
        if ($data['sellPost']->user_id != auth()->id()) {
            abort(404);
        }
        return view(template() . 'user.'.getDash().'.gameSell.edit', $data);
    }

    public function sellPostUpdate(Request $request, $id)
    {
        $purifiedData = $request->all();
        if ($request->has('image')) {
            $purifiedData['image'] = $request->image;
        }

        $rules = [
            'title' => 'required|max:40',
            'price' => 'required|numeric|min:1',
            'details' => 'required',
            'comments' => 'required',
            'image' => 'sometimes|required'
        ];
        $message = [
            'name.required' => 'Name field is required',
            'price.required' => 'Price field is required',
            'details.required' => 'Details field is required',
            'comments.required' => 'Comments field is required',
            'image.required' => 'Image field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return back()->withInput()->withErrors($validate);
        }

        DB::beginTransaction();
        try {
            $gameSell = SellPost::findOrFail($id);
            $gameSell->user_id = Auth()->user()->id;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'file') {
                        array_push($rules[$key], 'image');
                        array_push($rules[$key], 'mimes:jpeg,jpg,png');
                        array_push($rules[$key], 'max:10240');
                    }
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'file') {
                        array_push($rulesSpecification[$key], 'image');
                        array_push($rulesSpecification[$key], 'mimes:jpeg,jpg,png');
                        array_push($rulesSpecification[$key], 'max:10240');
                    }
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }


            $newRules = array_merge($rules, $rulesSpecification);


            $validate = Validator::make($purifiedData, $newRules);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $collection = collect($request);
            $reqField = [];
            $credentialChanges = '';
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {
                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);;
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return back()->with('error', 'Image could not be uploaded.')->withInput();
                                    }

                                }
                            } else {
                                $reqField[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                            }
                            if ($gameSell->credential->$inKey->field_value != $v) {
                                $credentialChanges .= "$inKey : " . $v . "<br>";
                            }
                        }
                    }
                }
                if (0 < strlen($credentialChanges)) {
                    $credentialChanges = "Changes Credentials <br>" . $credentialChanges;
                }


                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }

            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            $specificationChanges = '';
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            if ($inVal->type == 'file') {
                                if ($request->hasFile($inKey)) {

                                    try {
                                        $image = $request->file($inKey);
                                        $location = config('location.sellingPost.path');
                                        $filename = $this->uploadImage($image, $location);;
                                        $reqField[$inKey] = [
                                            'field_name' => $inKey,
                                            'field_value' => $filename,
                                            'type' => $inVal->type,
                                            'validation' => $inVal->validation,
                                        ];

                                    } catch (\Exception $exp) {
                                        return back()->with('error', 'Image could not be uploaded.')->withInput();
                                    }

                                }
                            } else {
                                $reqFieldSpecification[$inKey] = [
                                    'field_name' => $inKey,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                    'validation' => $inVal->validation,
                                ];
                                if ($gameSell->post_specification_form->$inKey->field_value != $v) {
                                    $specificationChanges .= "$inKey : " . $v . "<br>";
                                }
                            }
                        }
                    }
                }
                if (0 < strlen($specificationChanges)) {
                    $specificationChanges = "Changes Specification <br>" . $specificationChanges;
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }

            $changeImage = '';
            $images = array();

            if ($request->hasFile('image')) {
                if ($gameSell->image != $request->image) {
                    $changeImage = ' Image has been updated ' . "<br>";
                }
                try {
                    $gameImage = $purifiedData['image'];
                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $imageOld) {
                            $this->fileDelete($gameSell->image_driver, $imageOld);
                        }
                    }
                    $oldImages = $request->oldImage ?? [];
                    $mergedImages = array_merge($images, $oldImages);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver;

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }


            $changesTitle = '';
            if (isset($purifiedData['title'])) {
                if ($gameSell->title != $request->title) {
                    $changesTitle = 'Title ' . $gameSell->title . ' updated to ' . $request->title . "<br>";
                }
                $gameSell->title = $request->title;

            }

            $changesPrice = '';
            if (isset($purifiedData['price'])) {
                if ($gameSell->price != $request->price) {
                    $changesPrice = 'Price ' . $gameSell->price . ' updated to ' . $request->price . "<br>";
                }
                $gameSell->price = $request->price;
            }


            $changesDetails = '';
            if (isset($purifiedData['details'])) {
                if ($gameSell->details != $request->details) {
                    $changesDetails = "Details has been Updated <br>";
                }
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['comments'])) {
                $gameSell->comments = $request->comments;
            }

            $gameSell->status = 2;
            $gameSell->save();


            $user = Auth::user();

            if ($changesTitle . $changesPrice . $credentialChanges . $specificationChanges . $changesDetails . $changeImage != '') {
                $activity = new ActivityLog();
                $activity->sell_post_id = $id;
                $activity->title = "Resubmission";
                $activity->description = $changesTitle . $changesPrice . $changeImage . $credentialChanges . $specificationChanges . $changesDetails;
                $user->activities()->save($activity);
            }

            DB::commit();

            return back()->with('success', 'Successfully Updated');
        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function sellPostDelete($id)
    {
        $sellPost = SellPost::findOrFail($id);
        $old_images = $sellPost->image;

        if (!empty($old_images) && count($old_images) > 0) {
            foreach ($old_images as $img) {
                $this->fileDelete($sellPost->image_driver, $img);
            }
        }

        $sellPost->delete();
        return back()->with('success', 'Successfully Deleted');
    }

    public function SellDelete($id, $imgDelete)
    {
        $images = [];
        $galleryImage = SellPost::findOrFail($id);
        $old_images = $galleryImage->image;

        if (!empty($old_images)) {
            foreach ($old_images as $file) {
                $newString = Str::replaceFirst('sellingPost/', '', $file);
                if ($newString == $imgDelete) {
                    $this->fileDelete($galleryImage->image_driver, $file);
                } else {
                    $images[] = $file;
                }
            }
        }
        $galleryImage->image = $images;
        $galleryImage->save();
        return back()->with('success', 'Image has been deleted');
    }

    public function sellPostOffer(Request $request)
    {

        $purifiedData = $request->all();

        $rules = [
            'amount' => 'required|numeric|min:1',
            'description' => 'required',
        ];
        $message = [
            'amount.required' => 'Amount field is required',
            'description.required' => 'Description field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return back()->withInput()->withErrors($validate);
        }

        $auth = auth()->user();
        $sellPost = SellPost::where('status', 1)->findOrFail($request->sell_post_id);

        if ($sellPost->payment_status == 1) {
            return back()->with('warning', 'You can not offer already someone purchases');
        }


        $sellPostOffer = SellPostOffer::whereUser_id($auth->id)->whereSell_post_id($sellPost->id)->count();

        if ($sellPostOffer > 0) {

            $sellPostOffer = SellPostOffer::whereUser_id($auth->id)->whereSell_post_id($request->sell_post_id)->update(["amount" => $request->amount,
                "description" => $request->description,
                "status" => 3
            ]);

        } else {
            SellPostOffer::create([
                'author_id' => $sellPost->user_id,
                'user_id' => Auth::user()->id,
                'sell_post_id' => $request->sell_post_id,
                'amount' => $request->amount,
                'description' => $request->description,
            ]);
        }


        $sellPost = SellPost::findOrFail($request->sell_post_id);
        $user = $sellPost->user;
        if ($sellPostOffer > 0) {
            $this->isReOffer($sellPost, $user, $request);
        } else {
            $msg = [
                'title' => $sellPost->title,
                'amount' => $request->amount . ' ' . basicControl()->base_currency,
                'offer_by' => auth()->user()->firstname . ' ' . auth()->user()->lastname
            ];
            $action = [
                "link" => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_OFFER', $msg, $action);

            $this->sendMailSms($user, 'SELL_OFFER', [
                'link' => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
                'title' => $sellPost->title,
                'amount' => $request->amount . ' ' . config('basic.currency'),
                'offer_by' => auth()->user()->firstname . ' ' . auth()->user()->lastname,
                'description' => $request->description
            ]);
        }

        return back()->with('success', 'Offer Send');
    }

    public function isReOffer($sellPost, $user, $request)
    {
        $msg = [
            'title' => $sellPost->title,
            'amount' => $request->amount . ' ' . basicControl()->base_currency,
            'offer_by' => auth()->user()->firstname . ' ' . auth()->user()->lastname,
            'description' => $request->description
        ];
        $action = [
            "link" => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
            "icon" => "fa fa-money-bill-alt text-white"
        ];
        $this->userPushNotification($user, 'SELL_RE_OFFER', $msg, $action);

        $this->sendMailSms($user, 'SELL_RE_OFFER', [
            'link' => route('sellPost.details', [@slug($sellPost->title), $request->sell_post_id]),
            'title' => $sellPost->title,
            'amount' => $request->amount . ' ' . basicControl()->base_currency,
            'offer_by' => auth()->user()->firstname . ' ' . auth()->user()->lastname,
            'description' => $request->description
        ]);

        return 0;
    }

    public function sellPostOfferMore(Request $request)
    {
        $data['sellPostAll'] = SellPost::whereUser_id(Auth::id())->whereStatus(1)->get();
        $dateTrx = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateTrx);

        $query = SellPostOffer::query();
        $data['sellPostOffer'] = $query->where('author_id', Auth::id())
            ->orWhere('user_id', auth()->id())
            ->whereHas('sellPost')->whereHas('user')->with(['sellPost', 'user'])
            ->when(request('postId', false), function ($q, $postId) {
                $q->where('sell_post_id', $postId);
            })
            ->when(request('remark', false), function ($q, $remark) {
                $q->where('description', 'like', "%$remark%")
                    ->orWhereHas('user', function ($subQuery) use ($remark) {
                        $subQuery->where('firstname', 'like', "%$remark%")->orWhere('lastname', 'like', "%$remark%");
                    });
            })
            ->when($date == 1, function ($query) use ($dateTrx) {
                return $query->whereDate("created_at", $dateTrx);
            })
            ->when(!request('sortBy', false), function ($query, $sortBy) {
                $query->orderBy('updated_at', 'desc');
            })
            ->when(request('sortBy', false), function ($query, $sortBy) {
                if ($sortBy == 'latest') {
                    $query->orderBy('updated_at', 'desc');
                }
//                Payment Processing
                if ($sortBy == 'processing') {
                    $query->whereHas('sellPost', function ($qq) {
                        $qq->where('payment_lock', 1)->where('payment_status', 0)->whereNotNull('lock_at')->whereDate('lock_at', '<=', Carbon::now()->subMinutes(config('basic.payment_expired')));
                    })
                        ->where('status', 1)->where('payment_status', 0)->orderBy('amount', 'desc');
                }
//                Payment Complete
                if ($sortBy == 'complete') {
                    $query->whereHas('sellPost', function ($qq) {
                        $qq->where('payment_lock', 1)->where('payment_status', 1);
                    })->where('status', 1)->where('payment_status', 1)->orderBy('amount', 'desc');
                }
                if ($sortBy == 'low_to_high') {
                    $query->orderBy('amount', 'asc');
                }
                if ($sortBy == 'high_to_low') {
                    $query->orderBy('amount', 'desc');
                }
                if ($sortBy == 'pending') {
                    $query->whereStatus(0)->orderBy('amount', 'desc');
                }

                if ($sortBy == 'rejected') {
                    $query->whereStatus(2)->orderBy('amount', 'desc');
                }
                if ($sortBy == 'resubmission') {
                    $query->whereStatus(3)->orderBy('amount', 'desc');
                }
            })->paginate(basicControl()->paginate);

        return view(template() . 'user.'.getDash().'.sell_post.sell-post-offer', $data);
    }

    public function sellPostOfferRemove(Request $request)
    {

        $sellPostOffer = SellPostOffer::with('sellPost')->findOrFail($request->offer_id);
        if ($sellPostOffer) {
            $sellPostOffer->delete();
        }
        return back()->with('success', 'Remove Offer');
    }

    public function sellPostOfferReject(Request $request)
    {
        $sellPostOffer = SellPostOffer::findOrFail($request->offer_id);
        if ($sellPostOffer->status != 2) {
            $sellPostOffer->update([
                'status' => 2
            ]);

            $user = $sellPostOffer->user;
            $msg = [
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $sellPostOffer->amount . ' ' . basicControl()->base_currency,
            ];
            $action = [
                "link" => route('sellPost.details', [@slug($sellPostOffer->sellPost->title), $sellPostOffer->sellPost->id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'OFFER_REJECT', $msg, $action);

            $this->sendMailSms($user, 'OFFER_REJECT', [
                'link' => route('sellPost.details', [@slug($sellPostOffer->sellPost->title), $sellPostOffer->sellPost->id]),
                'title' => $sellPostOffer->sellPost->title,
                'amount' => $sellPostOffer->amount . ' ' . basicControl()->base_currency,
            ]);

            return back()->with('success', 'Reject Offer');
        }
        return back()->with('warning', 'Already Rejected');
    }

    public function sellPostOfferAccept(Request $request)
    {
        $purifiedData = $request->all();

        $rules = [
            'description' => 'required',
        ];
        $message = [
            'description.required' => 'Description field is required',
        ];

        $validate = Validator::make($purifiedData, $rules, $message);

        if ($validate->fails()) {
            return back()->withInput()->withErrors($validate);
        }

        DB::beginTransaction();
        try {

            $offerDetails = SellPostOffer::findOrFail($request->offer_id);
            if ($offerDetails->uuid != '') {
                return back()->with('warning', 'Offer Can not be accepted');
            }
            if ($offerDetails->sell_post_id) {
                if (!$offerDetails->uuid) {
                    $offerDetails->uuid = Str::uuid();
                }
                $offerDetails->status = 1;
                $offerDetails->attempt_at = Carbon::now();
                $offerDetails->save();

                $user = Auth::user();
                $sellPostChat = new SellPostChat();
                $sellPostChat->sell_post_id = $offerDetails->sell_post_id;
                $sellPostChat->offer_id = $request->offer_id;
                $sellPostChat->description = $request->description;
                $user->sellChats()->save($sellPostChat);

                DB::commit();

                $user = $offerDetails->user;
                $msg = [
                    'title' => $offerDetails->sellPost->title,
                    'amount' => $offerDetails->amount . ' ' . basicControl()->base_currency,
                ];
                $action = [
                    "link" => route('user.offerChat', $offerDetails->uuid),
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $this->userPushNotification($user, 'OFFER_ACCEPTED', $msg, $action);

                $this->sendMailSms($user, 'OFFER_ACCEPTED', [
                    'link' => route('user.offerChat', $offerDetails->uuid),
                    'title' => $offerDetails->sellPost->title,
                    'amount' => $offerDetails->amount . ' ' . basicControl()->base_currency,
                ]);

                return back()->with('success', 'Accepted Offer');
            }

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function sellPostOfferChat($uuid)
    {
        $auth = Auth::user();
        $offerRequest = SellPostOffer::where('uuid', $uuid)
            ->whereHas('user')
            ->whereHas('author')
            ->where(function ($query) use ($auth) {
                $query->where('user_id', $auth->id)
                    ->orWhere('author_id', $auth->id);
            })
            ->with('sellPost')
            ->firstOrFail();

        if (Auth::check() && $offerRequest->author_id == Auth::id()) {
            $data['isAuthor'] = true;
        } else {
            $data['isAuthor'] = false;
        }


        $data['persons'] = SellPostChat::where([
            'offer_id' => $offerRequest->id,
            'sell_post_id' => $offerRequest->sell_post_id
        ])
            ->with('chatable')
            ->get()->pluck('chatable')->unique('chatable');

        $sellPost = SellPost::FindOrFail($offerRequest->sell_post_id);

        return view(template() . 'user.'.getDash().'.sell_post.sell-post-offer-chat', $data, compact('offerRequest', 'sellPost'));
    }

    public function sellPostOfferPaymentLock(Request $request)
    {
        $purifiedData = $request->all();
        $rules = ['amount' => 'required|numeric|min:1',];
        $message = ['amount.required' => 'Amount field is required',];

        $validate = Validator::make($purifiedData, $rules, $message);
        if ($validate->fails()) {
            return back()->withInput()->withErrors($validate);
        }

        $sellPostOffer = SellPostOffer::with('sellPost')->findOrFail($request->offer_id);

        if ($sellPostOffer->sellPost->payment_uuid != '') {
            return back()->with('warning', 'Payment can not be lock');
        }

        if ($sellPostOffer->author_id != Auth::id()) {
            abort(403);
        }
        if ($sellPostOffer->sellPost->payment_lock == 1) {
            return back()->with('warning', 'Payment Allready Lock');
        }

        $sellPostOffer->amount = $request->amount;
        $sellPostOffer->save();
        $sellPost = $sellPostOffer->sellPost;
        $sellPost->payment_lock = 1;
        $sellPost->lock_for = $sellPostOffer->user_id;
        $sellPost->lock_at = Carbon::now();
        $sellPost->payment_uuid = str::uuid();
        $sellPost->save();

        $user = $sellPostOffer->user;
        $msg = [
            'title' => $sellPostOffer->sellPost->title,
            'amount' => $request->amount . ' ' . basicControl()->base_currency,
        ];
        $action = [
            "link" => route('user.sellPost.payment.url', $sellPostOffer->sellPost->payment_uuid),
            "icon" => "fa fa-money-bill-alt text-white"
        ];
        $this->userPushNotification($user, 'PAYMENT_LOCK', $msg, $action);

        $this->sendMailSms($user, 'PAYMENT_LOCK', [
            'link' => route('user.sellPost.payment.url', $sellPostOffer->sellPost->payment_uuid),
            'title' => $sellPostOffer->sellPost->title,
            'amount' => $request->amount . ' ' . basicControl()->base_currency,
        ]);

        return back()->with('success', 'Payment Lock');
    }

    public function sellPostPayment(Request $request, SellPost $sellPost)
    {
        $user = $this->user;
        if ($user->id == $sellPost->user_id) {
            return back()->with('warning', "Author can't buy");
        }

        if ($sellPost->payment_status == 1 || $sellPost->payment_status == 3) {
            return back()->with('warning', 'Someone Already purchase it');
        }
        if ($sellPost->payment_lock == 1 && $sellPost->lock_for != $user->id) {
            return back()->with('warning', 'Someone Booked For Payment');
        }

        if (!$sellPost->payment_uuid) {
            $sellPost->payment_uuid = Str::uuid();
            $sellPost->save();
        }
        return redirect()->route('user.sellPost.payment.url', $sellPost);
    }

    public function sellPostPaymentUrl(SellPost $sellPost)
    {
        $user = auth()->user();
        if ($user->id == $sellPost->user_id) {

            session()->flash('warning', "Author can't buy");
            return redirect()->route('sellPost.details', [slug($sellPost->title ?? 'sell-post'), $sellPost->id]);
        }

        if ($sellPost->payment_status == 1 || $sellPost->payment_status == 3) {
            session()->flash('warning', 'Someone Already Purchase It');
            return redirect()->route('sellPost.details', [slug($sellPost->title ?? 'sell-post'), $sellPost->id]);
        }


        if ($sellPost->payment_lock == 1 && $sellPost->lock_for != $user->id) {
            session()->flash('warning', 'Someone Booked For Payment');
            return redirect()->route('sellPost.details', [slug($sellPost->title ?? 'sell-post'), $sellPost->id]);
        }

        $price = $sellPost->price;
        $checkMyProposal = SellPostOffer::where([
            'user_id' => $user->id,
            'sell_post_id' => $sellPost->id,
            'status' => 1,
            'payment_status' => 0,
        ])->first();
        if ($checkMyProposal) {
            $price = (int)$checkMyProposal->amount;
        }
        $data['sellPost'] = $sellPost;
        $data['price'] = $price;
        $data['gateways'] = Gateway::where('status', 1)->orderBy('sort_by')->get();
        return view(template() . 'user.'.getDash().'.sell_post.sell-post-payment', $data);
    }

    public function sellPostMakePayment(Request $request)
    {
        $this->validate($request, [
            'gateway' => 'required', 'numeric',
            'sellPostId' => 'required', 'numeric',
            'selectedCurrency' => 'nullable|required_unless:gateway,0'
        ], [
            'gateway.required' => 'Please select a payment method',
            'sellPostId.required' => 'Please select a sell post'
        ]);

        $sellPost = SellPost::where('id', $request->sellPostId)
            ->where('status', 1)
            ->first();

        if (!$sellPost) {
            return response()->json(['error' => 'This post already sold or not available to sell'], 422);
        }

        if ($request->gateway != '0') {
            $gate = Gateway::where('status', 1)->findOrFail($request->gateway);
        }

        $price = $sellPost->price;
        if (Auth::check()) {
            $user = Auth::user();
            $checkMyProposal = SellPostOffer::where([
                'user_id' => $user->id,
                'sell_post_id' => $sellPost->id,
                'status' => 1,
                'payment_status' => 0,
            ])->first();
            if ($checkMyProposal) {
                $price = (int)$checkMyProposal->amount;
            }
        }

        $discount = 0;
        $user = auth()->user();

        $reqAmount = $price - $discount;

        if ($request->gateway == '0' && $user->balance < $reqAmount) {
            return back()->with('error', 'Insufficient Wallet Balance')->withInput();
        }

        if ($request->gateway != '0') {
            $checkAmountValidate = $this->validationCheck($reqAmount, $request->gateway, $request->selectedCurrency, null, 'yes');

            if (!$checkAmountValidate['status']) {
                return back()->with('error', $checkAmountValidate['message'])->withInput();
            }
        }

        $admin_amount = $reqAmount * $sellPost->sell_charge / 100;
        $seller_amount = $reqAmount - $admin_amount;

        $sellPostPayment = new SellPostPayment();
        $sellPostPayment->user_id = $user->id;
        $sellPostPayment->sell_post_id = $sellPost->id;
        $sellPostPayment->price = $reqAmount;
        $sellPostPayment->seller_amount = $seller_amount;
        $sellPostPayment->admin_amount = $admin_amount;
        $sellPostPayment->discount = $discount;
        $sellPostPayment->transaction = strRandom();

        $sellPostPayment->save();

        if ($request->gateway == '0' && $user->balance >= $reqAmount) {

            $user->balance -= $reqAmount;
            $user->save();
            $sellPostPayment->payment_status = 1;
            $sellPostPayment->save();

            $sellPost->payment_status = 1;
            $sellPost->lock_for = $user->id;
            $sellPost->save();

            $authorUser = $sellPost->user;

            $checkMyProposal = SellPostOffer::where([
                'user_id' => $user->id,
                'sell_post_id' => $sellPost->id,
                'status' => 1,
                'payment_status' => 0,
            ])->first();
            if ($checkMyProposal) {
                $checkMyProposal->payment_status = 1;
                $checkMyProposal->save();
            }

            SellPostOffer::where('user_id', '!=', $user->id)->where('sell_post_id', $sellPost->id)->get()->map(function ($item) {
                $item->uuid = null;
                $item->save();
            });
            $remark = 'Sell Post Payment Via Wallet';
            BasicService::makeTransaction($user->id, $reqAmount,'-', $sellPostPayment->transaction, $remark, $sellPostPayment->id, SellPostPayment::class);

            session()->flash('success', 'Your order has been processed');
            return redirect()->route('user.sellPostOrder');

        } else {
            $deposit = Deposit::create([
                'user_id' => auth()->id(),
                'payment_method_id' => $checkAmountValidate['gateway_id'],
                'payment_method_currency' => $checkAmountValidate['currency'],
                'amount' => $checkAmountValidate['amount'],
                'percentage_charge' => $checkAmountValidate['percentage_charge'],
                'fixed_charge' => $checkAmountValidate['fixed_charge'],
                'payable_amount' => $checkAmountValidate['payable_amount'],
                'amount_in_base' => $checkAmountValidate['payable_amount_baseCurrency'],
                'charge' => $checkAmountValidate['charge'],
                'payment_crypto_currency' => $checkAmountValidate['payment_crypto_currency'],
                'status' => 0,
                'depositable_id' => $sellPostPayment->id,
                'depositable_type' => SellPostPayment::class,
            ]);
            return redirect(route('payment.process', $deposit->trx_id));
        }
    }

    public function sellPostMyOffer()
    {
        $data['sellPostOffer'] = SellPostOffer::where('user_id', Auth::id())
            ->with(['sellPost', 'sellPost.category.details'])
            ->orderBy('id', 'DESC')
            ->paginate(basicControl()->paginate);

        return view(template() . 'user.'.getDash().'.gameSell.myOffer', $data);
    }

    public function myOfferSearch(Request $request)
    {
        $search = $request->all();
        $dateSearch = $request->datetrx;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);
        $sellPostOffer = SellPostOffer::where('user_id', $this->user->id)
            ->with(['sellPost', 'sellPost.category.details'])
            ->when(@$search['title'], function ($query) use ($search) {
                $query->whereHas('sellPost', function ($qq) use ($search) {
                    $qq->where('title', 'like', "%{$search['title']}%");
                });
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->orderBy('id', 'desc')
            ->paginate(basicControl()->paginate);
        $sellPostOffer = $sellPostOffer->appends($search);

        return view(template() . 'user.'.getDash().'.gameSell.myOffer', compact('sellPostOffer'));

    }
}
PK     x\6    3  Http/Controllers/User/KycVerificationController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Kyc;
use App\Models\UserKyc;
use App\Traits\Notify;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class KycVerificationController extends Controller
{
    use Upload, Notify;

    public function kycFormDetails(Request $request)
    {
        $val = $request->input('kycTypeID');
        $kyc = Kyc::where('id', $val)->first();
        $oldKyc = UserKyc::where('kyc_id', $val)->where('user_id', auth()->id())->latest()->first();

        if ($oldKyc && $oldKyc->status == 2) {
            return ['kyc' => $kyc, 'status' => $oldKyc->status, 'reason' => $oldKyc->reason];
        }
        if ($oldKyc) {
            return ['kyc' => $kyc, 'status' => $oldKyc->status];
        }

        return  ['kyc' => $kyc];
    }

    public function verificationSubmit(Request $request)
    {
        $kyc = Kyc::where('id', $request->kycType)->where('status', 1)->first();
        if (!$kyc) {
            return back()->with('error', 'Selected KYC not found.');
        }
        $oldKyc = UserKyc::where('kyc_id', $kyc->id)->where('user_id', Auth::user()->id)->first();

        $params = $kyc->input_form;
        $reqData = $request->except('_token', '_method');
        $rules = [];

        if ($params !== null) {
            foreach ($params as $key => $cus) {
                $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                if ($cus->type === 'file') {
                    $rules[$key][] = 'image';
                    $rules[$key][] = 'mimes:jpeg,jpg,png';
                    $rules[$key][] = 'max:10240';
                } elseif ($cus->type === 'text') {
                    $rules[$key][] = 'max:191';
                } elseif ($cus->type === 'number') {
                    $rules[$key][] = 'integer';
                } elseif ($cus->type === 'textarea') {
                    $rules[$key][] = 'min:3';
                    $rules[$key][] = 'max:300';
                }
            }
        }

        $validator = Validator::make($reqData, $rules);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $reqField = [];
        foreach ($request->except('_token', '_method', 'type') as $k => $v) {
            foreach ($params as $inKey => $inVal) {
                if ($k == $inKey) {
                    if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                        try {
                            $file = $this->fileUpload($request[$inKey], config('filelocation.kyc.path'), null, null, 'webp', 60);
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'field_label' => $inVal->field_label,
                                'field_value' => $file['path'],
                                'field_driver' => $file['driver'],
                                'validation' => $inVal->validation,
                                'type' => $inVal->type,
                            ];
                        } catch (\Exception $exp) {
                            session()->flash('error', 'Could not upload your ' . $inKey);
                            return back()->withInput();
                        }
                    } else {
                        $reqField[$inKey] = [
                            'field_name' => $inVal->field_name,
                            'field_label' => $inVal->field_label,
                            'validation' => $inVal->validation,
                            'field_value' => $v,
                            'type' => $inVal->type,
                        ];
                    }
                }
            }
        }

        if (isset($oldKyc) && $oldKyc->status = 0) {
            $oldKyc->kyc_info = $reqField;
            $oldKyc->status = 0;
            $oldKyc->save();
            $message = 'KYC Updated Successfully';

            return back()->with('success', $message);

        } else {
            UserKyc::create([
                'user_id' => auth()->id(),
                'kyc_id' => $kyc->id,
                'kyc_type' => $kyc->name,
                'kyc_info' => $reqField,
            ]);

            $message = 'KYC Submitted Successfully';
            return back()->with('success', $message);
        }
    }

    public function verificationHistory(Request $request){
        $data['userKyc'] = UserKyc::where('user_id', auth()->id())->orderBy('id', 'DESC')->paginate(basicControl()->paginate);

        return view(template().'user.'.getDash().'.profile.kyc_history', $data);
    }
}
PK     x\1!    )  Http/Controllers/User/OrderController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Collection;
use App\Models\Order;
use Illuminate\Http\Request;

class OrderController extends Controller
{

    public function topUpOrder(Request $request)
    {

        $status = null;
        if ($request->type == 'wait-sending') {
            $status = 0;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = Order::with(['orderDetails', 'orderDetails.detailable'])
            ->with([
                'orderDetails.detailable' => function ($query) {
                    $query->when(method_exists($query->getModel(), 'topUp'), function ($query) {
                        $query->with(['topUp.reviewByReviewer']);
                    });
                }
            ])
            ->own()
            ->payment()
            ->type('topup')
            ->when(isset($request->type) && $request->type != 'all', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($request->search), function ($query) use ($request) {
                return $query->where(function ($query) use ($request) {
                    $query->where('utr', 'LIKE', '%' . $request->search . '%')
                        ->orWhere('amount', 'LIKE', '%' . $request->search . '%');
                })
                    ->orWhereHas('orderDetails', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request->search . '%');
                    });
            })
            ->orderBy('id', 'desc')
            ->paginate(basicControl()->paginate);



        return view(template() . "user.".getDash() .".order.topup.index", $data);
    }

    public function cardOrder(Request $request)
    {
        $status = null;
        if ($request->type == 'wait-sending') {
            $status = 3;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = Order::with(['orderDetails', 'orderDetails.detailable'])
            ->with([
                'orderDetails.detailable' => function ($query) {
                    $query->when(method_exists($query->getModel(), 'card'), function ($query) {
                        $query->with(['card.reviewByReviewer']);
                    });
                }
            ])
            ->own()
            ->payment()
            ->type('card')
            ->when(isset($request->type) && $request->type != 'all', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($request->search), function ($query) use ($request) {
                return $query->where(function ($query) use ($request) {
                    $query->where('utr', 'LIKE', '%' . $request->search . '%')
                        ->orWhere('amount', 'LIKE', '%' . $request->search . '%');
                })
                    ->orWhereHas('orderDetails', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request->search . '%');
                    });
            })
            ->orderBy('id', 'desc')
            ->paginate(basicControl()->paginate);

        return view(template() . "user." . getDash() . ".order.card.index", $data);
    }
}
PK     x\zn2  2  (  Http/Controllers/User/HomeController.phpnu [        <?php

namespace App\Http\Controllers\User;


use App\Helpers\GoogleAuthenticator;
use App\Http\Controllers\Controller;
use App\Jobs\UserTrackingJob;
use App\Models\Card;
use App\Models\CardService;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\Kyc;
use App\Models\Language;
use App\Models\Order;
use App\Models\Payout;
use App\Models\SellPost;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use App\Models\SupportTicket;
use App\Models\Transaction;
use App\Models\UserKyc;
use App\Rules\PhoneLength;
use App\Traits\Upload;
use hisorange\BrowserDetect\Parser as Browser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
use Stevebauman\Purify\Facades\Purify;


class HomeController extends Controller
{
    use Upload;

    public function __construct()
    {
        $this->middleware(['auth']);
        $this->middleware(function ($request, $next) {
            $this->user = auth()->user();
            return $next($request);
        });
        $this->theme = template();
    }

    public function saveToken(Request $request)
    {
        try {
            Auth::user()
                ->fireBaseToken()
                ->create([
                    'token' => $request->token,
                ]);
            return response()->json([
                'msg' => 'token saved successfully.',
            ]);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }


    public function index()
    {
        $data['user'] = Auth::user();

        $data['stat'] = Order::payment()->own()
            ->selectRaw('COUNT(CASE WHEN order_for = "topup" THEN id END) AS totalTopUpOrder')
            ->selectRaw('COUNT(CASE WHEN order_for = "card" THEN id END) AS totalCardOrder')
            ->first();
        $data['sellPostOffer'] = SellPostOffer::where('author_id', auth()->user()->id)
            ->whereHas('sellPost')->whereHas('user')->with(['sellPost', 'user:id,firstname,lastname,image,image_driver'])->latest()->take(3)->get();

        $data['sellPost'] = SellPost::whereUser_id(Auth()->user()->id)
            ->with('category.details')->latest()->take(3)->get();

        $data['totalTickets'] = SupportTicket::where('user_id', $data['user']->id)->count();

        $data['firebaseNotify'] = config('firebase');

        $data['topSlider'] = CardService::where('status', 1)->where('is_offered', 1)->latest()->take(5)->get();

        return view(template() . "user." . getDash() . ".dashboard", $data);
    }


    public function profile()
    {
        $data['languages'] = Language::all();
        $data['userProfile'] = $this->user;
        return view(template() . "user." . getDash() . ".profile.my_profile", $data);
    }

    public function profileUpdateImage(Request $request)
    {
        $userProfile = $this->user;
        if ($request->file('image') && $request->file('image')->isValid()) {
            $extension = $request->image->extension();
            $profileName = strtolower($userProfile->username . '.' . $extension);
            $image = $this->fileUpload($request->image, config('filelocation.userProfile.path'), $profileName, null, 'webp', 60, $userProfile->image, $userProfile->image_driver);
            if ($image) {
                $userProfile->image = $image['path'];
                $userProfile->image_driver = $image['driver'];
            }
        }

        $remark = 'Update profile image';
        UserTrackingJob::dispatch($userProfile->id, request()->ip(), $remark);

        $userProfile->save();
        return back()->with('success', 'Uploaded Successfully.');
    }

    public function profileUpdate(Request $request)
    {
        $purifiedData = $request->all();
        $userProfile = $this->user;
        $validator = Validator::make($purifiedData, [
            'firstname' => 'required|min:3|max:100|string',
            'lastname' => 'required|min:3|max:100|string',
            'username' => 'sometimes|required|min:5|max:50|unique:users,username,' . $userProfile->id,
            'email' => 'sometimes|required|min:5|max:50|unique:users,email,' . $userProfile->id,
            'language' => 'required|integer|not_in:0|exists:languages,id',
            'timezone' => 'required',
            'address' => 'nullable|max:2500',
            'phone' => ['required', 'string', "unique:users,phone, $userProfile->id", new PhoneLength($request->input('phone_code'))],
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }
        try {
            $purifiedData = (object)$purifiedData;
            if ($purifiedData->email != $userProfile->email) {
                $userProfile->email_verification = 0;
            }
            if ($purifiedData->phone != $userProfile->phone) {
                $userProfile->sms_verification = 0;
            }

            $userProfile->firstname = $purifiedData->firstname;
            $userProfile->lastname = $purifiedData->lastname;
            $userProfile->username = $purifiedData->username;
            $userProfile->email = $purifiedData->email;
            $userProfile->address_one = $purifiedData->address ?? null;
            $userProfile->phone = $purifiedData->phone;
            $userProfile->phone_code = $purifiedData->phone_code ?? $userProfile->phone_code;
            $userProfile->language_id = $purifiedData->language;
            $userProfile->timezone = $purifiedData->timezone;
            $userProfile->country_code = Str::upper($purifiedData->country_code);
            $userProfile->country = $purifiedData->country;

            $userProfile->save();

            $remark = 'Update profile information';
            UserTrackingJob::dispatch($userProfile->id, request()->ip(), $remark);

            return back()->with('success', 'Profile Update Successfully');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    public function updatePassword(Request $request)
    {
        if ($request->method() == 'GET') {
            $data['userProfile'] = $this->user;

            return view(template() . "user." . getDash() . ".profile.password", $data);
        } elseif ($request->method() == 'POST') {
            $purifiedData = $request->all();
            $validator = Validator::make($purifiedData, [
                'currentPassword' => 'required|min:5',
                'password' => 'required|min:8|confirmed',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            try {
                $user = Auth::user();
                $purifiedData = (object)$purifiedData;

                if (!Hash::check($purifiedData->currentPassword, $user->password)) {
                    return back()->withInput()->withErrors(['currentPassword' => 'current password did not match']);
                }

                $user->password = bcrypt($purifiedData->password);
                $user->save();

                $remark = 'Updated password';
                UserTrackingJob::dispatch($user->id, request()->ip(), $remark);

                return back()->with('success', 'Password changed successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function kycSettings()
    {
        try {
            $data['kyc'] = Kyc::where('status', 1)->get();

            return view(template() . "user." . getDash() . ".profile.kyc", $data);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function addFund()
    {
        $data['basic'] = basicControl();
        $data['gateways'] = Gateway::where('status', 1)->orderBy('sort_by', 'ASC')->get();

        return view(template() . "user." . getDash() . ".fund.add_fund", $data);
    }

    public function paymentLog(Request $request)
    {
        $dateSearch = $request->created_at;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $data['logs'] = Deposit::with(['gateway:id,name,image,driver'])
            ->where('user_id', Auth::id())
            ->whereIn('status', ['1', '2', '3'])
            ->when($request->trxId, function ($query) {
                return $query->where('trx_id', 'LIKE', '%' . request('trxId') . '%');
            })
            ->when($request->amount, function ($query) {
                return $query->where('amount_in_base', 'LIKE', '%' . request('amount') . '%');
            })
            ->when($request->gateway_id, function ($query) {
                return $query->where('payment_method_id', request('gateway_id'));
            })
            ->when($request->status, function ($query) {
                return $query->where('status', request('status'));
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->latest()->paginate(basicControl()->paginate);

        $data['gateways'] = Gateway::select(['id', 'name'])->orderBy('sort_by', 'asc')->get();

        return view(template() . "user." . getDash() . ".fund.index", $data);
    }

    public function transaction(Request $request)
    {
        $dateSearch = $request->created_at;
        $date = preg_match("/^[0-9]{2,4}\-[0-9]{1,2}\-[0-9]{1,2}$/", $dateSearch);

        $data['transactions'] = Transaction::where('user_id', Auth::id())
            ->orderBy('id', 'desc')
            ->when($request->trxId, function ($query) {
                return $query->where('trx_id', 'LIKE', '%' . request('trxId') . '%');
            })
            ->when($request->amount, function ($query) {
                return $query->where('amount_in_base', 'LIKE', '%' . request('amount') . '%');
            })
            ->when($request->remark, function ($query) {
                return $query->where('remarks', 'LIKE', '%' . request('remark') . '%');
            })
            ->when($request->type, function ($query) {
                if (request('type') == 'order') {
                    return $query->where('transactional_type', Order::class);
                } elseif (request('type') == 'deposit') {
                    return $query->where('transactional_type', Deposit::class);
                }elseif (request('type') == 'payout') {
                    return $query->where('transactional_type', Payout::class);
                }elseif (request('type') == 'sellPost') {
                    return $query->where('transactional_type', SellPostPayment::class);
                }
            })
            ->when($date == 1, function ($query) use ($dateSearch) {
                return $query->whereDate("created_at", $dateSearch);
            })
            ->latest()->paginate(basicControl()->user_paginate);

        return view(template() . "user." . getDash() . ".transaction.index", $data);
    }

    public function apiKey(Request $request)
    {
        $user = auth()->user();
        if ($request->method() == 'GET') {
            $public_key = $user->public_key;
            $secret_key = $user->secret_key;
            if (!$public_key || !$secret_key) {
                $user->public_key = 'pk' . bin2hex(random_bytes(20));
                $user->secret_key = 'sk' . bin2hex(random_bytes(20));
                $user->save();
            }

            return view(template() . 'user.'.getDash().'.api-key');
        } elseif ($request->method() == 'POST') {
            $user->public_key = 'pk' . bin2hex(random_bytes(20));
            $user->secret_key = 'sk' . bin2hex(random_bytes(20));
            $user->save();

            $remark = 'Generated API key';
            UserTrackingJob::dispatch($user->id, request()->ip(), $remark);

            return back()->with('success', 'Api key generated successfully');
        }
    }

    public function changeDashboard(Request $request)
    {
        $request->validate([
            'dashboard' => 'required|string|in:daybreak,nightfall',
        ]);

        $user = Auth::user();

        $user->active_dashboard = $request->dashboard;
        $user->save();


        return response()->json([
            'success' => true,
            'message' => "'".ucfirst($user->active_dashboard)."'".' dashboard theme selected successfully.'
        ]);
    }

}
PK     x\[͉0\  \  0  Http/Controllers/User/VerificationController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Helpers\GoogleAuthenticator;
use App\Http\Controllers\Controller;
use App\Models\ContentDetails;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;

class VerificationController extends Controller
{

    use Notify;


    public function checkValidCode($user, $code, $add_min = 10000)
    {
        if (!$code) return false;
        if (!$user->sent_at) return false;
        if (Carbon::parse($user->sent_at)->addMinutes($add_min) < Carbon::now()) return false;
        if ($user->verify_code !== $code) return false;
        return true;
    }

    public function check()
    {
        $user = auth()->user();
        $template = ContentDetails::whereHas('content', function ($query) {
            $query->whereIn('name', ['authentication']);
        })->get()->groupBy('content.name');

        if (!$user->status) {
            Auth::guard('web')->logout();
        } elseif (!$user->email_verification) {
            if (!$this->checkValidCode($user, $user->verify_code)) {
                $user->verify_code = code(6);
                $user->sent_at = Carbon::now();
                $user->save();
                $this->mail($user, 'VERIFICATION_CODE', [
                    'code' => $user->verify_code
                ], null, null);
                session()->flash('success', 'Email verification code has been sent');
            }
            $page_title = 'Email Verification';
            return view(template() . 'auth.verification.email', compact('user', 'page_title', 'template'));
        } elseif (!$user->sms_verification) {
            if (!$this->checkValidCode($user, $user->verify_code)) {
                $user->verify_code = code(6);
                $user->sent_at = Carbon::now();
                $user->save();

                $this->verifyToSms($user, 'VERIFICATION_CODE', [
                    'code' => $user->verify_code
                ]);
                session()->flash('success', 'SMS verification code has been sent');
            }
            $page_title = 'SMS Verification';
            return view(template() . 'auth.verification.sms', compact('user', 'page_title', 'template'));
        } elseif (!$user->two_fa_verify) {
            $page_title = '2FA Code';
            return view(template() . 'auth.verification.2stepSecurity', compact('user', 'page_title', 'template'));

        }
        return redirect()->route('user.dashboard');
    }


    public function resendCode()
    {
        $type = request()->type;
        $user = auth()->user();
        if ($this->checkValidCode($user, $user->verify_code, 2)) {
            $target_time = Carbon::parse($user->sent_at)->addMinutes(2)->timestamp;
            $delay = $target_time - time();
            throw ValidationException::withMessages(['resend' => 'Please Try after ' . gmdate("i:s", $delay) . ' minutes']);
        }
        if (!$this->checkValidCode($user, $user->verify_code)) {
            $user->verify_code = code(6);
            $user->sent_at = Carbon::now();
            $user->save();
        } else {
            $user->sent_at = Carbon::now();
            $user->save();
        }

        if ($type === 'email') {
            $this->mail($user, 'VERIFICATION_CODE', [
                'code' => $user->verify_code
            ], null, null);
            return back()->with('success', 'Email verification code has been sent.');
        } elseif ($type === 'mobile') {
            $this->verifyToSms($user, 'VERIFICATION_CODE', [
                'code' => $user->verify_code
            ]);
            return back()->with('success', 'SMS verification code has been sent');
        } else {
            throw ValidationException::withMessages(['error' => 'Sending Failed']);
        }
    }

    public function mailVerify(Request $request)
    {
        // Define validation rules and custom error messages
        $rules = [
            'code' => 'required',
        ];
        $msg = [
            'code.required' => 'Email verification code is required',
        ];

        $this->validate($request, $rules, $msg);

        $user = auth()->user();

        if ($this->checkValidCode($user, $request->code)) {
            $user->email_verification = 1;
            $user->verify_code = null;
            $user->sent_at = null;
            $user->save();

            return redirect()
                ->intended(route('user.dashboard'))
                ->with('success', __('Email verified successfully!'));
        }

        throw ValidationException::withMessages([
            'error' => __('Verification code didn\'t match!'),
        ]);
    }


    public function smsVerify(Request $request)
    {
        $rules = [
            'code' => 'required',
        ];
        $msg = [
            'code.required' => 'Sms verification code is required',
        ];
        $validate = $this->validate($request, $rules, $msg);
        $user = Auth::user();

        if ($this->checkValidCode($user, $request->code)) {
            $user->sms_verification = 1;
            $user->verify_code = null;
            $user->sent_at = null;
            $user->save();

            return redirect()->intended(route('user.dashboard'));
        }
        throw ValidationException::withMessages(['error' => 'Verification code didn\'t match!']);
    }

    public function twoFAverify(Request $request)
    {
        $this->validate($request, [
            'code' => 'required',
        ], [
            'code.required' => 'Email verification code is required',
        ]);
        $ga = new GoogleAuthenticator();
        $user = Auth::user();
        $getCode = $ga->getCode($user->two_fa_code);
        if ($getCode == trim($request->code)) {
            $user->two_fa_verify = 1;
            $user->save();
            return redirect()->intended(route('user.dashboard'));
        }
        throw ValidationException::withMessages(['error' => 'Wrong Verification Code']);

    }


}
PK     x\#׭	  	  +  Http/Controllers/User/DepositController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Gateway;
use App\Traits\MakeOrder;
use Illuminate\Http\Request;
use App\Traits\PaymentValidationCheck;
use Illuminate\Support\Facades\Auth;

class DepositController extends Controller
{

    use PaymentValidationCheck, MakeOrder;

    public function supportedCurrency(Request $request)
    {
        $gateway = Gateway::where('id', $request->gateway)->first();
        return response([
            'success' => true,
            'data' => $gateway->supported_currency,
            'currencyType' => $gateway->currency_type,
        ]);
    }

    public function checkAmount(Request $request)
    {
        if ($request->ajax()) {
            $amount = $request->amount;
            $selectedCurrency = $request->selected_currency;

            $selectGateway = $request->select_gateway;
            $selectedCryptoCurrency = $request->selectedCryptoCurrency;
            $amountType = $request->amountType ?? 'base';
            $data = $this->checkAmountValidate($amount, $selectedCurrency, $selectGateway, $selectedCryptoCurrency, $amountType);

            return response()->json($data);
        }
        return response()->json(['error' => 'Invalid request'], 400);
    }

    public function checkAmountValidate($amount, $selectedCurrency, $selectGateway, $selectedCryptoCurrency = null, $amountType = 'base')
    {
        return $this->validationCheck($amount, $selectGateway, $selectedCurrency, $selectedCryptoCurrency, $amountType);
    }


    public function paymentRequest(Request $request)
    {
        try {
            $checkAmountValidate = $this->validationCheck($request->amount, $request->gateway_id,
                $request->supported_currency, $request->supported_crypto_currency, 'other');

            if (!$checkAmountValidate['status']) {
                return back()->with('error', $checkAmountValidate['message']);
            }

            $deposit = $this->depositCreate($checkAmountValidate);
            return redirect(route('payment.process', $deposit->trx_id));

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     x\[]  ]  0  Http/Controllers/User/NotificationController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\NotificationSettings;
use App\Models\NotificationTemplate;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    public function index()
    {
        $data['user'] = User::with('notifypermission')->where('id', Auth::id())->firstOr(function () {
            throw new \Exception('The notification templete was not found.');
        });
        $data['notificationTemplates'] = NotificationTemplate::where('notify_for', 0)->get();


        return view(template() . 'user.'.getDash().'.profile.notification_settings', $data);
    }
    public function notificationSettingsChanges(Request $request)
    {
        try {
            $user = Auth::user();
            $userTemplate = NotificationSettings::where('notifyable_id', $user->id)
                ->where('notifyable_type', User::class)
                ->firstOr(function () {
                    throw new \Exception('Notification Template not found.');
                });

            $userTemplate->template_email_key = $request->email_key;
            $userTemplate->template_sms_key = $request->sms_key;
            $userTemplate->template_in_app_key = $request->in_app_key;
            $userTemplate->template_push_key = $request->push_key;
            $userTemplate->save();

            return back()->with('success', 'Notification Permission Updated Successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\iT  T  -  Http/Controllers/User/SocialiteController.phpnu [        <?php

namespace App\Http\Controllers\User;

use App\Helpers\UserSystemInfo;
use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\User;
use App\Models\UserLogin;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Laravel\Socialite\Facades\Socialite;

class SocialiteController extends Controller
{
    use Upload;
    public function socialiteLogin($socialite)
    {
        if (config('socialite.' . $socialite . '_status')) {

            return Socialite::driver($socialite)->redirect();
        }
        return redirect()->route('login');
    }

    public function socialiteCallback($socialite)
    {
        try {
            $user = Socialite::driver($socialite)->user();
            $columName = $socialite . '_id';
            $searchUser = User::where($columName, $user->id)->first();

            if ($searchUser) {
                Auth::login($searchUser);
                return redirect('user/dashboard');

            } else {
                $languageId = Language::select('id')->where('default_status', 1)->first()->id ?? null;

                $newUser = User::create([
                    'first_name' => $user->name,
                    'email' => $user->email,
                    'username' => $user->email,
                    'password' => Hash::make($user->name),
                    $columName => $user->id,
                    'language_id' => $languageId,
                    'email_verification' => (basicControl()->email_verification) ? 0 : 1,
                    'sms_verification' => (basicControl()->sms_verification) ? 0 : 1,
                ]);

                $this->extraWorkWithRegister($newUser);
                Auth::login($newUser);
                return redirect('user/dashboard');
            }

        } catch (\Exception $e) {
            return redirect()->route('login');
        }
    }

    public function extraWorkWithRegister($newUser): void
    {
        $newUser->last_login = Carbon::now();
        $newUser->last_seen = Carbon::now();
        $newUser->two_fa_verify = ($newUser->two_fa == 1) ? 0 : 1;
        $newUser->save();

        $info = @json_decode(json_encode(getIpInfo()), true);
        $ul['user_id'] = $newUser->id;

        $ul['longitude'] = (!empty(@$info['long'])) ? implode(',', $info['long']) : null;
        $ul['latitude'] = (!empty(@$info['lat'])) ? implode(',', $info['lat']) : null;
        $ul['country_code'] = (!empty(@$info['code'])) ? implode(',', $info['code']) : null;
        $ul['location'] = (!empty(@$info['city'])) ? implode(',', $info['city']) . (" - " . @implode(',', @$info['area']) . "- ") . @implode(',', $info['country']) . (" - " . @implode(',', $info['code']) . " ") : null;
        $ul['country'] = (!empty(@$info['country'])) ? @implode(',', @$info['country']) : null;

        $ul['ip_address'] = UserSystemInfo::get_ip();
        $ul['browser'] = UserSystemInfo::get_browsers();
        $ul['os'] = UserSystemInfo::get_os();
        $ul['get_device'] = UserSystemInfo::get_device();

        UserLogin::create($ul);
    }
}
PK     x\vw3    /  Http/Controllers/ChatNotificationController.phpnu [        <?php

namespace App\Http\Controllers;

use App\Events\UpdateOfferChatNotification;
use App\Models\Admin;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Models\User;
use App\Traits\Notify;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ChatNotificationController extends Controller
{
    use Notify;

    public function show(Request $request, $uuid)
    {
        $offerRequest = SellPostOffer::where('uuid', $uuid)
            ->firstOrFail();
        $siteNotifications = SellPostChat::whereHasMorph(
            'chatable',
            [
                User::class,
                Admin::class,
            ],
            function ($query) use ($offerRequest) {
                $query->where([
                    'offer_id' => $offerRequest->id,
                    'sell_post_id' => $offerRequest->sell_post_id
                ]);
            }
        )->with('chatable:id,username,phone,image,image_driver')->get();

        return $siteNotifications;
    }

    public function newMessage(Request $request)
    {
        $rules = [
            'offer_id' => ['required'],
            'sell_post_id' => ['required'],
            'message' => ['required']
        ];

        $req = $request->all();
        $validator = Validator::make($req, $rules);
        if ($validator->fails()) {
            return response(['errors' => $validator->messages()], 200);
        }
        $user = Auth::user();

        $sellPostOffer = SellPostOffer::where('id', $request->offer_id)
            ->where('sell_post_id', $request->sell_post_id)
            ->firstOrFail();


        $chat = new SellPostChat();
        $chat->description = $req['message'];
        $chat->sell_post_id = $sellPostOffer->sell_post_id;
        $chat->offer_id = $sellPostOffer->id;
        $log = $user->chatable()->save($chat);


        $data['id'] = $log->id;
        $data['chatable_id'] = $log->chatable_id;
        $data['chatable_type'] = $log->chatable_type;
        $data['chatable'] = [
            'fullname' => $log->chatable->fullname,
            'id' => $log->chatable->id,
            'image' => $log->chatable->image,
            'mobile' => $log->chatable->mobile,
            'imgPath' => $log->chatable->imgPath,
            'username' => $log->chatable->username,
        ];
        $data['description'] = $log->description;
        $data['is_read'] = $log->is_read;
        $data['is_read_admin'] = $log->is_read_admin;
        $data['formatted_date'] = $log->formatted_date;
        $data['created_at'] = $log->created_at;
        $data['updated_at'] = $log->updated_at;

        event(new \App\Events\OfferChatNotification($data, $sellPostOffer->uuid));

        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->author, $data, $sellPostOffer->uuid);
        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->user, $data, $sellPostOffer->uuid);

        return response(['success' => true], 200);
    }


    public function showByAdmin($uuid)
    {
        $offerRequest = SellPostOffer::where('uuid', $uuid)
            ->firstOrFail();


        $siteNotifications = SellPostChat::whereHasMorph(
            'chatable',
            [
                User::class,
                Admin::class
            ],
            function ($query) use ($offerRequest) {
                $query->where([
                    'offer_id' => $offerRequest->id,
                    'sell_post_id' => $offerRequest->sell_post_id
                ]);
            }
        )->with('chatable:id,username,image,image_driver')->get();

        return $siteNotifications;
    }


    public function newMessageByAdmin(Request $request)
    {
        $rules = [
            'offer_id' => ['required'],
            'sell_post_id' => ['required'],
            'message' => ['required']
        ];

        $req = $request->all();
        $validator = Validator::make($req, $rules);
        if ($validator->fails()) {
            return response(['errors' => $validator->messages()], 200);
        }


        $user = auth::guard('admin')->user();
        $sellPostOffer = SellPostOffer::where('id', $request->offer_id)
            ->where('sell_post_id', $request->sell_post_id)
            ->firstOrFail();

        $chat = new SellPostChat();
        $chat->description = $req['message'];
        $chat->offer_id = $sellPostOffer->id;
        $chat->sell_post_id = $sellPostOffer->sell_post_id;
        $log = $user->chatable()->save($chat);


        $uuid = $sellPostOffer->uuid;
        $data['id'] = $log->id;
        $data['chatable_id'] = $log->chatable_id;
        $data['chatable_type'] = $log->chatable_type;
        $data['chatable'] = [
            'fullname' => $log->chatable->fullname,
            'id' => $log->chatable->id,
            'image' => $log->chatable->image,
            'mobile' => $log->chatable->mobile,
            'imgPath' => $log->chatable->imgPath,
            'username' => $log->chatable->username,
        ];
        $data['description'] = $log->description;
        $data['is_read'] = $log->is_read;
        $data['is_read_admin'] = $log->is_read_admin;
        $data['formatted_date'] = $log->formatted_date;
        $data['created_at'] = $log->created_at;
        $data['updated_at'] = $log->updated_at;

        event(new \App\Events\OfferChatNotification($data, $uuid));

        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->author, $data, $sellPostOffer->uuid);
        $this->sendRealTimeMessageThrowFirebase($sellPostOffer->user, $data, $sellPostOffer->uuid);

        return response(['success' => true], 200);
    }

    public function readAt($id)
    {
        $siteNotification = SellPostChat::find($id);
        if ($siteNotification) {
            $siteNotification->delete();
            if (Auth::guard('admin')->check()) {
                event(new UpdateOfferChatNotification(Auth::guard('admin')->id()));
            } else {
                event(new UpdateOfferChatNotification(Auth::id()));
            }
            $data['status'] = true;
        } else {
            $data['status'] = false;
        }
        return $data;
    }

    public function readAllByAdmin()
    {
        $siteNotification = SellPostChat::whereHasMorph(
            'chatable',
            [Admin::class],
            function ($query) {
                $query->where([
                    'chatable_id' => Auth::guard('admin')->id()
                ]);
            }
        )->delete();

        if ($siteNotification) {
            event(new UpdateOfferChatNotification(Auth::guard('admin')->id()));
        }
        $data['status'] = true;
        return $data;
    }

    public function readAll()
    {
        $siteNotification = SellPostChat::whereHasMorph(
            'chatable',
            [User::class],
            function ($query) {
                $query->where([
                    'chatable' => Auth::id()
                ]);
            }
        )->delete();

        if ($siteNotification) {
            event(new UpdateOfferChatNotification(Auth::id()));
        }

        $data['status'] = true;
        return $data;
    }
}
PK     x\w&  &  ,  Http/Controllers/Frontend/CardController.phpnu [        <?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\CardService;
use App\Models\Category;
use App\Models\Gateway;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Review;
use App\Traits\MakeOrder;
use App\Traits\PaymentValidationCheck;
use App\Traits\Rating;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CardController extends Controller
{
    use MakeOrder, PaymentValidationCheck, Rating;

    public function __construct()
    {
        $this->theme = template();
    }

    public function cardList(Request $request)
    {
        $data['categories'] = Category::type('card')->active()->sort()
            ->get(['id', 'name', 'icon', 'type', 'active_children', 'status', 'sort_by']);

        $data['cards'] = Card::select(['id', 'category_id', 'region', 'status',
            'name', 'slug', 'image', 'total_review', 'avg_rating', 'sell_count'])
            ->where('status', 1)
            ->when(isset($request->category) && !empty($request->category), function ($query) use ($request) {
                $query->where('category_id', $request->category);
            })
            ->when(isset($request->filter) && !empty($request->filter), function ($query) use ($request) {
                if ($request->filter == 'all') {
                    $query->orderBy('sort_by', 'desc');
                } elseif ($request->filter == '1') {
                    $query->orderBy('sell_count', 'desc');
                } elseif ($request->filter == '2') {
                    $query->latest();
                } elseif ($request->filter == '3') {
                    $query->where('trending', 1);
                } elseif ($request->filter == '4') {
                    $query->orderBy('created_at', 'asc');
                }
            })
            ->whereHas('activeServices')
            ->paginate(10);

        return view(template() . 'frontend.card.index', $data);
    }

    public function getCard(Request $request)
    {
        $offset = request()->get('offset', 0);
        $limit = request()->get('limit', 10);

        if (!$request->catId) {
            $data['categories'] = Category::type('card')->active()->sort()
                ->get(['id', 'name', 'icon', 'type', 'active_children', 'status', 'sort_by']);
        }

        $data['cards'] = Card::select(['id', 'category_id', 'region', 'status',
            'name', 'slug', 'image', 'total_review', 'avg_rating'])
            ->where('status', 1)
            ->when(isset($request->catId), function ($query) use ($request) {
                return $query->where('category_id', $request->catId);
            })
            ->whereHas('activeServices')
            ->skip($offset)
            ->take($limit)
            ->get();

        return response()->json($data, 200);
    }

    public function cardDetails($slug = null)
    {
        $data['card'] = Card::with(['activeServices', 'activeServices.activeCodes'])->where(['status' => 1, 'slug' => $slug])->firstOrFail();

        $data['relatedCards'] = Card::select(['id', 'name', 'status', 'image', 'region', 'slug'])->where('id', '!=', $data['card']->id)
            ->where('status', 1)->where('name', 'LIKE', '%' . $data['card']->name . '%')->take(10)->get();

        $data['otherCards'] = Card::select(['id', 'name', 'status', 'image', 'region', 'slug'])
            ->where('id', '!=', $data['card']->id)->where('status', 1)->take(10)->get();

        $data['reviewStatic'] = $this->getTopReview(Card::class, $data['card']->id);

        return view($this->theme . 'frontend.card.details', $data);
    }

    public function singleOrder(Request $request)
    {
        $service = CardService::where('status', 1)->find($request->serviceId);

        if (!$service) {
            return response()->json(['status' => false, 'message' => 'Service not found']);
        }

        DB::beginTransaction();
        try {
            $quantity = $request->quantity;
            $totalAmount = showActualPrice($service) * $quantity;
            $quantities[$service->id] = $quantity;

            $order = $this->orderCreate($totalAmount, 'card');
            $this->orderDetailsCreate($order, $service, CardService::class, $quantities);
            DB::commit();

            return response()->json(['status' => true, 'route' => route('card.user.order', ['utr' => $order->utr])]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['status' => false, 'message' => 'Something went wrong']);
        }
    }

    public function buy(Request $request)
    {
        DB::beginTransaction();
        try {
            $cartItems = session()->get('cart');

            $ids = [];
            $quantities = [];
            if (!empty($cartItems)) {
                foreach ($cartItems as $cart) {
                    $ids[] = $cart['id'];
                    $quantities[$cart['id']] = $cart['quantity'];
                }
            }

            $services = CardService::whereHas('card', function ($query) {
                $query->where('status', 1);
            })->where('status', 1)->whereIn('id', $ids)->get();

            $totalAmount = 0;
            if (!empty($services)) {
                foreach ($services as $service) {
                    if (isset($quantities[$service->id])) {
                        $totalAmount += (showActualPrice($service) * $quantities[$service->id]);
                    }
                }
            }

            $order = $this->orderCreate($totalAmount, 'card');

            $this->orderDetailsCreate($order, $services, CardService::class, $quantities);
            DB::commit();

            return redirect()->route('card.user.order', ['utr' => $order->utr]);
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Something went wrong');
        }
    }


    public function order(Request $request)
    {
        $order = Order::select(['id', 'amount', 'payment_status', 'status',
            'order_for', 'utr', 'created_at', 'user_id', 'discount'])
            ->where(['utr' => $request->utr, 'payment_status' => 0, 'status' => 0, 'order_for' => 'card'])->firstOrFail();

        if ($request->method() == 'GET') {
            $gateways = Gateway::where('status', 1)->orderBy('sort_by', 'ASC')->get();
            return view(template() . 'frontend.card.order', compact('order', 'gateways'));
        } elseif ($request->method() == 'POST') {
            if ($order->amount > 0) {
                if (isset($request->gateway_id) && $request->gateway_id == '-1') {
                    $payByWallet = $this->payByWallet($order);
                    if (!$payByWallet['status']) {
                        return back()->with('error', $payByWallet['message']);
                    }

                    return redirect()->route('user.cardOrder', ['type' => 'all'])
                        ->with('success', 'Order has been placed successfully');
                }
                $validationRules = [
                    'gateway_id' => 'required|integer|min:1',
                    'supported_currency' => 'required',
                ];

                $validate = Validator::make($request->all(), $validationRules);
                if ($validate->fails()) {
                    return back()->withErrors($validate)->withInput();
                }

                $gateway = Gateway::select(['id', 'status'])->where('status', 1)->findOrFail($request->gateway_id);
                $checkAmountValidate = $this->validationCheck($order->amount, $gateway->id, $request->supported_currency, null, 'yes');

                if (!$checkAmountValidate['status']) {
                    return back()->with('error', $checkAmountValidate['message']);
                }

                $deposit = $this->depositCreate($checkAmountValidate, Order::class, $order->id);
                session()->forget('cart');
                return redirect(route('payment.process', $deposit->trx_id));
            } else {
                return back()->with('error', 'Unable to processed order');
            }
        }
    }

    public function addReview(Request $request)
    {
        $this->validate($request, [
            'cardId' => 'required',
            'rating' => 'required|numeric|min:1|max:5',
            'comment' => 'required|string|max:200',
        ]);

        try {
            $cardId = $request->cardId;
            $card = Card::select(['id', 'status', 'name'])->where('status', 1)->findOrFail($cardId);

            $isHasOrder = OrderDetail::with(["detailable" => function ($query) use ($cardId) {
                $query->whereHas('card', function ($q) use ($cardId) {
                    $q->where('id', $cardId);
                });
            }])
                ->whereHas('order', function ($qq) {
                    $qq->where('payment_status', 1);
                })
                ->where('user_id', auth()->id())
                ->where('detailable_type', CardService::class)
                ->exists();

            if ($isHasOrder) {
                Review::updateOrCreate([
                    'reviewable_type' => Card::class,
                    'reviewable_id' => $cardId,
                    'user_id' => auth()->id(),
                ], [
                    'rating' => $request->rating,
                    'comment' => $request->comment,
                ]);

                $this->reviewNotifyToAdmin(auth()->user(), $card->name, $request->rating);
                return back()->with('success', 'Review Added Successfully');
            }
            return back()->with('error', 'You are not eligible for review');
        } catch (\Exception $e) {
            return back()->with('error', 'You are not eligible for review');
        }
    }

}
PK     x\gKiN2  N2  -  Http/Controllers/Frontend/TopUpController.phpnu [        <?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Jobs\UpdateReviewAndRatingJob;
use App\Models\Category;
use App\Models\Coupon;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\Review;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\MakeOrder;
use App\Traits\PaymentValidationCheck;
use App\Traits\Rating;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class TopUpController extends Controller
{
    use MakeOrder, PaymentValidationCheck, Rating;

    public function __construct()
    {
        $this->theme = template();
    }

    public function topupList(Request $request)
    {
        $data['categories'] = Category::where('type', 'top_up')->where('status', 1)->get();
        list($min, $max) = array_pad(explode(';', $request->my_range, 2), 2, 0);

        $valueRange = TopUpService::selectRaw('MAX(price) as highValue, MIN(price) as lowValue')->first();
        $data['max'] = $request->has('my_range') ? $max : $valueRange->highValue;
        $data['min'] = $request->has('my_range') ? $min : $valueRange->lowValue;
        $data['max_price'] = $valueRange->highValue ?? 1000;
        $data['min_price'] = $valueRange->lowValue ?? 0;


        $data['topUp'] = TopUp::where('status', 1)
            ->when(isset($request->search) && !empty($request->search), function ($query) use ($request) {
                $query->where('name', 'LIKE', "%{$request->search}%");
            })
            ->when(isset($request->category) && !empty($request->category), function ($query) use ($request) {
                $query->where('category_id', $request->category);
            })
            ->when(isset($request->filter) && !empty($request->filter), function ($query) use ($request) {
                if ($request->filter == 'all') {
                    $query->orderBy('sort_by', 'desc');
                } elseif ($request->filter == '1') {
                    $query->orderBy('avg_rating', 'desc');
                } elseif ($request->filter == '2') {
                    $query->latest();
                } elseif ($request->filter == '3') {
                    $query->orderBy('created_at', 'asc');
                }
            })
            ->orderBy('sort_by', 'ASC')
            ->paginate(12);

        return view(template() . 'frontend.topUp.list', $data);
    }

    public function getDirectTopUp(Request $request)
    {
        $offset = request()->get('offset', 0);
        $limit = request()->get('limit', 16);

        if (!$request->catId) {
            $data['categories'] = Category::type('top_up')
                ->active()
                ->sort()
                ->get(['id', 'name', 'icon', 'type', 'active_children', 'status', 'sort_by']);
        }

        $data['topUps'] = TopUp::select(['id', 'category_id', 'status', 'name', 'slug', 'image'])
            ->where('status', 1)
            ->when($request->catId, function ($query) use ($request) {
                return $query->where('category_id', $request->catId);
            })
            ->whereHas('activeServices')
            ->skip($offset)
            ->take($limit)
            ->get();

        return response()->json($data, 200);
    }


    public function directTopUpDetails($slug = null)
    {
        $data['topUp'] = TopUp::with(['activeServices'])->where(['status' => 1, 'slug' => $slug])->firstOrFail();
        $data['reviewStatic'] = $this->getTopReview(TopUp::class, $data['topUp']->id);
        return view(template() . 'frontend.topUp.details', $data);
    }

    public function buy(Request $request)
    {

        $this->validate($request, [
            'topUpId' => ['required', 'numeric'],
            'serviceId' => ['required', 'numeric']
        ], [
            'topUpId.required' => 'Unprocessable. Please try again later',
            'serviceId.required' => 'Unprocessable. Please try again later'
        ]);

        DB::beginTransaction();
        try {
            $service = TopUpService::whereHas('topUp', function ($query) {
                $query->where('status', 1);
            })->where('status', 1)->findOrFail($request->serviceId);
            $topUp = $service->topUp;

            $rules = [];
            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    $rules[$cus->field_name] = ['required'];
                    if ($cus->field_type == 'select') {
                        $options = implode(',', array_keys((array)$cus->option));
                        array_push($rules[$cus->field_name], 'in:' . $options);
                    }
                }
            }

            $this->validate($request, $rules);

            $info = [];

            if ($topUp->order_information != null) {
                foreach ($topUp->order_information as $cus) {
                    if (isset($request->{$cus->field_name})) {
                        $info[$cus->field_name] = [
                            'field' => $cus->field_value,
                            'value' => $request->{$cus->field_name},
                        ];
                    }
                }
            }

            $order = $this->orderCreate(showActualPrice($service), 'topup', $info);
            $this->orderDetailsCreate($order, $service, TopUpService::class);

            session()->forget(['topupPrice']);
            session()->put('topupPrice', $order->amount);

            DB::commit();
            return redirect()->route('topUp.user.order', ['utr' => $order->utr]);
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', 'Something went wrong');
        }
    }

    public function order(Request $request)
    {
        $order = Order::select(['id', 'user_id', 'amount', 'payment_status',
            'status', 'order_for', 'utr', 'created_at', 'discount'])
            ->where(['utr' => $request->utr, 'payment_status' => 0, 'status' => 0, 'order_for' => 'topup'])->firstOrFail();

        if ($request->method() == 'GET') {
            $gateways = Gateway::where('status', 1)->orderBy('sort_by', 'ASC')->get();
            return view(template() . 'frontend.topUp.order', compact('order', 'gateways'));
        } elseif ($request->method() == 'POST') {

            try {
                if ($order->amount > 0) {
                    if (isset($request->gateway_id) && $request->gateway_id == '-1') {
                        $payByWallet = $this->payByWallet($order);
                        if (!$payByWallet['status']) {
                            return back()->with('error', $payByWallet['message']);
                        }

                        return redirect()->route('user.topUpOrder', ['type' => 'wait-sending'])
                            ->with('success', 'Order has been placed successfully');
                    }
                    $validationRules = [
                        'gateway_id' => 'required|integer|min:1',
                        'supported_currency' => 'required',
                    ];

                    $validate = Validator::make($request->all(), $validationRules);
                    if ($validate->fails()) {
                        return back()->withErrors($validate)->withInput();
                    }
                    $gateway = Gateway::select(['id', 'status'])->where('status', 1)->findOrFail($request->gateway_id);
                    $checkAmountValidate = $this->validationCheck($order->amount, $gateway->id, $request->supported_currency, null, 'yes');
                    if (!$checkAmountValidate['status']) {
                        return back()->with('error', $checkAmountValidate['message']);
                    }

                    $deposit = $this->depositCreate($checkAmountValidate, Order::class, $order->id);
                    return redirect(route('payment.process', $deposit->trx_id));
                } else {
                    return back()->with('error', 'Unable to processed order');
                }
            } catch (\Exception $exception) {
                return back()->with('error', 'Something went wrong. Please try later');
            }
        }
    }

    public function addReview(Request $request)
    {
        $this->validate($request, [
            'topUpId' => 'required',
            'rating' => 'required|numeric|min:1|max:5',
            'comment' => 'required|string|max:200',
        ]);

        try {
            $topUpId = $request->topUpId;
            $topUp = TopUp::select(['id', 'status', 'name'])->where('status', 1)->findOrFail($topUpId);

            $isHasOrder = OrderDetail::with(["detailable" => function ($query) use ($topUpId) {
                $query->whereHas('topUp', function ($q) use ($topUpId) {
                    $q->where('id', $topUpId);
                });
            }])
                ->whereHas('order', function ($qq) {
                    $qq->where('payment_status', 1);
                })
                ->where('user_id', auth()->id())
                ->where('detailable_type', TopUpService::class)
                ->exists();

            if ($isHasOrder) {

                $review = Review::updateOrCreate([
                    'reviewable_type' => TopUp::class,
                    'reviewable_id' => $topUpId,
                    'user_id' => auth()->id(),
                ], [
                    'rating' => $request->rating,
                    'comment' => $request->comment,
                ]);

                UpdateReviewAndRatingJob::dispatch($review->id, TopUp::class, $topUpId);

                $this->reviewNotifyToAdmin(auth()->user(), $topUp->name, $request->rating);
                return back()->with('success', 'Review Added Successfully');
            }
            return back()->with('error', 'You are not eligible for review');
        } catch (\Exception $e) {
            return back()->with('error', 'You are not eligible for review');
        }
    }

    public function couponApply(Request $request)
    {
        $order = Order::own()->with(['orderDetails:id,order_id,parent_id'])->where('payment_status', 0)
            ->where('utr', $request->utr)->latest()->first();

        if ($order->coupon_code == $request->couponCode) {
            return response()->json([
                'status' => 'error',
                'message' => 'Already Applied',
            ]);
        }

        if ($order) {
            $coupon = Coupon::where('code', $request->couponCode)->where('status', 1)
                ->where('start_date', '<=', Carbon::now())->first();

            if ($coupon && (!$coupon->end_date || $coupon->end_date > Carbon::now())) {

                $parentIds = $order->orderDetails->pluck('parent_id')->toArray();
                if ($order->order_for == 'topup') {
                    if (empty(array_diff($coupon->top_up_list ?? [], $parentIds))) {
                        return response()->json([
                            'status' => 'error',
                            'message' => 'You are not eligible to apply this coupon',
                        ]);
                    }
                }

                if ($order->order_for == 'card') {
                    if (empty(array_diff($coupon->card_list ?? [], $parentIds))) {
                        return response()->json([
                            'status' => 'error',
                            'message' => 'You are not eligible to apply this coupon',
                        ]);
                    }
                }

                if ($coupon->is_unlimited || ($coupon->used_limit > $coupon->total_use)) {
                    $discount = $coupon->discount;
                    if ($coupon->discount_type == 'percent') {
                        $discount = ($order->amount * $coupon->discount) / 100;
                    }

                    $order->coupon_id = $coupon->id;
                    $order->coupon_code = $coupon->code;
                    $order->amount = (($order->amount + $order->discount) - $discount);
                    $order->discount = $discount;
                    $order->save();

                    return response()->json([
                        'status' => 'success',
                        'discount' => getAmount($discount,2),
                        'amount' => getAmount($order->amount,2),
                        'total_amount' => userCurrencyPosition($order->amount),
                        'message' => "You get " . userCurrencyPosition($discount) . " discount",
                    ]);
                }
            }
        }

        return response()->json([
            'status' => 'error',
            'message' => 'You are not eligible to apply this coupon',
        ]);
    }

}
PK     x\+Zj-  -  ,  Http/Controllers/Frontend/CartController.phpnu [        <?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\CardService;
use App\Models\TopUpService;
use Illuminate\Http\Request;

class CartController extends Controller
{

    public function getCartList()
    {
        return view(template() . 'frontend.card.cart');
    }

    public function getCartItems()
    {
        $carts = [];
        $subtotal = 0;
        $discount = 0;
        $totalDiscount = 0;
        $totalPrice = 0;
        $totalSubtotal = 0;
        $cartItems = session()->get('cart');
        if (!empty($cartItems)) {
            $reversedCartItems = array_reverse($cartItems);
            foreach ($reversedCartItems as $cart) {
                $carts[] = [
                    "id" => $cart['id'],
                    "name" => $cart['name'],
                    "image" => $cart['image'],
                    "quantity" => $cart['quantity'],
                    "price" => userCurrencyPosition($cart['price']),
                    "actualPrice" => userCurrencyPosition($cart['actualPrice']),
                    "discount" => $cart['discount'] . '' . ($cart['discountType'] == 'flat' ? basicControl()->base_currency : '%'),
                    'totalPrice' => userCurrencyPosition($cart['quantity'] * $cart['price'])
                ];

                $price = $cart['price'] * (int)$cart['quantity'];
                $discount += calculateDiscountAmount($price, $cart['discount'], $cart['discountType']);
                $subtotal += $price;
            }

            $totalPrice = userCurrencyPosition(($subtotal - $discount));
            $totalSubtotal = userCurrencyPosition($subtotal);
            $totalDiscount = userCurrencyPosition($discount);
        }
        return response()->json(['status' => true, 'items' => $carts,
            'totalPrice' => $totalPrice, 'totalSubtotal' => $totalSubtotal, 'totalDiscount' => $totalDiscount]);
    }

    public function addCart(Request $request)
    {
        $service = CardService::where('status', 1)->find($request->serviceId);

        if (!$service) {
            return response()->json(['status' => false, 'message' => 'Service not found']);
        }

        $cart = session()->get('cart', []);
        $serviceId = $service->id;
        $quantity = $request->quantity;

        if (isset($cart[$serviceId])) {
            $cart[$serviceId]['quantity'] += $quantity;
        } else {
            $cart[$serviceId] = [
                "id" => $serviceId,
                "name" => $service->name,
                "image" => $service->imagePath(),
                "quantity" => $quantity,
                "price" => $service->price,
                "actualPrice" => showActualPrice($service),
                "discount" => $service->discount,
                "discountType" => $service->discount_type,
            ];
        }

        session()->put('cart', $cart);
        return response()->json(['status' => true, 'cartCount' => count(session()->get('cart')),
            'message' => 'Product added to cart successfully!']);
    }


    public function quantityUpdate(Request $request)
    {
        $cart = session()->get('cart');
        if (isset($cart[$request->serviceId])) {
            $cart[$request->serviceId]['quantity'] += $request->type;
            session()->put('cart', $cart);
            return response()->json(['status' => true]);
        }
        return response()->json(['status' => false, 'message', 'Something went wrong']);
    }

    public function remove(Request $request)
    {
        if ($request->serviceId) {
            $cart = session()->get('cart');
            if (isset($cart[$request->serviceId])) {
                unset($cart[$request->serviceId]);
                session()->put('cart', $cart);
                return response()->json(['status' => true]);
            }
        }
        return response()->json(['status' => false, 'message', 'Something went wrong']);
    }

    public function cartCount()
    {
        $cartCount = 0;
        if (session()->get('cart')) {
            $cartCount = count(session()->get('cart'));
            if (in_array($cartCount, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])) {
                $cartCount = $cartCount;
            }
        }
        $cartData = session()->get('cart', []);

        $totalDiscountAmount = 0;
        $totalAmount = 0;

        if (!empty($cartData)) {
            foreach ($cartData as $key => $item) {
                if (isset($item['price'], $item['actualPrice'])) {
                    $cartData[$key]['price'] = userCurrencyPosition($item['price']);
                    $cartData[$key]['actualPrice'] = userCurrencyPosition($item['actualPrice']);

                    $discountAmount = $item['price'] - $item['actualPrice'];
                    $cartData[$key]['discountAmount'] = userCurrencyPosition($discountAmount);
                    $amount = $item['price'] * $item['quantity'];
                    $totalDiscountAmount += ($discountAmount * $item['quantity']);
                    $totalAmount += ($amount - ($discountAmount * $item['quantity']));
                }
            }
        }

        $totalDiscountAmountFormatted = userCurrencyPosition($totalDiscountAmount);

        return response()->json([
            'status' => true,
            'cartCount' => $cartCount,
            'sessionCard' => $cartData,
            'totalDiscountAmount' => $totalDiscountAmountFormatted,
            'subTotal' => userCurrencyPosition($totalAmount),
        ]);
    }

}
PK     x\,    ,  Http/Controllers/Frontend/BlogController.phpnu [        <?php

namespace App\Http\Controllers\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Models\BlogCategory;
use App\Models\BlogDetails;
use App\Models\Content;
use App\Models\Page;
use App\Models\PageDetail;
use Illuminate\Http\Request;

class BlogController extends Controller
{

    public function blog(Request $request, $slug = null)
    {
        $page = Page::where('name', 'blog')->where('template_name', getTheme())->first();

        $data['pageSeo'] = [
            'page_title' => $page->page_title,
            'meta_title' => $page->meta_title,
            'meta_keywords' => implode(',', $page->meta_keywords ?? []),
            'meta_description' => $page->meta_description,
            'og_description' => $page->og_description,
            'meta_robots' => $page->meta_robots,
            'meta_image' => getFile($page->meta_image_driver, $page->meta_image),
            'breadcrumb_image' => $page->breadcrumb_status ?
                getFile($page->breadcrumb_image_driver, $page->breadcrumb_image) : null,
        ];

        $data['blogs'] = Blog::with('category', 'details')
            ->when($slug != null, function ($query) use ($slug) {
                $query->whereHas('category', function ($qq) use ($slug) {
                    $qq->where('slug', $slug);
                });
            })
            ->when(isset($request->search),  function ($query) use ($request) {
                $query->whereHas('details', function ($qq) use($request) {
                    $qq->where('title', 'like', '%' . $request->search . '%');
                });
            })
            ->orderBy('id', 'desc')
            ->paginate(basicControl()->paginate);


        return view(template() . 'blog', $data);
    }

    public function blogDetails(Request $request, $slug)
    {
        $data['pageSeo']['page_title'] = 'Blog Details';
        $data['blogDetails'] = BlogDetails::with('blog')
            ->whereHas('blog', function ($query) use($slug) {
                $query->where('slug', $slug);
            })->firstOrFail();

        $data['popularContentDetails'] = BlogDetails::with('blog')
            ->where('id', '!=', $data['blogDetails']->id)
            ->when(isset($request->title), function ($query) use ($request) {
                return $query->where('title', 'LIKE', '%' . $request->title . '%');
            })
            ->take(3)->latest()
            ->get();

        $data['categories'] = BlogCategory::withCount(['blogs'])->get();

        $blogDetails = $data['blogDetails'];
        $data['pageSeo'] = [
            'page_title' => optional($blogDetails->blog)->page_title,
            'meta_title' => optional($blogDetails->blog)->meta_title,
            'meta_keywords' => implode(',', optional($blogDetails->blog)->meta_keywords ?? []),
            'meta_description' => optional($blogDetails->blog)->meta_description,
            'og_description' => optional($blogDetails->blog)->og_description,
            'meta_robots' => optional($blogDetails->blog)->meta_robots,
            'meta_image' => getFile(optional($blogDetails->page)->meta_image_driver, optional($blogDetails->blog)->meta_image),
            'breadcrumb_image' => optional($blogDetails->blog)->breadcrumb_status ?
                getFile(optional($blogDetails->page)->breadcrumb_image_driver, optional($blogDetails->blog)->breadcrumb_image) : null,
        ];

        return view(template() . 'blog_details', $data);
    }
}
PK     x\ق    )  Http/Controllers/FaSecurityController.phpnu [        <?php

namespace App\Http\Controllers;

use App\Helpers\GoogleAuthenticator;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use PragmaRX\Google2FA\Google2FA;
use App\Traits\Notify;
use hisorange\BrowserDetect\Parser as Browser;
use Illuminate\Http\Request;

class FaSecurityController extends Controller
{
    use Notify;


    public function twoStepSecurity()
    {
        $basic = basicControl();
        $user = auth()->user();
        $google2fa = new Google2FA();
        $secret = $user->two_fa_code ?? $this->generateSecretKeyForUser($user);

        // Generate QR code URL
        $qrCodeUrl = $google2fa->getQRCodeUrl(
            auth()->user()->username,
            $basic->site_title,
            $secret
        );
        return view(template() . 'user.'.getDash().'.twoFA.index', compact('secret', 'qrCodeUrl'));
    }

    public function twoStepRegenerate()
    {
        $user = auth()->user();
        $user->two_fa_code = null;
        $user->save();
        session()->flash('success','Re-generate Successfully');
        return redirect()->route('user.twostep.security');
    }

    private function generateSecretKeyForUser(User $user)
    {
        $google2fa = new Google2FA();
        $secret = $google2fa->generateSecretKey();
        $user->update(['two_fa_code' => $secret]);

        return $secret;
    }

    public function twoStepEnable(Request $request)
    {
        $user = auth()->user();
        $secret = auth()->user()->two_fa_code;
        $google2fa = new Google2FA();
        $valid = $google2fa->verifyKey($secret, $request->code);
        if ($valid) {
            $user['two_fa'] = 1;
            $user['two_fa_verify'] = 1;
            $user->save();

            $this->mail($user, 'TWO_STEP_ENABLED', [
                'action' => 'Enabled',
                'code' => $user->two_fa_code,
                'ip' => request()->ip(),
                'time' => date('d M, Y h:i:s A'),
            ]);

            return back()->with('success', 'Google Authenticator Has Been Enabled.');
        } else {
            return back()->with('error', 'Wrong Verification Code.');
        }
    }


    public function twoStepDisable(Request $request)
    {
        $this->validate($request, [
            'password' => 'required',
        ]);

        if (!Hash::check($request->password, auth()->user()->password)) {
            return back()->with('error', 'Incorrect password. Please try again.');
        }

        auth()->user()->update([
            'two_fa' => 0,
            'two_fa_verify' => 1,
        ]);

        $user = auth()->user();
        $this->mail($user, 'TWO_STEP_DISABLED', [
            'time' => date('d M, Y h:i:s A'),
        ]);
        return redirect()->route('user.dashboard')->with('success', 'Two-step authentication disabled successfully.');
    }
}
PK     x\cJj  j  )  Http/Controllers/Admin/LogoController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Traits\Upload;

class LogoController extends Controller
{
    use Upload;

    public function logoSetting()
    {
        $basicControl = basicControl();
        return view('admin.control_panel.logo', compact('basicControl'));
    }

    public function logoUpdate(Request $request)
    {

        $request->validate([
            'logo' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
            'favicon' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
            'admin_logo' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
        ]);

        $basicControl = basicControl();
        if ($request->hasFile('logo')) {
            try {
                $image = $this->fileUpload($request->logo, config('filelocation.logo.path'), null, null,'webp', 60, $basicControl->logo, $basicControl->logo_driver);
                if ($image) {
                    $basicControl->logo = $image['path'];
                    $basicControl->logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Logo could not be uploaded.');
            }
        }

        if ($request->hasFile('favicon')) {
            try {
                $image = $this->fileUpload($request->favicon, config('filelocation.logo.path'), null, null, 'webp', 60, $basicControl->favicon,$basicControl->favicon_driver);
                if ($image) {
                    $basicControl->favicon = $image['path'];
                    $basicControl->favicon_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Favicon could not be uploaded.');
            }
        }

        if ($request->hasFile('admin_logo')) {
            try {
                $image = $this->fileUpload($request->admin_logo, config('filelocation.logo.path'), null, null, 'webp', 60,$basicControl->admin_logo, $basicControl->admin_logo_driver);
                if ($image) {
                    $basicControl->admin_logo = $image['path'];
                    $basicControl->admin_logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Admin Logo could not be uploaded.');
            }
        }

        if ($request->hasFile('admin_dark_mode_logo')) {
            try {
                $image = $this->fileUpload($request->admin_dark_mode_logo, config('filelocation.logo.path'), null, null, 'webp', 60,$basicControl->admin_dark_mode_logo,$basicControl->admin_dark_mode_logo_driver);
                if ($image) {
                    $basicControl->admin_dark_mode_logo = $image['path'];
                    $basicControl->admin_dark_mode_logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Admin Logo could not be uploaded.');
            }
        }

        $basicControl->save();

        return back()->with('success', 'Logo, favicon and breadcrumb has been updated.');

    }

}
PK     x\fH2  H2  -  Http/Controllers/Admin/LanguageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use Illuminate\Http\Request;
use App\Traits\Upload;
use Facades\App\Services\LocalizationService;
use Exception;
use Facades\App\Services\Translate\BaseTranslateService;

class LanguageController extends Controller
{
    use Upload;

    public function index()
    {
        $languages = Language::all();
        return view('admin.language.list', compact('languages'));
    }

    public function create()
    {
        $shortNames = config('languages.langCode');
        return view('admin.language.create', compact('shortNames'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:languages,name',
            'short_name' => 'required|string|max:3|unique:languages,short_name',
            'rtl' => 'nullable|integer|in:0,1',
            'status' => 'nullable|integer|in:0,1',
            'default_lang' => 'nullable|integer|in:0,1',
            'flag' => ' sometimes|required|mimes:jpg,png,jpeg|max:10240',
        ]);

        try {
            if ($request->file('flag') && $request->file('flag')->isValid()) {
                $image = $this->fileUpload($request->flag, config('filelocation.language.path'), null, null, 'webp', 60);
                if ($image) {
                    $flagImage = $image['path'];
                    $driver = $image['driver'] ?? 'local';
                }
            }

            $response = Language::create([
                'name' => $request->name,
                'short_name' => $request->short_name,
                'status' => $request->status,
                'rtl' => $request->rtl,
                'default_status' => $request->default_lang,
                'flag' => $flagImage ?? null,
                'flag_driver' => $driver ?? 'local'
            ]);

            if (!$response) {
                throw new Exception('Something went wrong while storing language. Please try again later.');
            }

            LocalizationService::createLang(defaultLang()->short_name, $request->short_name);

            if ($response->default_status == 1) {
                session()->put('lang', $response->short_name);
                session()->put('rtl', $response ? $response->rtl : 0);
                Language::whereNotIn('id', [$response->id])->get()->map(function ($item) {
                    $item->default_status = 0;
                    $item->save();
                });
            }
            return redirect()->route('admin.language.index')->with('success', "`{$response->name}` language has been created successfully.");
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit($id)
    {
        try {
            $language = Language::where('id', $id)->firstOr(function () {
                throw new Exception('No Language found.');
            });

            $shortNames = config('languages.langCode');
            return view('admin.language.edit', compact('language', 'shortNames'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:languages,name,' . $id,
            'short_name' => 'required|string|max:3|unique:languages,short_name,' . $id,
            'rtl' => 'nullable|integer|in:0,1',
            'status' => 'nullable|integer|in:0,1',
            'default_lang' => 'nullable|integer|in:0,1',
            'flag' => 'sometimes|required|mimes:jpg,png,jpeg,svg|max:10240',
        ]);

        try {
            $language = Language::where('id', $id)->firstOr(function () {
                throw new \Exception('No Language found.');
            });

            $oldShortName = $language->short_name;

            if ($request->file('flag') && $request->file('flag')->isValid()) {
                $image = $this->fileUpload($request->flag, config('filelocation.language.path'), null, null, 'webp', 60, $language->flag, $language->flag_driver);
                if ($image) {
                    $flagImage = $image['path'];
                    $flagDriver = $image['driver'];
                }
            }

            $response = $language->update([
                'name' => $request->name,
                'short_name' => $request->short_name,
                'status' => $request->status,
                'rtl' => $request->rtl,
                'flag' => $flagImage ?? $language->flag,
                'flag_driver' => $flagDriver ?? $language->flag_driver,
                'default_status' => $request->default_lang == 1 ? 1 : 0,
            ]);

            if (!$response) {
                throw new Exception('Something went wrong. Please try again later.');
            }

            LocalizationService::renameLang($oldShortName, $language->short_name);

            if ($language->default_status == 1) {
                session()->put('lang', $language->short_name);
                session()->put('rtl', $language ? $language->rtl : 0);
                Language::whereNotIn('id', [$language->id])->get()->map(function ($item) {
                    $item->default_status = 0;
                    $item->save();
                });
            }

            return back()->with('success', "`{$language->name}` language has been updated successfully");

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    function destroy(Request $request, $id)
    {
        try {
            $language = Language::where(['id' => $id, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you had selected default language.');
            });

            if (strtolower($language->short_name) != 'en') {
                $language->notificationTemplates()->delete();
                $language->pageDetails()->delete();
                $language->contentDetails()->delete();
                $response = $language->delete();
            }

            throw_if(!$response, 'Something went wrong. Please try again later.');
            LocalizationService::deleteLang($language->short_name);
            return back()->with('success', "`{$language->name}` language has been deleted successfully.");
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function keywords($shortName)
    {
        try {
            $language = Language::where('short_name', $shortName)->firstOr(function () {
                throw new \Exception('No Language found.');
            });
            $languages = Language::all();
            $keywords = json_decode(file_get_contents(resource_path('lang/') . strtolower($shortName) . '.json'));
            $pageTitle = $language->name . " Language Keyword";
            return view('admin.language.keywords', compact('language', 'keywords', 'languages', 'pageTitle'));
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function addKeyword(Request $request, $shortName)
    {
        $this->validate($request, [
            'key' => 'required|string|min:1|max:100',
            'value' => 'required|string|min:1|max:100'
        ], [
            'required' => 'This field is required.',
            'string' => 'This field must be string.'
        ]);
        try {
            $response = LocalizationService::updateLangKeyword($shortName, $request->key, $request->value);

            throw_if(!$response, 'Something went wrong. Please try again later.');

            session()->flash('success', "`{$request->key}` keyword has been added successfully.");
        } catch (\Exception $exception) {
            session()->flash('error', $exception->getMessage());
        }
        return response()->json(['url' => route('admin.language.keywords', $shortName)]);
    }


    public function updateKeyword(Request $request, $shortName, $key)
    {
        $this->validate($request, [
            'value' => 'required|string'
        ], [
            'required' => 'This field is required.',
            'string' => 'This field must be string.'
        ]);

        try {
            $key = urldecode($key);
            $routeName = request()->route()->getName();
            $default = $routeName == 'admin.update.language.default.keyword' ? true : false;
            $response = LocalizationService::updateLangKeyword($shortName, $key, $request->value, $default);
            throw_if(!$response, 'Something went wrong. Please try again later.');
            session()->flash('success', "`{$key}` keyword has been updated successfully.");
        } catch (\Exception $exception) {
            session()->flash('alert', $exception->getMessage());
        }
        return response()->json(['url' => route('admin.language.keywords', $shortName)]);
    }

    public function deleteKeyword($shortName, $key)
    {
        try {
            $key = urldecode($key);
            $response = LocalizationService::deleteLangKeyword($shortName, $key);

            throw_if(!$response, 'Something went wrong. Please try again later.');
            return back()->with('success', "`{$key}` keyword has been deleted successfully.");
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }


    public function importJson(Request $request)
    {
        try {
            $myLang = Language::where(['id' => $request->my_lang, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you selected default language.');
            });

            $lang = Language::findOrFail($request->lang_id);
            $json = file_get_contents(resource_path('lang/') . $lang->short_name . '.json');
            $jsonArray = json_decode($json, true);

            file_put_contents(resource_path('lang/') . $myLang->short_name . '.json', json_encode($jsonArray));
            return back()->with('success', 'Import data successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function changeStatus($id)
    {
        try {
            $language = Language::where(['id' => $id, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you selected default language.');
            });

            $response = $language->update([
                'status' => !$language->status
            ]);

            throw_if(!$response, 'Something went wrong. Please try again later.');

            $status = $language->status == 1 ? 'activated' : 'deactivated';
            return back()->with('success', "`{$language->name}` language has been {$status} successfully.");
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function singleKeywordTranslate(Request $request)
    {
        $shortName = $request->shortName;
        $key = $request->key;
        $singleTranslatedText = BaseTranslateService::singleKeywordTranslated($shortName, $key);

        $path = resource_path("lang/{$shortName}.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }

        $contents[$key] = $singleTranslatedText;
        file_put_contents($path, stripslashes(json_encode($contents, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)));
        return response([
            'message' => 'Keyword Translation Successfully.',
            'translatedText' => $singleTranslatedText
        ]);
    }

    public function allKeywordTranslate(Request $request, $shortName)
    {
        $allTranslatedText = BaseTranslateService::textTranslate($shortName);
        $path = resource_path("lang/{$shortName}.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }
        $mergedTranslations = array_merge($contents, $allTranslatedText);
        file_put_contents($path, json_encode($mergedTranslations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        return back()->with('success', 'Keyword Translation Successfully.');
    }
}
PK     x\F6  6  (  Http/Controllers/Admin/KycController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Kyc;
use App\Models\UserKyc;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Exception;
use Yajra\DataTables\Facades\DataTables;

class KycController extends Controller
{

    use Notify;

    public function index()
    {
        $data['kycList'] = Kyc::get();
        return view('admin.kyc.list', $data);
    }

    public function create()
    {
        return view('admin.kyc.create');
    }

    public function store(Request $request)
    {
        $requestData = $request->all();
        $rules = [
            'name' => 'required|string',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
        ];

        $validator = Validator::make($requestData, $rules, $customMessages);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $inputForm = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_label'] = ucwords($request->field_name[$a]);
                    $arr['type'] = $request->input_type[$a];
                    $arr['validation'] = $request->is_required[$a];
                    $inputForm[$arr['field_name']] = $arr;
                }
            }

            $kyc = Kyc::create([
                'name' => $request->name,
                'slug' => Slug($request->name),
                'input_form' => $inputForm,
                'status' => $request->status
            ]);

            if (!$kyc) {
                throw new Exception('something went wrong, Please try again');
            }

            return back()->with('success', 'KYC Store successfully');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function edit($id)
    {
        try {
            $data['kyc'] = Kyc::where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });

            return view('admin.kyc.edit', $data);

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

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

        $requestData = $request->all();
        $rules = [
            'name' => 'required|string',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
        ];

        $validator = Validator::make($requestData, $rules, $customMessages);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {

            $inputForm = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_label'] = ucwords($request->field_name[$a]);
                    $arr['type'] = $request->input_type[$a];
                    $arr['validation'] = $request->is_required[$a];
                    $inputForm[$arr['field_name']] = $arr;
                }
            }

            $kyc = Kyc::where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });

            $kyc->update([
                'name' => $request->name,
                'slug' => slug($request->name),
                'input_form' => $inputForm,
                'status' => $request->status
            ]);

            if (!$kyc) {
                throw new Exception('Something went wrong');
            }

            return back()->with('success', 'KYC updated successfully');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function userKycList($status = 'all')
    {

        $userKYCRecord = \Cache::get('userKYCRecord');
        if (!$userKYCRecord){
            $userKYCRecord = UserKyc::selectRaw('COUNT(id) AS totalKYC')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingKYCPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvedKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvedKYCPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS rejectedKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS rejectedKYCPercentage')
                ->get()
                ->toArray();
            \Cache::put('userKYCRecord', $userKYCRecord);
        }
        return view('admin.kyc.user_kyc', compact('status', 'userKYCRecord'));
    }

    public function userKycSearch(Request $request, $status = 'all')
    {
        $filterVerificationType = $request->filterVerificationType;
        $filterStatus = $request->filterStatus;
        $search = $request->search['value']??null;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $userKyc = UserKyc::query()->with(['user:id,username,firstname,lastname,image,image_driver'])
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('kyc_type', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%");
                            $q->orWhere('lastname', 'LIKE', "%$search%");
                            $q->orWhere('username', 'LIKE', "%$search%");
                            $q->orWhere('email', 'LIKE', "%$search%");
                        });
                });
            })
            ->when($status == 'all', function ($query) {
                return $query->whereIn('status', [0, 1, 2]);
            })
            ->when($status == 'pending', function ($query) {
                return $query->whereStatus(0);
            })
            ->when($status == 'approve', function ($query) {
                return $query->whereStatus(1);
            })
            ->when($status == 'rejected', function ($query) {
                return $query->whereStatus(2);
            })
            ->when(!empty($filterVerificationType), function ($query) use ($filterVerificationType) {
                return $query->where('kyc_type', $filterVerificationType);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($userKyc)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('verification type', function ($item) {
                return $item->kyc_type;
            })
            ->addColumn('status', function ($item) {
                $statusLabels = [
                    0 => '<span class="badge bg-soft-warning text-warning">
                            <span class="legend-indicator bg-warning"></span> ' . trans('Pending') . '
                        </span>',
                    1 => '<span class="badge bg-soft-success text-success">
                            <span class="legend-indicator bg-success"></span> ' . trans('Verified') . '
                        </span>',
                    2 => '<span class="badge bg-soft-danger text-danger">
                            <span class="legend-indicator bg-danger"></span> ' . trans('Rejected') . '
                        </span>'
                ];
                return isset($statusLabels[$item->status]) ? $statusLabels[$item->status] : '';
            })
            ->addColumn('action', function ($item) {
                $url = route('admin.kyc.view', $item->id);
                return '<a class="btn btn-white btn-sm" href="' . $url . '">
                      <i class="bi-eye"></i> ' . trans("View") . '
                    </a>';
            })
            ->rawColumns(['name', 'status', 'action'])
            ->make(true);
    }

    public function view($id)
    {
        try {
            $data['userKyc'] = UserKyc::with('user')->where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });
            return view('admin.kyc.view', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function action(Request $request, $id)
    {
        $req = $request->except('_token', '_method');
        $rules = [
            'rejected_reason' => 'sometimes|required|string|min:3',
            'status' => 'nullable|integer|in:0,1,2'
        ];

        $validator = Validator::make($req, $rules);
        if ($validator->fails()) {
            $newArr = $validator->getMessageBag();
            $newArr->add('rejectedMessage', 1);
            return back()->withErrors($newArr)->withInput();
        }

        try {
            $userKyc = UserKyc::findOrFail($id);
            if ($request->status == 1) {
                $userKyc->status = 1;
                $userKyc->approved_at = now();
                $message = 'Approved Successfully';
                $this->userSendMailNotify($userKyc->user, 'approve');
            } elseif ($request->status == 2) {
                $userKyc->status = 2;
                $userKyc->reason = $request->rejected_reason;
                $message = 'Rejected Successfully';
                $this->userSendMailNotify($userKyc->user, 'reject');
            }

            $userKyc->save();
            return back()->with('success', $message);

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function userSendMailNotify($user, $type)
    {
        if ($type == 'approve') {
            $templateKey = 'KYC_APPROVED';
        } else {
            $templateKey = 'KYC_REJECTED';
        }
        $action = [
            "link" => "#",
            "icon" => "fa-light fa-address-book"
        ];
        $this->sendMailSms($user, $templateKey);
        $this->userPushNotification($user, $templateKey, $action);
        $this->userFirebasePushNotification($user, $templateKey);
        return 0;
    }

    public function kycIsMandatory(Request $request){


        $validated = $request->validate([
            'kycMandatory' => 'required',
        ]);

        $setting = basicControl();
        $setting->isKycMandatory = $validated['kycMandatory'];
        $setting->save();

        return response()->json([
            'success' => true,
            'message' => 'KYC status updated successfully.',
            'currentStatus' => $setting->isKycMandatory
        ]);
    }
}
PK     x\z  z  2  Http/Controllers/Admin/PaymentMethodController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Gateway;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class PaymentMethodController extends Controller
{
    use Upload;

    public function index()
    {
        $data['paymentGateways'] = Gateway::automatic()->orderBy('sort_by', 'ASC')->get();
        return view('admin.payment_methods.list', $data);
    }

    public function sortPaymentMethods(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Gateway::where('code', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function edit($id)
    {
        try {
            $data['basicControl'] = basicControl();
            $data['method'] = Gateway::findOrFail($id);
            return view('admin.payment_methods.edit', $data);
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|string',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.name' => 'required|string',
            'receivable_currencies.*.currency_symbol' => 'required|string|max:255',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'description' => 'required|string|min:3',
            'is_active' => 'nullable|integer|in:0,1',
            'test_environment' => 'sometimes|required|string|in:test,live',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'receivable_currencies.*.currency_symbol.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $gateway = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception('No payment method found');
        });

        $parameters = [];
        foreach ($request->except('_token', '_method', 'image') as $k => $v) {
            foreach ($gateway->parameters as $key => $cus) {
                if ($k != $key) {
                    continue;
                } else {
                    $rules[$key] = 'required';
                    $parameters[$key] = $v;
                }
            }
        }

        $validator = Validator::make($request->all(), $rules, $customMessages);

        if ($validator->fails()) {
            $names = collect(request()->receivable_currencies)
                ->filter(function ($item) {
                    return isset($item['name']) && $item['name'] !== null;
                })
                ->pluck('name')
                ->toArray();
            return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput($request->input())
                ->with('selectedCurrencyList', $names);
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 70, $gateway->image, $gateway->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $collection = collect($request->receivable_currencies);
            $supportedCurrency = $collection->pluck('name')->all();
            $response = $gateway->update([
                'name' => $request->name,
                'supported_currency' => $supportedCurrency,
                'receivable_currencies' => $request->receivable_currencies,
                'description' => $request->description,
                'parameters' => $parameters,
                'image' => $gatewayImage ?? $gateway->image,
                'driver' => $driver ?? $gateway->driver,
                'environment' => $request->test_environment ?? null,
                'status' => $request->is_active
            ]);

            if (!$response) {
                throw new \Exception('Unexpected error! Please try again.');
            }
            return back()->with('success', 'Gateway data has been updated.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }


    public function deactivate(Request $request)
    {
        try {
            $gateway = Gateway::where('code', $request->code)->firstOrFail();
            $gateway->update([
                'status' => $gateway->status == 1 ? 0 : 1
            ]);
            return back()->with('success', 'Gateway status updated successfully.');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     x\2-  -  2  Http/Controllers/Admin/SupportTicketController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\SupportTicketAttachment;
use App\Models\SupportTicketMessage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Exception;
use App\Traits\Upload;
use App\Traits\Notify;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class SupportTicketController extends Controller
{
    use Upload, Notify;

    public function tickets($status = 'all')
    {
        $ticketRecord = \Cache::get('ticketRecord');
        if (!$ticketRecord) {
            $ticketRecord = SupportTicket::selectRaw('COUNT(id) AS totalTicket')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS openTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS openTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS answerTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS answerTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS repliedTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS repliedTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS closedTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS closedTicketPercentage')
                ->get()
                ->toArray();
            \Cache::put('ticketRecord', $ticketRecord);
        }
        return view('admin.support_ticket.list', compact('status', 'ticketRecord'));
    }


    public function ticketSearch(Request $request)
    {

        $filterSubject = $request->subject;
        $filterStatus = $request->filterStatus;
        $search = $request->search['value'];
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $supportTicket = SupportTicket::query()->with('user:id,username,firstname,lastname,image,image_driver')
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('subject', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%");
                            $q->orWhere('lastname', 'LIKE', "%$search%");
                            $q->orWhere('username', 'LIKE', "%$search%");
                            $q->orWhere('email', 'LIKE', "%$search%");
                        });
                });
            })
            ->when(!empty($filterSubject), function ($query) use ($filterSubject) {
                return $query->where('subject', $filterSubject);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });

        return DataTables::of($supportTicket)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('username', function ($item) {
                $url = route("admin.user.edit", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('subject', function ($item) {
                return Str::limit($item->subject, 30);

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return ' <span class="badge bg-soft-warning text-warning">
                                    <span class="legend-indicator bg-warning"></span> ' . trans('Open') . '
                                </span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                                    <span class="legend-indicator bg-success"></span> ' . trans('Answered') . '
                                </span>';

                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-info text-info">
                                    <span class="legend-indicator bg-info"></span> ' . trans('Customer Reply') . '
                                </span>';

                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">
                                    <span class="legend-indicator bg-danger"></span> ' . trans('Closed') . '
                                </span>';
                }
            })
            ->addColumn('lastReply', function ($item) {
                return dateTime($item->last_reply);
            })
            ->addColumn('action', function ($item) {
                $url = route('admin.ticket.view', $item->id);
                return '<a class="btn btn-white btn-sm" href="' . $url . '">
                      <i class="bi-eye"></i> ' . trans("View") . '
                    </a>';
            })
            ->rawColumns(['username', 'subject', 'status', 'action'])
            ->make(true);
    }


    public function ticketView($id)
    {
        $data['ticket'] = SupportTicket::where('id', $id)->with('user', 'messages')->firstOrFail();
        $data['title'] = "Ticket #" . $data['ticket']->ticket;
        return view('admin.support_ticket.view', $data);
    }


    public function ticketReplySend(Request $request, $id)
    {
        $request->validate([
            'message' => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $admin = Auth::guard('admin')->user();

            $ticketRes = SupportTicket::where('id', $id)->firstOr(function () {
                throw new \Exception('No data found!');
            });

            $ticketRes->update([
                'last_reply' => Carbon::now(),
                'status' => 1,
            ]);

            if (!$ticketRes) {
                DB::rollBack();
                throw new Exception('Something went wrong while updating data.');
            }

            $resTicketDetails = SupportTicketMessage::create([
                'support_ticket_id' => $id,
                'admin_id' => $admin->id,
                'message' => $request->message,
            ]);

            if (!$resTicketDetails) {
                DB::rollBack();
                throw new Exception('Something went wrong while updating data.');
            }

            if (!empty($request->attachments)) {
                $attachments = [];
                $numberOfAttachments = count($request->attachments);

                for ($i = 0; $i < $numberOfAttachments; $i++) {
                    if ($request->hasFile('attachments.' . $i)) {
                        $file = $request->file('attachments.' . $i);
                        $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), null, null, 'webp', null);
                        if (empty($supportFile['path'])) {
                            throw new Exception('File could not be uploaded.');
                        }
                        $attachments[] = [
                            'support_ticket_message_id' => $resTicketDetails->id,
                            'file' => $supportFile['path'],
                            'driver' => $supportFile['driver'] ?? 'local',
                        ];
                    }
                }
            }

            if (!empty($attachments)) {
                $attachmentResponse = DB::table('support_ticket_attachments')->insert($attachments);
                if (!$attachmentResponse) {
                    DB::rollBack();
                    throw new Exception('Something went wrong while storing attachments. Please try again later.');
                }
            }

            DB::commit();

            $msg = [
                'ticket_id' => $ticketRes->ticket
            ];
            $action = [
                "link" => route('user.ticket.view', $ticketRes->ticket),
                "icon" => "fas fa-ticket-alt text-white"
            ];

            $this->userPushNotification($ticketRes->user, 'ADMIN_REPLIED_TICKET', $msg, $action);
            $this->userFirebasePushNotification($ticketRes->user, 'ADMIN_REPLIED_TICKET', $msg, $action);
            $this->sendMailSms($ticketRes->user, 'ADMIN_REPLIED_TICKET', [
                'ticket_id' => $ticketRes->ticket,
                'ticket_subject' => $ticketRes->subject,
                'reply' => $request->message,
            ]);

            return back()->with('success', "Ticket has been replied");

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }

    }

    public function ticketClosed($id)
    {
        $ticket = SupportTicket::findOrFail($id);
        $ticket->update([
            'status' => 3
        ]);
        return back()->with('success', "Ticket has been closed");
    }

    public function ticketDownload($ticket_id)
    {
        $attachment = SupportTicketAttachment::with('supportMessage', 'supportMessage.ticket')->findOrFail(decrypt($ticket_id));
        $file = $attachment->file;
        $full_path = getFile($attachment->driver, $file);
        $title = slug($attachment->supportMessage->ticket->subject) . '-' . $file;
        header('Content-Disposition: attachment; filename="' . $title);
        header("Content-Type: " . $full_path);
        return readfile($full_path);
    }


}
PK     x\R8_2  2  3  Http/Controllers/Admin/RolePermissionController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTables;

class RolePermissionController extends Controller
{
    protected $admin;
    public function editStaff($id)
    {
        $staff = Admin::findOrFail($id);
        $roles = Role::where('status',1)->get();
        return view('admin.manage_staff.edit',compact('staff','roles'));
    }
    public function staffUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => ['required',Rule::exists('admins', 'id')],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($request->id)],
            'username' => ['required', 'string', 'max:50', Rule::unique('admins', 'username')->ignore($request->id)],
            'role' => ['required'],
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->messages()], 422);
        }

        $user = Admin::findOrFail($request->id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->username = $request->username;
        $user->role_id = $request->role;
        $user->status = $request->status?1:0;
        if ($request->password){
            $user->password = Hash::make($request->password);
        }
        $user->save();
        session()->flash('success', 'User Updated Successfully');
        return redirect()->route('admin.role.staff');
    }

   public function index()
   {
       return view('admin.role_permission.index');
   }

    public function getRoleList(Request $request)
    {
        $roles = Role::query()
            ->when(!empty($request->search['value']),function ($query) use ($request){
                $query->where('name','LIKE','%'.$request->search['value'].'%');
            })
            ->orderBy('id', 'desc');

        return DataTables::of($roles)
            ->addColumn('no',function ($item){
                static $counter = 0;
                return ++$counter;
            })
            ->addColumn('name',function ($item){
                return $item->name;
            })
            ->addColumn('status',function ($item){
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                $bg = $item->status == 1 ? 'success' : 'danger';
                return "<span class='badge  bg-soft-success text-$bg bg-soft-$bg text-$bg'><span class='legend-indicator bg-$bg'></span>".$status."</span>";
            })
            ->addColumn('action',function ($item){
                $id = $item->id;
                $deleteUrl = route('admin.role.delete',$item->id);

                    return "<div class='btn-group' role='group'>
                      <a href='javascript:void(0)' class='btn btn-white btn-sm edit_user_btn edit_role_btn' data-bs-toggle='modal' data-bs-target='#EditRoleModal' data-id='$id'>
                        <i class='bi bi-pencil-square dropdown-item-icon'></i> ".trans('Edit')."
                      </a>
                    <div class='btn-group'>
                      <button type='button' class='btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty' id='userEditDropdown' data-bs-toggle='dropdown' aria-expanded='false'></button>
                      <div class='dropdown-menu dropdown-menu-end mt-1' aria-labelledby='userEditDropdown'>
                         <a class='dropdown-item loginAccount DeleteBtn' data-route='$deleteUrl' href='javascript:void(0)' data-bs-toggle='modal' data-bs-target='#deleteModal'>
                           <i class='bi bi-trash dropdown-item-icon'></i>
                          ".trans("Delete")."
                        </a>
                      </div>
                    </div>
                  </div>";
            })
            ->rawColumns(['no','name','status','action'])
            ->make(true);
    }

    public function getRole($id)
    {
        $role = Role::findOrFail($id);
        return response()->json([
            'role' => $role,
        ]);
    }

    public function staffList()
    {
        return view('admin.manage_staff.index');
    }

    public function getStaffList(Request $request)
    {
        $staffs = Admin::query()->with('role')
            ->where('id','!=',auth()->guard('admin')->id())
            ->whereNotNull('role_id')
            ->orderBy('name', 'asc')
            ->when(!empty($request->search['value']),function ($query)use($request){
                $query->where('name','LIKE','%'.$request->search['value'].'%')
                    ->orWhere('username','LIKE','%'.$request->search['value'].'%')
                    ->orWhereHas('role',function ($subQuery)use($request){
                        $subQuery->where('name','LIKE','%'.$request->search['value'].'%');
                    });
            });
        return DataTables::of($staffs)
            ->addColumn('no',function (){
                static  $count = 0;
                return ++$count;
            })
            ->addColumn('user',function ($item){
                $profile = '';
                if (!$item->image) {
                    $firstLetter = substr($item->name, 0, 1);
                    $profile =  '<div class="avatar avatar-sm avatar-soft-primary avatar-circle">
                        <span class="avatar-initials">' . $firstLetter . '</span>
                     </div>';

                } else {
                    $url = getFile($item->image_driver, $item->image);
                    $profile =  '<div class="avatar avatar-sm avatar-circle">
                        <img class="avatar-img" src="' . $url . '" alt="Image Description">
                     </div>';

                }
                return  '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                            <div class="flex-shrink-0">
                                    '.$profile.'
                             </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                              <h5 class="text-hover-primary mb-0">' . optional($item)->name.'</h5>
                              <span class="fs-6 text-body">@' . optional($item)->username ?? 'Unknown' . '</span>
                            </div>
                          </a>';
            })
            ->addColumn('role',function ($item){
                return "<span class='badge bg-primary rounded-pill'>".optional($item->role)->name."</span>";
            })
            ->addColumn('status',function ($item){
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                $bg = $item->status == 1 ? 'success' : 'danger';
                return "<span class='badge  bg-soft-success text-$bg bg-soft-$bg text-$bg'><span class='legend-indicator bg-$bg'></span>".$status."</span>";
            })
            ->addColumn('action',function ($item){
                $editUrl = route('admin.edit.staff',$item->id);
                $status = $item->status == 1?'Inactive':'Active';
                $statsChangeUrl = route('admin.role.statusChange', $item->id);
                $loginUrl = route('admin.role.usersLogin',$item->id);
                $icon = $item->status==1?"<i class='fa-light fa-circle-xmark dropdown-item-icon'></i>":'<i class="fa-sharp fa-light fa-check dropdown-item-icon"></i>';
                return adminAccessRoute(config('role.manage_staff.access.edit'))?"<div class='btn-group' role='group'>
                      <a href='$editUrl' class='btn btn-white btn-sm edit_user_btn'>
                        <i class='bi bi-pencil-square dropdown-item-icon'></i> ".trans('Update Staff')."
                      </a>
                    <div class='btn-group'>
                      <button type='button' class='btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty' id='userEditDropdown' data-bs-toggle='dropdown' aria-expanded='false'></button>
                      <div class='dropdown-menu dropdown-menu-end mt-1' aria-labelledby='userEditDropdown'>
                          <a class='dropdown-item LoginAccount'  href='javascript:void(0)' data-route='$loginUrl' >
                           <i class='fa-sharp fa-light fa-right-to-bracket dropdown-item-icon'></i>
                          ".trans("Login as Staff")."
                        </a>
                        <a class='dropdown-item  statusChangeButton' href='javascript:void(0)' data-route='$statsChangeUrl' data-bs-toggle='modal' data-bs-target='#statusChangeModal' data-status='$status'>
                       $icon
                          ".trans($status)."
                        </a>
                      </div>
                    </div>
                  </div>":'';
            })
            ->rawColumns(['no','user','role','status','action'])
            ->make(true);
    }

    public function staffCreate()
    {
        $roles = Role::where('status',1)->get();
        return view('admin.manage_staff.create',compact('roles'));
    }

    public function staffStore(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
            'username' => ['required', 'string', 'max:50', 'unique:admins,username'],
            'password' => ['required', 'string', 'min:6'],
            'role' => ['required'],
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $user = new Admin();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->username = $request->username;
        $user->password = Hash::make($request->password);
        $user->role_id = $request->role;
        $user->status = $request->status == 'on'?1:0;

        $user->save();
        session()->flash('success', 'Saved Successfully');
        return redirect()->route('admin.role.staff');
    }

    public function statusChange($id)
    {
        $user = Admin::findOrFail($id);
        if ($user) {
            if ($user->status == 1) {
                $user->status = 0;
            } else {
                $user->status = 1;
            }
            $user->save();
            return back()->with('success', 'Updated Successfully');
        }
    }

    public function userLogin($id)
    {
        Auth::guard('admin')->loginUsingId($id);
        $list = collect(config('role'))->pluck(['access','view'])->collapse()->intersect(optional(optional(Auth::guard('admin')->user())->role)->permission);
        if(count($list) == 0){
            $list = collect(['admin.profile']);
        }
        return redirect()->intended(route($list->first()));
    }

    public function roleCreate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'status' => 'required|boolean',
            'access' => 'required|array|min:1',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $role = new Role();
        $role->user_id = auth()->id();
        $role->name = $request->name;
        $role->status = $request->status;
        $role->permission =  (isset($request->access)) ? $request->access : [];

        $role->save();
        session()->flash('success', 'Saved Successfully');
        return redirect()->back();
    }

    public function roleUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'status' => 'required|boolean',
            'access' => 'required|array|min:1',
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->messages()], 422);
        }
        $role = Role::findOrFail($request->id);
        try {
            $role->name = $request->name;
            $role->status = $request->status;
            $role->permission =  (isset($request->access)) ? $request->access : [];
            $role->save();
        }catch (\Exception $exception){
            return back()->with('error', $exception->getMessage());
        }

        session()->flash('success', 'Update Successfully');
        return redirect()->back();
    }

    public function roleDelete($id)
    {
        $role = Role::with(['roleUsers'])->find($id);
        if (count($role->roleUsers) > 0) {
            return back()->with('error','This role has many users');
        }
        $role->delete();
        return back()->with('success', 'Delete successfully');
    }
}
PK     x\%]Ժ)  )  ,  Http/Controllers/Admin/ContentController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\ContentDetails;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Traits\Upload;


class ContentController extends Controller
{
    use Upload;

    public function index($content)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $data['singleContent'] = config('contents.' . $content . '.single');
        $data['multipleContents'] = config('contents.' . $content . '.multiple');
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $defaultLanguage = $data['languages']->where('default_status', true)->first();

        $data['singleContentData'] = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
            })->get()->groupBy('language_id');


        $data['multipleContentData'] = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
                $query->where('type', 'multiple');
            })->where('language_id', $defaultLanguage->id)
            ->get();

        $contentImage = config('contents.' . $content . '.preview');

        return view('admin.frontend_management.content.index', $data, compact('content', 'contentImage'));

    }

    public function store(Request $request, $content, $language)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.single.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $singleContent = Content::updateOrCreate(['name' => $content], ['name' => $content, 'type' => 'single']);

        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $singleContent->media->{$key} ?? null;
            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.single.size.image');
                    $image = $this->fileUpload($request->$key, config('filelocation.contents.path'), null, $size,'webp');
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('alert', 'Image could not be uploaded.');
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $singleContent->media = $mediaData;
            $singleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.single.field_name'), config("contents.content_media"));

        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::updateOrCreate(
                ['content_id' => $singleContent->id, 'language_id' => $language],
                ['content_id' => $singleContent->id, 'language_id' => $language, 'description' => $description ?: null]
            );
        }

        if (!$contentDetails) {
            return back()->with('Something went wrong, Please try again.');
        }
        return back()->with('success', 'Content Created Successfully');
    }

    public function manageContentMultiple($content)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['multipleContent'] = config('contents.' . $content . '.multiple');

        return view('admin.frontend_management.content.create', $data, compact('content'));
    }

    public function manageContentMultipleStore(Request $request, $content, $language)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.multiple.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $multipleContent = Content::create(['name' => $content, 'type' => 'multiple']);

        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $multipleContent->media->{$key} ?? null;

            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.multiple.size.image');

                    $image = $this->fileUpload($request->$key, config('filelocation.contents.path'), null, $size, 'webp', 60);
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('error', $exp->getMessage());
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $multipleContent->media = $mediaData;
            $multipleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.multiple.field_name'), config("contents.content_media"));
        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::create([
                'content_id' => $multipleContent->id,
                'language_id' => $language,
                'description' => $description ?? null
            ]);
        }

        if (!$contentDetails) {
            throw new \Exception("Something went wrong, Please try again");
        }

        return back()->with('success', 'Created Successfully');
    }

    public function multipleContentItemEdit($content, $id)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['multipleContent'] = config('contents.' . $content . '.multiple');

        $data['multipleContentData'] = ContentDetails::with('content')
            ->where('content_id', $id)
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
                $query->where('type', 'multiple');
            })
            ->get()->groupBy('language_id');
        return view('admin.frontend_management.content.edit', $data, compact('content', 'id'));
    }

    public function multipleContentItemUpdate(Request $request, $content, $id, $language)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.multiple.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $multipleContent = Content::findOrFail($id);
        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $multipleContent->media->{$key} ?? null;
            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.multiple.size.image');
                    $image = $this->fileUpload($request->$key, config('filelocation.contents.path'), null, $size, 'webp', 60, @$multipleContent->media->image->path, @$multipleContent->media->image->driver);
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('alert', 'Image could not be uploaded.');
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $multipleContent->media = $mediaData;
            $multipleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.multiple.field_name'), config("contents.content_media"));

        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::updateOrCreate(
                ['content_id' => $id, 'language_id' => $language],
                ['content_id' => $id, 'language_id' => $language, 'description' => $description ?: null]
            );
        }

        if (!$contentDetails) {
            throw new \Exception("Something went wrong, Please try again");
        }

        return back()->with('success', 'Created Successfully');
    }


    public function ContentDelete($id)
    {
        try {
            $content = Content::findOrFail($id);
            $content->delete();

            $this->fileDelete(optional(optional($content->media)->image)->driver, optional(optional($content->media)->image)->path);

            $contentDetails = ContentDetails::where('content_id', $id)->get();
            foreach ($contentDetails as $detail) {
                $detail->delete();
            }
            return back()->with('success', 'Content has been deleted');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }


}
PK     x\g  g  ,  Http/Controllers/Admin/StorageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FileStorage;
use Illuminate\Http\Request;
use App\Traits\Upload;

class StorageController extends Controller
{
    use Upload;

    public function index()
    {
        $data['fileStorageMethod'] = FileStorage::orderBy('id', 'asc')->get();
        return view('admin.storage.index', $data);
    }

    public function edit($id)
    {
        $fileStorageMethod = FileStorage::where('code', '!=', 'local')->findOrFail($id);
        return view('admin.storage.edit', compact('fileStorageMethod'));
    }

    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|min:2|max:20|string',
        ];

        $storage = FileStorage::where('code', '!=', 'local')->findOrFail($id);
        $parameters = [];
        foreach ($request->except('_token', '_method', 'image') as $k => $v) {
            foreach ($storage->parameters as $key => $cus) {
                if ($k != $key) {
                    continue;
                } else {
                    $rules[$key] = 'required|string|min:1|max:191';
                    $parameters[$key] = $v;
                }
            }
        }

        $request->validate($rules);

        try {
            $response = $storage->update([
                'name' => $request->name,
                'parameters' => $parameters,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please try again.");
            }
            $this->envWrite($storage->code, $storage->parameters);
        } catch (\Exception $e) {
            return back()->with("error", $e->getMessage());
        }
        return back()->with('success', 'File Storage System Updated Successfully.');
    }

    public function setDefault(Request $request, $id)
    {
        try {
            $activeStorage = FileStorage::findOrFail($id);
            $activeStorage->update([
                'status' => 1
            ]);

            $storages = FileStorage::where('id', '!=', $id)->get();
            foreach ($storages as $storage) {
                $storage->update([
                    'status' => 0
                ]);
            }

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('FILESYSTEM_DRIVER', $activeStorage->code, $env);
            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            return back()->with('success', 'File system Set As Default Updated Successfully');
        } catch (\Exception $e) {
            return back()->with("error", $e->getMessage());
        }
    }

    public function envWrite($storageType, $parameters)
    {
        $envPath = base_path('.env');
        $env = file($envPath);
        if ($storageType == 's3') {
            $env = $this->set('AWS_ACCESS_KEY_ID', $parameters['access_key_id'], $env);
            $env = $this->set('AWS_SECRET_ACCESS_KEY', $parameters['secret_access_key'], $env);
            $env = $this->set('AWS_DEFAULT_REGION', $parameters['default_region'], $env);
            $env = $this->set('AWS_BUCKET', $parameters['bucket'], $env);
            $env = $this->set('AWS_URL', $parameters['url'], $env);
            $env = $this->set('AWS_ENDPOINT', $parameters['endpoint'], $env);
        } elseif ($storageType == 'sftp') {
            $env = $this->set('SFTP_USERNAME', $parameters['sftp_username'], $env);
            $env = $this->set('SFTP_PASSWORD', $parameters['sftp_password'], $env);
        } elseif ($storageType == 'do') {
            $env = $this->set('DIGITALOCEAN_SPACES_KEY', $parameters['spaces_key'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_SECRET', $parameters['spaces_secret'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_ENDPOINT', $parameters['spaces_endpoint'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_REGION', $parameters['spaces_region'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_BUCKET', $parameters['spaces_bucket'], $env);
        } elseif ($storageType == 'ftp') {
            $env = $this->set('FTP_HOST', $parameters['ftp_host'], $env);
            $env = $this->set('FTP_USERNAME', $parameters['ftp_username'], $env);
            $env = $this->set('FTP_PASSWORD', $parameters['ftp_password'], $env);
        }
        $env = $this->set('FILESYSTEM_DRIVER', $storageType, $env);
        $fp = fopen($envPath, 'w');
        fwrite($fp, implode($env));
        fclose($fp);
        return 0;
    }


    private function set($key, $value, $env)
    {
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            if ($entry[0] == $key) {
                $env[$env_key] = $key . "=" . $value . "\n";
            } else {
                $env[$env_key] = $env_value;
            }
        }
        return $env;
    }
}
PK     x\x#*  #*  -  Http/Controllers/Admin/CurrencyController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CurrencyStoreRequest;
use App\Models\Currency;
use App\Traits\CurrencyRateUpdate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Mockery\Exception;
use Yajra\DataTables\Facades\DataTables;

class CurrencyController extends Controller
{
    use CurrencyRateUpdate;

    public function currencyList()
    {
        return view('admin.currency.index');
    }

    public function currencyListSearch(Request $request)
    {
        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $currencies = Currency::orderBy('sort_by', 'ASC')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%")
                        ->orWhere('code', 'LIKE', "%$search%")
                        ->orWhere('rate', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($currencies)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                return '<span>' . $item->name . '(' . $item->symbol . ')' . '</span>';

            })
            ->addColumn('code', function ($item) {
                return '<span>' . $item->code . '</span>';

            })
            ->addColumn('rate', function ($item) use ($basicControl) {
                $rate = number_format($item->rate, 4);
                return "<span class='text-dark'> 1 $basicControl->base_currency = $rate $item->code </span>";

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.currencyStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.currencyStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.currencyDelete', $item->id);

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                       data-name="' . $item->name . '" data-code="' . $item->code . '" data-symbol="' . $item->symbol . '" data-rate="' . $item->rate . '"
                       data-route="' . route('admin.currencyEdit', $item->id) . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'code', 'rate', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function currencyCreate(CurrencyStoreRequest $request)
    {
        try {
            $currency = new Currency();
            $fillData = $request->except('_token');
            $currency->fill($fillData)->save();
            return back()->with('success', 'Currency Added Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyEdit(CurrencyStoreRequest $request, $id)
    {
        $currency = Currency::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $currency->fill($fillData)->save();
            return back()->with('success', 'Currency Updated Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyStatusChange(Request $request)
    {
        $currency = Currency::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $currency->status = 1;
            } else {
                $currency->status = 0;
            }
            $currency->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencySort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Currency::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function currencyDelete($id)
    {
        try {
            Currency::findOrFail($id)->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Currency::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Currency has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Currency::whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Currency status has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleRateUpdate(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            $currencies = Currency::select(['id', 'code', 'rate'])->whereIn('id', $request->strIds)->get();
            $currencyCodes = implode(',', $currencies->pluck('code')->toArray());

            $response = $this->fiatRateUpdate(basicControl()->base_currency, $currencyCodes);

            if ($response['status']) {
                foreach ($response['res'] as $key => $apiRes) {
                    $apiCode = substr($key, -3);
                    $matchingCurrencies = $currencies->where('code', $apiCode);

                    if ($matchingCurrencies->isNotEmpty()) {
                        $matchingCurrencies->each(function ($currency) use ($apiRes) {
                            $currency->update([
                                'rate' => $apiRes,
                            ]);
                        });
                    }
                }
            } else {
                session()->flash('error', $response['res']);
            }

            session()->flash('success', 'Rate Updated successfully');
            return response()->json(['success' => 1]);
        }
    }
}
PK     x\uCA  CA  )  Http/Controllers/Admin/PageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\ManageMenu;
use App\Models\Page;
use App\Rules\AlphaDashWithoutSlashes;
use App\Traits\Upload;
use Http\Client\Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use MatthiasMullie\Minify\JS;

class PageController extends Controller
{
    use Upload;

    public function index()
    {
        $theme = basicControl()->theme;
        $data['allTemplate'] = getThemesNames();
        abort_if(!in_array($theme, getThemesNames()), 404);
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->orderBy('default_status', 'desc')->get();
        $defaultLanguage = Language::where('default_status', true)->first();
        $data['allPages'] = Page::with(['details' => function ($query) use ($defaultLanguage) {
            $query->where('language_id', $defaultLanguage->id);
        }])->whereNull('custom_link')->where('template_name', $theme)->get();
        return view("admin.frontend_management.page.index", $data, compact("theme", 'defaultLanguage'));
    }

    public function create($theme)
    {
        abort_if(!in_array($theme, getThemesNames()), 404);
        $data['url'] = url('/') . "/";
        $data["sections"] = getPageSections();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        return view("admin.frontend_management.page.create", $data, compact('theme'));
    }

    public function store(Request $request, $theme)
    {

        $request->validate([
            'name' => 'required|string|min:3|max:100',
            'slug' => [
                'required',
                'min:1',
                'max:100',
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')->where(function ($query) use ($theme) {
                    return $query->where('template_name', $theme);
                }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
            'page_content' => 'required|string|min:3',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',

        ]);

        if ($request->hasFile('breadcrumb_image')) {
            $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pageImage.path'), null, null, 'webp', 60);
            if ($image) {
                $breadCrumbImage = $image['path'];
                $breadCrumbImageDriver = $image['driver'];
            }
        }

        $sections = preg_match_all('/\[\[([^\]]+)\]\]/', strtolower($request->page_content), $matches) ? $matches[1] : null;

        try {
            $response = Page::create([
                "name" => strtolower($request->name),
                "slug" => $request->slug,
                "template_name" => $theme,
                "breadcrumb_image" => $breadCrumbImage ?? null,
                "breadcrumb_image_driver" => $breadCrumbImageDriver ?? 'local',
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
                "type" => 0
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $response->details()->create([
                "name" => $request->name,
                'language_id' => $request->language_id,
                'content' => $request->page_content,
                'sections' => $sections,
            ]);

            return redirect()->route('admin.page.index', $theme)->with('success', 'Page Saved Successfully');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function edit($id, $theme, $language = null)
    {
        abort_if(!in_array($theme, getThemesNames()), 404);
        $page = Page::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])->where('template_name', $theme)->where('id', $id)->first();

        $data["sections"] = getPageSections();
        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view("admin.frontend_management.page.edit", $data, compact('page', 'language', 'theme'));
    }

    public function update(Request $request, $id, $theme)
    {
        if ($request->status == 0) {
            $menu = $request->name;
            $menuHeader = ManageMenu::where('menu_section', 'header')->first();
            $nestedArr = $menuHeader->menu_items;
            removeValue($nestedArr, strtolower($menu));
            $menuHeader->menu_items = $nestedArr;
            $menuHeader->save();


            $menuFooter = ManageMenu::where('menu_section', 'footer')->first();

            $nestedArr2 = $menuFooter->menu_items;
            removeValue($nestedArr2, strtolower($menu));
            $menuHeader->menu_items = $nestedArr2;
            $menuHeader->save();
        }
        $request->validate([
            'name' => ['required', 'string', 'min:1', 'max:100',
                Rule::unique('page_details', 'page_id')->ignore($id),
            ],
            'slug' => [
                'required',
                'min:1',
                'max:100',
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')
                    ->ignore($id)
                    ->where(function ($query) use ($theme) {
                        return $query->where('template_name', $theme);
                    }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
            'page_content' => 'required|string|min:3',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'sometimes|required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',
        ]);

        try {
            $page = Page::findOrFail($id);
            $sections = preg_match_all('/\[\[([^\]]+)\]\]/', strtolower($request->page_content), $matches) ? $matches[1] : null;

            if ($request->hasFile('breadcrumb_image')) {
                $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pagesImage.path'), null, null, 'webp', 80, $page->breadcrumb_image, $page->breadcrumb_image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
                $breadCrumbImage = $image['path'];
                $breadCrumbImageDriver = $image['driver'] ?? 'local';
            }

            $response = $page->update([
                "slug" => $request->slug,
                "template_name" => $theme,
                "breadcrumb_image" => $breadCrumbImage ?? $page->breadcrumb_image,
                "breadcrumb_image_driver" => $breadCrumbImageDriver ?? $page->breadcrumb_image_driver,
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $page->details()->updateOrCreate([
                'language_id' => $request->language_id,
            ],
                [
                    "name" => $request->name,
                    'content' => $request->page_content,
                    'sections' => $sections,
                ]
            );

            return redirect()->route('admin.page.index', $theme)->with('success', 'Page Updated Successfully');

        } catch (Exception $e) {
            if (isset($breadCrumbImage, $breadCrumbImageDriver))
                $this->fileDelete($breadCrumbImageDriver, $breadCrumbImage);
            return back()->with('error', $e->getMessage());
        }

    }

    public function delete(Request $request, $id)
    {
        try {
            $page = Page::where('id', $id)->firstOr(function () {
                throw new \Exception('Something went wrong, Please try again');
            });


            $headerMenu = ManageMenu::where('menu_section', 'header')->first();
            $footerMenu = ManageMenu::where('menu_section', 'footer')->first();
            $lookingKey = $page->name;
            $headerMenu->update([
                'menu_items' => filterCustomLinkRecursive($headerMenu->menu_items, $lookingKey)
            ]);
            $footerMenu->update([
                'menu_items' => filterCustomLinkRecursive($footerMenu->menu_items, $lookingKey)
            ]);
            $this->fileDelete($page->meta_image_driver, $page->meta_image);
            $page->delete();
            $page->details()->delete();

            return back()->with('success', 'Page deleted successfully');

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function editStaticPage($id, $theme, $language = null)
    {
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['page'] = Page::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])->where('id', $id)->first();

        return view("admin.frontend_management.page.edit_static", $data);
    }

    public function updateStaticPage(Request $request, $id, $theme)
    {

        $request->validate([
            'name' => ['required', 'string', 'min:1', 'max:100',
                Rule::unique('page_details', 'page_id')->ignore($id),
            ],
            'language_id' => 'required|integer|exists:languages,id',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'sometimes|required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',
        ]);

        try {

            $page = Page::findOrFail($id);

            if ($request->hasFile('breadcrumb_image')) {
                $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pagesImage.path'), null, null, 'webp', 80, $page->breadcrumb_image, $page->breadcrumb_image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
            }

            $response = $page->update([
                "breadcrumb_image" => $image['path'] ?? $page->breadcrumb_image,
                "breadcrumb_image_driver" => $image['driver'] ?? $page->breadcrumb_image_driver,
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $page->details()->updateOrCreate([
                'language_id' => $request->language_id,
            ],
                [
                    "name" => $request->name,
                ]
            );
            return redirect()->route('admin.page.index', $theme)->with('success', 'Static Page Updated Successfully');
        } catch (Exception $e) {
            if (isset($image['path'], $image['driver']))
                $this->fileDelete($image['driver'], $image['path']);
            return back()->with('error', $e->getMessage());
        }
    }

    public function updateSlug(Request $request)
    {
        $theme = basicControl()->theme;
        $rules = [
            "pageId" => "required|exists:pages,id",
            "newSlug" => [
                "required",
                "min:1",
                "max:100",
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')
                    ->ignore($request->pageId)
                    ->where(function ($query) use ($theme) {
                        return $query->where('template_name', $theme);
                    }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()]);
        }

        $pageId = $request->pageId;
        $newSlug = $request->newSlug;
        $page = Page::find($pageId);

        if (!$page) {
            return back()->with("error", "Page not found");
        }

        $page->update([
            'slug' => $newSlug
        ]);

        return response([
            'success' => true,
            'slug' => $page->slug
        ]);
    }

    public function pageSEO($id)
    {;
        try {
            $data['page'] = Page::where('id', $id)
                ->select('id', 'name', 'page_title', 'meta_title', 'meta_keywords', 'meta_description', 'og_description', 'meta_robots', 'meta_image', 'meta_image_driver')
                ->firstOr(function () {
                    throw new \Exception('Page is not available.');
                });
            return view("admin.frontend_management.page.seo", $data);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function pageSeoUpdate(Request $request, $id)
    {
        $request->validate([
            'page_title' => 'required|string|min:3|max:100',
            'meta_title' => 'nullable|string|min:3|max:191',
            'meta_keywords' => 'nullable|array',
            'meta_keywords.*' => 'nullable|string|min:1|max:255',
            'meta_description' => 'nullable|string|min:1|max:500',
            'og_description' => 'nullable|string|min:1|max:500',
            'meta_robots' => 'nullable|array',
            'meta_robots.*' => 'nullable|string|min:1|max:255',
            'meta_image' => 'nullable|mimes:jpeg,png,jpeg|max:10240'
        ]);

        try {
            $page = Page::where('id', $id)
                ->select('id', 'name', 'page_title', 'meta_title', 'meta_keywords', 'meta_description', 'og_description', 'meta_robots', 'meta_image', 'meta_image_driver')
                ->firstOr(function () {
                    throw new \Exception('Page is not available.');
                });

            if ($request->hasFile('meta_image')) {
                $metaImage = $this->fileUpload($request->meta_image, config('filelocation.seo.path'), null, null, 'webp', 60, $page->meta_image, $page->meta_image_driver);
                throw_if(empty($metaImage['path']), 'Image path not found');
            }

            if ($request->meta_robots) {
                $meta_robots = implode(",", $request->meta_robots);
            }
            $response = $page->update([
                'page_title' => $request->page_title,
                'meta_title' => $request->meta_title,
                'meta_keywords' => $request->meta_keywords,
                'meta_description' => $request->meta_description,
                'og_description' => $request->og_description,
                'meta_robots' => $meta_robots ?? null,
                'meta_image' => $metaImage['path'] ?? $page->meta_image,
                'meta_image_driver' => $metaImage['driver'] ?? $page->meta_image_driver,
            ]);
            throw_if(!$response, 'Something went wrong, While updating insert data.');
            return back()->with('success', 'Page Seo has been updated.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     x\k[=    /  Http/Controllers/Admin/ManageMenuController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\ManageMenu;
use App\Models\Page;
use App\Models\PageDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ManageMenuController extends Controller
{
    public function manageMenu()
    {
        $theme = basicControl()->theme ?? 'dark';
        $defaultLanguage = Language::where('default_status', true)->first();
        $data['pages'] = Page::with(['details' => function ($query) use ($defaultLanguage) {
            $query->where('language_id', $defaultLanguage->id);
        }])->where('template_name', $theme)->get();

        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['headerMenus'] = ManageMenu::where('menu_section', 'header')->where('theme', $theme)->firstOrFail();
        $data['footerMenus'] = ManageMenu::where('menu_section', 'footer')->where('theme', $theme)->firstOrFail();
        return view('admin.frontend_management.manage-menu', $data);
    }

    public function headerMenuItemStore(Request $request)
    {
        $request->validate([
            'menu_item' => 'nullable|array',
        ]);

        try {
            $menu = ManageMenu::where('menu_section', 'header')->where('theme', basicControl()->theme)->firstOrFail();

            $response = $menu->update([
                'menu_items' => $request->menu_item
            ]);

            if (!$response) {
                throw new \Exception('Something went something, Please try again');
            }
            return back()->with('success', 'Header menu saved successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function footerMenuItemStore(Request $request)
    {
        $request->validate([
            'menu_item' => 'nullable|array',
        ]);
        try {
            $menu = ManageMenu::where('menu_section', 'footer')->where('theme', basicControl()->theme)->firstOrFail();

            $response = $menu->update([
                'menu_items' => $request->menu_item
            ]);

            if (!$response) {
                throw new \Exception('Something went something, Please try again');
            }
            return back()->with('success', 'Footer menu saved successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function addCustomLink(Request $request)
    {
        $rules = [
            'link_text' => 'required|string|min:2|max:100',
            'link' => 'required|url',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            $addError = $validator->getMessageBag();
            $addError->add('errorMessage', 1);
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $pageForMenu = Page::create([
                'name' => strtolower($request->link_text),
                'slug' => null,
                'template_name' => basicControl()->theme,
                'home_name' => slug($request->link_text),
                'custom_link' => $request->link,
                'type' => 3
            ]);

            if (!$pageForMenu) {
                return back()->with('error', 'Something went wrong, when storing custom link data');
            }

            $defaultLanguage = Language::where('default_status', true)->first();
            $pageForMenu->details()->create([
                'language_id' => $defaultLanguage->id,
                'name' => $request->link_text,
            ]);

            return back()->with('success', 'Custom link added to the menu.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


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

        $rules = [
            'language_id' => 'required',
            'link_text.*' => 'required|max:100',
            'link.*' => 'required|max:100',
        ];

        $message = [
            'link_text.*.required' => 'This link text field is required.',
            'link.*.required' => 'This link field is required.',
        ];

        $language = $request->language_id;
        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, $rules, $message);

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        try {
            $customPage = Page::where('template_name', basicControl()->theme)->findOrFail($id);
            $response = $customPage->update([
                'custom_link' => $request->link[$language]
            ]);

            throw_if(!$response, 'Something went wrong while updating custom menu data.');

            if ($language != 0) {
                $pageDetails = PageDetail::updateOrCreate(
                    ['page_id' => $id, 'language_id' => $language],
                    ['page_id' => $id, 'language_id' => $language, 'name' => $request->link_text[$language]]
                );
            }
            throw_if(!$pageDetails, 'Something went wrong while updating custom menu data.');

            return back()->with('success', 'Custom menu updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function deleteCustomLink(Request $request, $pageId)
    {
        $customPage = Page::where('template_name', basicControl()->theme)->findOrFail($pageId);

        $headerMenu = ManageMenu::where('menu_section', 'header')->where('theme', basicControl()->theme)->first();
        $footerMenu = ManageMenu::where('menu_section', 'footer')->where('theme', basicControl()->theme)->first();

        $lookingKey = $customPage->name;

        $headerMenu->update([
            'menu_items' => filterCustomLinkRecursive($headerMenu->menu_items, $lookingKey)
        ]);

        $footerMenu->update([
            'menu_items' => filterCustomLinkRecursive($footerMenu->menu_items, $lookingKey)
        ]);

        $customPage->delete();
        return back()->with('success', 'Custom link deleted from the menu.');
    }

    public function getCustomLinkData(Request $request)
    {
        $pageId = $request->pageId;
        $languageId = $request->languageId;

        $customPage = PageDetail::with('page:id,name,custom_link')
            ->where('page_id', $pageId)
            ->where('language_id', $languageId)
            ->first();

        return response()->json([
            'name' => $customPage ? $customPage->name : '',
            'custom_link' => $customPage ? optional($customPage->page)->custom_link : ''
        ]);
    }
}
PK     x\c     4  Http/Controllers/Admin/MaintenanceModeController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MaintenanceMode;
use Illuminate\Http\Request;
use App\Traits\Upload;


class MaintenanceModeController extends Controller
{
    use Upload;

    public function index()
    {
        $data['basicControl'] = basicControl();
        $data['maintenanceMode'] = MaintenanceMode::firstOrFail();
        return view("admin.control_panel.maintenance_mode", $data);
    }

    public function maintenanceModeUpdate(Request $request)
    {

        $request->validate([
            "heading" => "required|string|min:3",
            "description" => "required|string|min:3",
            "is_maintenance_mode" => "nullable|integer|in:0,1",
            "image" => "sometimes|required|mimes:jpg,png,jpeg,gif,svg",
        ]);

        try {
            $maintenanceMode = MaintenanceMode::firstOrCreate();

            if ($request->hasFile('image')) {
                $image = $this->fileUpload($request->image, config('filelocation.maintenanceMode.path'), null, null,'webp', 60,$maintenanceMode->image,$maintenanceMode->image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
                $image = $image['path'];
                $imageDriver = $image['driver'] ?? 'local';
            }

            $maintenanceMode->update([
                'heading' => $request->heading,
                'description' => $request->description,
                'image' => $image ?? $maintenanceMode->image,
                'image_driver' => $imageDriver ?? $maintenanceMode->image_driver,
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                'is_maintenance_mode' => $request->is_maintenance_mode
            ]);

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', "Maintenance Mode updated successfully");

    }
}
PK     x\Y1  1  .  Http/Controllers/Admin/PayoutLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Transaction;
use App\Traits\Notify;
use Carbon\Carbon;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Yajra\DataTables\Facades\DataTables;

class PayoutLogController extends Controller
{
    use Notify;

    public function index()
    {
        $payoutRecord = \Cache::get('payoutRecord');
        if (!$payoutRecord) {
            $payoutRecord = Payout::selectRaw('COUNT(id) AS totalWithdrawLog')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS pendingWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS pendingWithdrawPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS successWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS successWithdrawPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS cancelWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS cancelWithdrawPercentage')
                ->get()
                ->toArray();
            \Cache::put('payoutRecord', $payoutRecord);
        }

        $data['methods'] = PayoutMethod::where('is_active', 1)->orderBy('id', 'asc')->get();
        return view('admin.payout.logs', $data, compact('payoutRecord'));
    }

    public function search(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'];

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $payout = Payout::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'method:id,name,logo,driver'])
            ->whereHas('user')
            ->whereHas('method')
            ->orderBy('id', 'desc')
            ->where('status', '!=', 0)
            ->orderBy('id', 'desc')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('trx_id', 'LIKE', $search)
                    ->orWhereHas('user', function ($q) use ($search) {
                        $q->where('email', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('method', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });

        return DataTables::of($payout)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route("admin.user.edit", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {

                return '<a class="d-flex align-items-center me-2 cursor-unset" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->method)->name . '</h5>
                                </div>
                              </a>';
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payout_currency_code . "</h6>";

            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . getAmount($item->charge) . ' ' . $item->payout_currency_code . "</span>";
            })
            ->addColumn('net amount', function ($item) {
                return "<h6>" . currencyPosition(getAmount($item->amount_in_base_currency)) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), @$v->field_value ?? $v->field_name),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                $icon = $item->status == 1 ? 'pencil' : 'eye';

                $statusColor = '';
                $statusText = '';
                if ($item->status == 0) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 1) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 2) {
                    $statusColor = 'badge bg-soft-success text-success';
                    $statusText = 'Success';
                } else if ($item->status == 3) {
                    $statusColor = 'badge bg-soft-danger text-danger';
                    $statusText = 'Cancel';
                }

                return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-id='$item->id'
                data-info='" . json_encode($details) . "'
                data-userid='" . optional($item->user)->id . "'
                data-sendername='" . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . "'
                data-transactionid='$item->trx_id'
                data-feedback='$item->feedback'
                data-amount=' " . getAmount($item->amount) . ' ' . $item->payout_currency_code . "'
                data-method='" . optional($item->method)->name . "'
                data-gatewayimage='" . getFile(optional($item->method)->driver, optional($item->method)->logo) . "'
                data-datepaid='" . dateTime($item->created_at, 'd M Y') . "'
                data-status='$item->status'
                data-status_color='$statusColor'
                data-status_text='$statusText'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payout.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
            })
            ->rawColumns(['name', 'amount', 'charge', 'method', 'net amount', 'status', 'action'])
            ->make(true);

    }


    public function action(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
            'status' => ['required', Rule::in(['2', '3'])],
        ]);
        $payout = Payout::where('id', $request->id)->whereIn('status', [1])->with('user', 'method')->firstOrFail();


        if ($request->status == 3) {
            $payout->feedback = $request->feedback;
            $payout->save();
            BasicService::preparePayoutFail($payout);
            return back()->with('success', "Payment Rejected.");
        }

        if (optional($payout->payoutMethod)->is_automatic == 1) {
            $methodObj = 'App\\Services\\Payout\\' . optional($payout->payoutMethod)->code . '\\Card';
            $data = $methodObj::payouts($payout);

            if (!$data) {
                return back()->with('error', 'Method not available or unknown errors occur');
            }

            if ($data['status'] == 'error') {
                BasicService::preparePayoutFail($payout);
                return back()->with('error', $data['data']);
            }
        }

        if (optional($payout->payoutMethod)->is_automatic == 0) {
            $payout->feedback = $request->feedback;
            $payout->save();
            BasicService::preparePayoutComplete($payout);

        } else {
            if (optional($payout->payoutMethod)->code == 'coinbase' || optional($payout->payoutMethod)->code == 'perfectmoney') {
                $payout->feedback = $request->feedback;
                $payout->save();
                BasicService::preparePayoutComplete($payout);
            } else {
                $payout->feedback = $request->feedback;
                $payout->response_id = $data['response_id'];
                $payout->save();
            }
        }

        return back()->with('success', 'Payment Confirmed');
    }
}
PK     x\>:  :  .  Http/Controllers/Admin/DashboardController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\SupportTicket;
use App\Models\Transaction;
use App\Models\User;
use App\Models\UserKyc;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Traits\Upload;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class DashboardController extends Controller
{
    use Upload, Notify;

    public function index()
    {
        $data['firebaseNotify'] = config('firebase');
        $data['latestUser'] = User::latest()->limit(5)->get();
        $statistics['schedule'] = $this->dayList();
        return view('admin.dashboard-alternative', $data, compact("statistics"));
    }

    public function monthlyDepositWithdraw(Request $request)
    {
        $keyDataset = $request->keyDataset;

        $dailyTransaction = $this->dayList();

        Transaction::when($keyDataset == '0', function ($query) {
            $query->whereMonth('created_at', Carbon::now()->month);
        })
            ->when($keyDataset == '1', function ($query) {
                $lastMonth = Carbon::now()->subMonth();
                $query->whereMonth('created_at', $lastMonth->month);
            })
            ->select(
                DB::raw('SUM(amount_in_base) as totalTransaction'),
                DB::raw('DATE_FORMAT(created_at,"Day %d") as date')
            )
            ->groupBy(DB::raw("DATE(created_at)"))
            ->get()->map(function ($item) use ($dailyTransaction) {
                $dailyTransaction->put($item['date'], $item['totalTransaction']);
            });

        return response()->json([
            "totalTransaction" => currencyPosition($dailyTransaction->sum()),
            "dailyTransaction" => $dailyTransaction,
        ]);
    }

    public function saveToken(Request $request)
    {
        $admin = Auth::guard('admin')->user()
            ->fireBaseToken()
            ->create([
                'token' => $request->token,
            ]);
        return response()->json([
            'msg' => 'token saved successfully.',
        ]);
    }


    public function dayList()
    {
        $totalDays = Carbon::now()->endOfMonth()->format('d');
        $daysByMonth = [];
        for ($i = 1; $i <= $totalDays; $i++) {
            array_push($daysByMonth, ['Day ' . sprintf("%02d", $i) => 0]);
        }

        return collect($daysByMonth)->collapse();
    }

    protected function followupGrap($todaysRecords, $lastDayRecords = 0)
    {

        if (0 < $lastDayRecords) {
            $percentageIncrease = (($todaysRecords - $lastDayRecords) / $lastDayRecords) * 100;
        } else {
            $percentageIncrease = 0;
        }
        if ($percentageIncrease > 0) {
            $class = "bg-soft-success text-success";
        } elseif ($percentageIncrease < 0) {
            $class = "bg-soft-danger text-danger";
        } else {
            $class = "bg-soft-secondary text-body";
        }

        return [
            'class' => $class,
            'percentage' => round($percentageIncrease, 2)
        ];
    }


    public function chartUserRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $userRecord = collect(User::selectRaw('COUNT(id) AS totalUsers')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateUserCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateUserCount')
            ->get()->makeHidden(['last-seen-activity', 'fullname'])
            ->toArray())->collapse();
        $followupGrap = $this->followupGrap($userRecord['currentDateUserCount'], $userRecord['previousDateUserCount']);

        $userRecord->put('followupGrapClass', $followupGrap['class']);
        $userRecord->put('followupGrap', $followupGrap['percentage']);

        $current_month_data = DB::table('users')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $userRecord['chartPercentageIncDec'] = fractionNumber($userRecord['totalUsers'] - $userRecord['currentDateUserCount'], false);
        return response()->json(['userRecord' => $userRecord, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartTicketRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $ticketRecord = collect(SupportTicket::selectRaw('COUNT(id) AS totalTickets')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateTicketsCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateTicketsCount')
            ->selectRaw('count(CASE WHEN status = 2  THEN status END) AS replied')
            ->selectRaw('count(CASE WHEN status = 1  THEN status END) AS answered')
            ->selectRaw('count(CASE WHEN status = 0  THEN status END) AS pending')
            ->get()
            ->toArray())->collapse();

        $followupGrap = $this->followupGrap($ticketRecord['currentDateTicketsCount'], $ticketRecord['previousDateTicketsCount']);
        $ticketRecord->put('followupGrapClass', $followupGrap['class']);
        $ticketRecord->put('followupGrap', $followupGrap['percentage']);

        $current_month_data = DB::table('support_tickets')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $ticketRecord['chartPercentageIncDec'] = fractionNumber($ticketRecord['totalTickets'] - $ticketRecord['currentDateTicketsCount'], false);
        return response()->json(['ticketRecord' => $ticketRecord, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartOrderRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $orderRecords = collect(Order::payment()->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateOrderCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateOrderCount')
            ->get()
            ->toArray())->collapse();
        $followupGrap = $this->followupGrap($orderRecords['currentDateOrderCount'], $orderRecords['previousDateOrderCount']);
        $orderRecords->put('followupGrapClass', $followupGrap['class']);
        $orderRecords->put('followupGrap', $followupGrap['percentage']);


        $current_month_data = DB::table('orders')->where('payment_status', 1)
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $orderRecords['chartPercentageIncDec'] = fractionNumber($orderRecords['totalOrder'] - $orderRecords['currentDateOrderCount'], false);
        return response()->json(['orderRecord' => $orderRecords, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartTransactionRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');

        $transaction = collect(Transaction::selectRaw('COUNT(id) AS totalTransaction')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateTransactionCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateTransactionCount')
            ->whereRaw('YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) = MONTH(NOW())')
            ->get()
            ->toArray())
            ->collapse();

        $followupGrap = $this->followupGrap($transaction['currentDateTransactionCount'], $transaction['previousDateTransactionCount']);
        $transaction->put('followupGrapClass', $followupGrap['class']);
        $transaction->put('followupGrap', $followupGrap['percentage']);


        $current_month_data = DB::table('transactions')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $transaction['chartPercentageIncDec'] = fractionNumber($transaction['totalTransaction'] - $transaction['currentDateTransactionCount'], false);
        return response()->json(['transactionRecord' => $transaction, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }


    public function chartLoginHistory()
    {
        $userLoginsData = DB::table('user_logins')
            ->whereDate('created_at', '>=', now()->subDays(30))
            ->select('browser', 'os', 'get_device')
            ->get();

        $userLoginsBrowserData = $userLoginsData->groupBy('browser')->map->count();
        $data['browserKeys'] = $userLoginsBrowserData->keys();
        $data['browserValue'] = $userLoginsBrowserData->values();

        $userLoginsOSData = $userLoginsData->groupBy('os')->map->count();
        $data['osKeys'] = $userLoginsOSData->keys();
        $data['osValue'] = $userLoginsOSData->values();

        $userLoginsDeviceData = $userLoginsData->groupBy('get_device')->map->count();
        $data['deviceKeys'] = $userLoginsDeviceData->keys();
        $data['deviceValue'] = $userLoginsDeviceData->values();

        return response()->json(['loginPerformance' => $data]);
    }

    public function chartTopUpOrderRecords()
    {
        $currentTime = Carbon::now();
        $data['topUpOrderToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'topup')[0] ?? null;
        $data['topUpOrderYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'topup')[0] ?? null;
        $data['totalTopUpOrder'] = Order::payment()->type('topup')->count();
        return response()->json(['topUpOrderRecord' => $data]);
    }

    public function chartCardOrderRecords()
    {
        $currentTime = Carbon::now();
        $data['cardOrderToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'card')[0] ?? null;
        $data['cardOrderYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'card')[0] ?? null;
        $data['totalCardOrder'] = Order::payment()->type('card')->count();
        return response()->json(['cardOrderRecord' => $data]);
    }

    public function chartAddFundRecords()
    {
        $currentTime = Carbon::now();
        $data['cardAddFundToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'fund')[0] ?? null;
        $data['cardAddFundYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'fund')[0] ?? null;
        $data['totalAddFund'] = Deposit::where('status', 1)->where('payment_method_id', '!=', '-1')->sum('amount_in_base');
        $data['currencySymbol'] = basicControl()->currency_symbol;
        return response()->json(['addFundRecord' => $data]);
    }

    public function chartOrderMovement()
    {
        $orderRecords = DB::table('orders')
            ->where('payment_status', 1)
            ->selectRaw('
        MONTH(created_at) as month,
        COUNT(CASE WHEN order_for = "topup" THEN 1 END) AS topUpOrder,
        COUNT(CASE WHEN order_for = "card" THEN 1 END) AS cardOrder
    ')
            ->whereYear('created_at', date('Y'))  // Optional: Filter by current year
            ->groupBy(DB::raw('MONTH(created_at)'))
            ->orderBy(DB::raw('MONTH(created_at)'))
            ->get();


        // Initialize monthly data arrays with zeros
        $monthlyData = [
            'topUp' => array_fill(0, 12, 0),
            'card' => array_fill(0, 12, 0),
        ];

        foreach ($orderRecords as $record) {
            $monthIndex = $record->month - 1; // Adjust month to zero-based index for JavaScript
            $monthlyData['topUp'][$monthIndex] = $record->topUpOrder;
            $monthlyData['card'][$monthIndex] = $record->cardOrder;
        }

        return response()->json([
            'orderFigures' => [
                'horizontalBarChatInbox' => $monthlyData
            ]
        ]);
    }

    function getDataForTimeRange($start, $end, $type)
    {
        $hours = [];
        $counts = [];

        for ($i = 0; $i < 24; $i++) {
            if ($i % 2 == 0) {
                $hour = $start->copy()->subHours($i + 1);
                $formattedHour = $hour->format('hA');
                $hours[] = $formattedHour;

                if ($type == 'topup' || $type == 'card') {
                    $count = DB::table('orders')
                        ->where('payment_status', 1)
                        ->where('order_for', $type)
                        ->where('updated_at', '>=', $hour)
                        ->where('updated_at', '<', $hour->copy()->addHours(2))
                        ->count();
                } elseif ($type == 'fund') {
                    $count = DB::table('deposits')
                        ->where('status', 1)
                        ->where('payment_method_id', '!=', '-1')
                        ->where('updated_at', '>=', $hour)
                        ->where('updated_at', '<', $hour->copy()->addHours(2))
                        ->count();
                }
                $counts[] = $count;
            }
        }
        $hours = array_reverse($hours);
        $counts = array_reverse($counts);

        $data[] = [
            'hours' => $hours,
            'counts' => $counts,
        ];
        return $data;
    }

}
PK     x\db[H+  H+  2  Http/Controllers/Admin/ManualGatewayController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Gateway;
use App\Traits\Upload;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Exception;

class ManualGatewayController extends Controller
{
    use Upload;

    public function index()
    {
        $data['methods'] = Gateway::manual()->orderBy('sort_by', 'asc')->get();
        return view('admin.payment_methods.manual.list', $data);
    }

    public function create()
    {
        $data['basicControl'] = basicControl();
        return view('admin.payment_methods.manual.create', $data);
    }

    public function store(Request $request)
    {

        $rules = [
            'name' => "required|min:3",
            'description' => 'required|string|min:3',
            'note' => 'required|string|min:3',
            'manual_gateway_status' => "nullable|integer|in:0,1",
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.currency' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'required|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'note.required' => 'The payment description field is required.',
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'receivable_currencies.*.currency.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $input_form = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $input_form[$arr['field_name']] = $arr;
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 60);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('alert', 'Image could not be uploaded.');
            }
        }

        $request->validate($rules, $customMessages);

        $collection = collect($request->receivable_currencies);
        $supportedCurrency = $collection->pluck('currency')->all();
        $response = Gateway::create([
            'name' => $request->name,
            'code' => Str::slug($request->name),
            'supported_currency' => $supportedCurrency,
            'receivable_currencies' => $request->receivable_currencies,
            'parameters' => $input_form,
            'image' => $gatewayImage ?? null,
            'driver' => $driver ?? null,
            'status' => $request->status,
            'note' => $request->note,
            'description' => $request->description
        ]);

        if (!$response) {
            throw new \Exception('Unexpected error! Please try again.');
        }

        return back()->with('success', 'Gateway data has been add successfully.');

    }

    public function edit($id)
    {
        $data['basicControl'] = basicControl();
        $data['method'] = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception("Invalid Gateways Request");
        });
        return view('admin.payment_methods.manual.edit', $data);
    }


    public function update(Request $request, $id)
    {
        $rules = [
            'name' => "required|min:3|unique:gateways,name," . $id,
            'description' => 'required|string|min:3',
            'note' => 'required|string|min:3',
            'manual_gateway_status' => "nullable|integer|in:0,1",
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.currency' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'note.required' => 'The payment description field is required.',
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'receivable_currencies.*.currency.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $gateway = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception("Invalid Gateways Request");
        });

        if (1000 > $gateway->id) {
            return back()->with('error', 'Invalid Gateways Request');
        }


        $input_form = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $input_form[$arr['field_name']] = $arr;
            }
        }

        $request->validate($rules, $customMessages);

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 60, $gateway->image, $gateway->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('alert', 'Image could not be uploaded.');
            }
        }

        $collection = collect($request->receivable_currencies);
        $supportedCurrency = $collection->pluck('currency')->all();

        $response = $gateway->update([
            'name' => $request->name,
            'supported_currency' => $supportedCurrency,
            'receivable_currencies' => $request->receivable_currencies,
            'parameters' => $input_form,
            'image' => $gatewayImage ?? $gateway->image,
            'driver' => $driver ?? $gateway->driver,
            'status' => $request->manual_gateway_status,
            'note' => $request->note,
            'description' => $request->description
        ]);

        if (!$response) {
            throw new Exception('Unexpected error! Please try again.');
        }

        return back()->with('success', 'Gateway data has been updated.');

    }

}
PK     x\N    1  Http/Controllers/Admin/BlogCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class BlogCategoryController extends Controller
{
    public function index()
    {
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->paginate(10);
        return view('admin.blog_category.list', $data);
    }

    public function create()
    {
        return view('admin.blog_category.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);
        try {
            $response = BlogCategory::create([
                'name' => $request->name,
                'slug' => Str::slug($request->name)
            ]);
            throw_if(!$response, 'Something went wrong while storing blog category data. Please try again later.');
            return back()->with('success', 'Blog category save successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit(string $id)
    {
        try {
            $data['blogCategory'] = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });
            return view('admin.blog_category.edit', $data);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => 'required',
        ]);
        try {
            $blogCategory = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });

            $response = $blogCategory->update([
                'name' => $request->name,
                'slug' => Str::slug($request->name)
            ]);
            throw_if(!$response, 'Something went wrong while storing blog category data. Please try again later.');
            return back()->with('success', 'Blog category save successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $blogCategory = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });
            $blogCategory->delete();
            return redirect()->back()->with('success', 'Blog category deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
    public function status($id){

        try {
            $blogCategory = BlogCategory::select('id', 'status')
                ->where('id', $id)
                ->firstOr(function () {
                    throw new \Exception('Blog Category not found.');
                });

            $blogCategory->status = ($blogCategory->status == 1) ? 0 : 1;
            $blogCategory->save();

            return back()->with('success','Blog Category Status Changed Successfully.');
        }catch (\Exception $e){
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     x\pUk<  k<  9  Http/Controllers/Admin/NotificationTemplateController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\NotificationTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Facades\App\Services\BasicService;

class NotificationTemplateController extends Controller
{

    public function defaultTemplate(Request $request)
    {
        $basicControl = basicControl();
        if ($request->isMethod('get')) {
            return view('admin.notification_templates.email_template.default', ['basicControl' => $basicControl]);
        } elseif ($request->isMethod('post')) {

            $request->validate([
                'sender_email' => 'required|email:rfc,dns',
                'sender_email_name' => 'required|string|max:100',
                'email_description' => 'required|string',
            ]);

            try {
                $basicControl->update([
                    'sender_email' => $request->sender_email,
                    'sender_email_name' => $request->sender_email_name,
                    'email_description' => $request->email_description
                ]);

                $env = [
                    'MAIL_FROM_ADDRESS' => $request->sender_email,
                    'MAIL_FROM_NAME' => '"' . $request->sender_email_name . '"'
                ];

                BasicService::setEnv($env);
                return back()->with('success', 'Default email template updated successfully.');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function emailTemplates()
    {
        $emailTemplates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');
        return view('admin.notification_templates.email_template.index', ['emailTemplates' => $emailTemplates]);
    }

    public function editEmailTemplate($id)
    {
        try {
            $data['languages'] = Language::select('id', 'name')->get();
            $data["template"] = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Email template is not available.');
            });

            $templateKey = $data["template"]->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.email_template.edit', $data, compact('templates'));

        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function updateEmailTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'subject.*' => 'required|string|max:200',
            'email_from.*' => 'required|string|max:100',
            'email_template.*' => 'required|string',
            'mail_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'subject.*.required' => 'The subject field is required.',
            'email_from.*.required' => 'The email from field is required.',
            'email_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Email template is not available.');
            });

            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'mail') {
                        $status[$key] = $request->mail_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
                'template_key' => $template->template_key,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'subject' => $request->subject[$language->id] ?? null,
                'email_from' => $request->email_from[$language->id] ?? null,
                'short_keys' => $template->short_keys,
                'email' => strip_tags($request->email_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name ?? null
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'Email template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }


    public function smsTemplates()
    {
        $smsTemplates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');
        return view('admin.notification_templates.sms_template.index', compact('smsTemplates'));
    }

    public function editSmsTemplate($id)
    {
        try {
            $data['languages'] = Language::select('id', 'name')->get();
            $data['template'] = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('SMS template is not available.');
            });

            $templateKey = $data['template']->template_key;
            $data['templates'] = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.sms_template.edit', $data);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updateSmsTemplate(Request $request, $id, $language_id)
    {

        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'sms_template.*' => 'required|string',
            'sms_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'sms_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });

            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'sms') {
                        $status[$key] = $request->sms_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'sms' => strip_tags($request->sms_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'SMS template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage())->withInput($request->all());
        }
    }


    public function inAppNotificationTemplates()
    {
        $templates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');;
        return view('admin.notification_templates.in_app_notification_template.index', compact('templates'));
    }

    public function editInAppNotificationTemplate($id)
    {
        try {
            $languages = Language::select('id', 'name')->get();
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('In-app template is not available.');
            });

            $templateKey = $template->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.in_app_notification_template.edit', compact('template', 'languages', 'templates'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updateInAppNotificationTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'in_app_notification_template.*' => 'required|string',
            'in_app_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'in_app_notification_template.*.required' => 'The message field is required.',
        ]);


        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'in_app') {
                        $status[$key] = $request->in_app_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'in_app' => strip_tags($request->in_app_notification_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'In App Notification template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }

    public function pushNotificationTemplates()
    {
        $templates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');;
        return view('admin.notification_templates.push_notification_template.index', compact('templates'));
    }

    public function editPushNotificationTemplate($id)
    {
        try {
            $languages = Language::select('id', 'name')->get();
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Push template is not available.');
            });
            $templateKey = $template->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.push_notification_template.edit', compact('template', 'languages', 'templates'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updatePushNotificationTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'push_notification_template.*' => 'required|string',
            'push_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'push_notification_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });


            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'push') {
                        $status[$key] = $request->push_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'push' => strip_tags($request->push_notification_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name

            ]);
            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'Push Notification template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }
}
PK     x\qγn    +  Http/Controllers/Admin/PluginController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Validation\ValidationException;
use Vonage\Client\Exception\Validation;
use function GuzzleHttp\Promise\all;

class PluginController extends Controller
{
    public function pluginConfig()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.plugin_config', compact('basicControl'));
    }

    public function tawkConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.tawk_control', compact('basicControl'));
    }

    public function tawkConfigurationUpdate(Request $request)
    {
        try {
            $request->validate([
                'tawk_id' => 'required|string|min:3',
                'status' => 'required|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "tawk_id" => $request->tawk_id,
                "tawk_status" => $request->status
            ]);

            return back()->with('success', 'Successfully Updated');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function fbMessengerConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.fb_messenger_control', compact('basicControl'));
    }

    public function fbMessengerConfigurationUpdate(Request $request)
    {
        try {
            $request->validate([
                'fb_app_id' => 'required|string|min:3',
                'fb_page_id' => 'required|string|min:3',
                'fb_messenger_status' => 'required|integer|min:0|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "fb_app_id" => $request->fb_app_id,
                "fb_page_id" => $request->fb_page_id,
                "fb_messenger_status" => $request->fb_messenger_status
            ]);

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function googleRecaptchaConfiguration()
    {
        $data['googleRecaptchaSiteKey'] = env('GOOGLE_RECAPTCHA_SITE_KEY');
        $data['googleRecaptchaSecretKey'] = env('GOOGLE_RECAPTCHA_SECRET_KEY');
        $data['googleRecaptchaSiteVerifyUrl'] = env('GOOGLE_RECAPTCHA_SITE_VERIFY_URL');
        $data['basicControl'] = basicControl();
        return view('admin.plugin_controls.google_recaptcha_control', $data);
    }

    public function googleRecaptchaConfigurationUpdate(Request $request)
    {

        try {
            $request->validate([
                'google_recaptcha_site_key' => 'required|string|min:3',
                'google_recaptcha_secret_key' => 'required|string|min:3',
                'google_recaptcha_site_verify_url' => 'required|string|min:3',
                'google_reCapture_admin_login' => 'integer|in:0,1',
                'google_reCaptcha_status_login' => 'integer|in:0,1',
                'google_reCaptcha_status_registration' => 'integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                'google_reCapture_admin_login' => $request->google_reCapture_admin_login,
                'google_reCaptcha_status_login' => $request->google_reCaptcha_status_login,
                'google_reCaptcha_status_registration' => $request->google_reCaptcha_status_registration
            ]);


            $env = [
                'GOOGLE_RECAPTCHA_SITE_KEY' => $request->google_recaptcha_site_key,
                'GOOGLE_RECAPTCHA_SECRET_KEY' => $request->google_recaptcha_secret_key,
                'GOOGLE_RECAPTCHA_SITE_VERIFY_URL' => $request->google_recaptcha_site_verify_url,
            ];

            BasicService::setEnv($env);

            Artisan::call('config:clear');
            Artisan::call('cache:clear');

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function googleAnalyticsConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.analytic_control', compact('basicControl'));
    }

    public function googleAnalyticsConfigurationUpdate(Request $request)
    {

        try {
            $request->validate([
                'MEASUREMENT_ID' => 'required|min:3',
                'analytic_status' => 'required|integer|in:0,1',
            ], [
                'MEASUREMENT_ID.required' => " The MEASUREMENT ID field is required.
"
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "measurement_id" => $request->MEASUREMENT_ID,
                "analytic_status" => $request->analytic_status,
            ]);

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->withErrors($e->getMessage());
        }
    }

    public function manualRecaptcha()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.manual_recaptcha', compact('basicControl'));
    }

    public function manualRecaptchaUpdate(Request $request)
    {
        try {
            $request->validate([
                'admin_login_recaptcha' => 'required|integer|in:0,1',
                'user_login_recaptcha' => 'required|integer|in:0,1',
                'user_registration_recaptcha' => 'required|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->recaptcha_admin_login = $request->admin_login_recaptcha;
            $basicControl->reCaptcha_status_login = $request->user_login_recaptcha;
            $basicControl->reCaptcha_status_registration = $request->user_registration_recaptcha;
            $basicControl->save();

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    public function activeRecaptcha(Request $request)
    {

        try {
            $request->validate([
                'googleRecaptcha' => 'nullable|integer|in:0,1',
                'manualRecaptcha' => 'nullable|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->google_recaptcha = $request->googleRecaptcha;
            $basicControl->manual_recaptcha = $request->manualRecaptcha;
            $basicControl->save();

            return response([
                'success' => true,
                'message' => "Recaptcha Updated Successfully"
            ]);
        } catch (\Exception $e) {
            return response([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
}
PK     x\ۖQ  Q  1  Http/Controllers/Admin/BasicControlController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BasicControl;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Facades\App\Services\BasicService;
use Facades\App\Services\CurrencyLayerService;
use Exception;

class BasicControlController extends Controller
{
    public function index($settings = null)
    {
        $settings = $settings ?? 'settings';
        abort_if(!in_array($settings, array_keys(config('generalsettings'))), 404);
        $settingsDetails = config("generalsettings.{$settings}");
        return view('admin.control_panel.settings', compact('settings', 'settingsDetails'));
    }

    public function basicControl()
    {
        $data['basicControl'] = basicControl();
        $data['timeZones'] = timezone_identifiers_list();
        $data['dateFormat'] = config('dateformat');
        return view('admin.control_panel.basic_control', $data);
    }

    public function basicControlUpdate(Request $request)
    {
        $request->validate([
            'site_title' => 'required|string|min:1|max:100',
            'time_zone' => 'required|string',
            'base_currency' => 'required|string|min:1|max:100',
            'currency_symbol' => 'required|string|min:1|max:100',
            'fraction_number' => 'required|integer|not_in:0',
            'paginate' => 'required|integer|not_in:0',
            'date_format' => 'required|string',
            'contact_number' => 'required|max:20',
            'payment_released' => 'required|max:20',
            'payment_expired' => 'required|max:20',
            'admin_prefix' => 'required|string|min:3|max:100',
            'light_primary_color' => 'required|string',
            'dark_primary_color' => 'required|string',
        ]);

        try {
            $basic = BasicControl();
            $response = BasicControl::updateOrCreate([
                'id' => $basic->id ?? ''
            ], [
                'site_title' => $request->site_title,
                'time_zone' => $request->time_zone,
                'base_currency' => $request->base_currency,
                'currency_symbol' => $request->currency_symbol,
                'fraction_number' => $request->fraction_number,
                'date_time_format' => $request->date_format,
                'contact_number' => $request->contact_number,
                'payment_released' => $request->payment_released,
                'payment_expired' => $request->payment_expired,
                'paginate' => $request->paginate,
                'admin_prefix' => $request->admin_prefix,
                'light_primary_color' => $request->light_primary_color,
                'dark_primary_color' => $request->dark_primary_color,
            ]);

            if (!$response)
                throw new Exception('Something went wrong, when updating data');

            $env = [
                'APP_TIMEZONE' => $response->time_zone,
                'APP_DEBUG' => $response->error_log == 0 ? 'true' : 'false'
            ];

            BasicService::setEnv($env);
            session()->flash('success', 'Basic control has been successfully configured');
            Artisan::call('optimize:clear');
            return back();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function basicControlActivityUpdate(Request $request)
    {
        $request->validate([
            'strong_password' => 'nullable|numeric|in:0,1',
            'registration' => 'nullable|numeric|in:0,1',
            'error_log' => 'nullable|numeric|in:0,1',
            'card' => 'nullable|numeric|in:0,1',
            'top_up' => 'nullable|numeric|in:0,1',
            'sell_post' => 'nullable|numeric|in:0,1',
            'is_active_cron_notification' => 'nullable|numeric|in:0,1',
            'has_space_between_currency_and_amount' => 'nullable|numeric|in:0,1',
            'is_force_ssl' => 'nullable|numeric|in:0,1',
            'is_currency_position' => 'nullable|string|in:left,right'
        ]);

        try {
            $basic = BasicControl();
            $response = BasicControl::updateOrCreate([
                'id' => $basic->id ?? ''
            ], [
                'error_log' => $request->error_log,
                'strong_password' => $request->strong_password,
                'registration' => $request->registration,
                'card' => $request->card,
                'top_up' => $request->top_up,
                'sell_post' => $request->sell_post,
                'is_active_cron_notification' => $request->is_active_cron_notification,
                'has_space_between_currency_and_amount' => $request->has_space_between_currency_and_amount,
                'is_currency_position' => $request->is_currency_position,
                'is_force_ssl' => $request->is_force_ssl
            ]);

            if (!$response)
                throw new Exception('Something went wrong, when updating the data.');

            session()->flash('success', 'Basic control has been successfully configured.');
            Artisan::call('optimize:clear');
            return back();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyExchangeApiConfig()
    {
        $data['scheduleList'] = config('schedulelist.schedule_list');
        $data['basicControl'] = basicControl();
        return view('admin.control_panel.exchange_api_setting', $data);
    }

    public function currencyExchangeApiConfigUpdate(Request $request)
    {
        try {
            $basicControl = basicControl();
            $basicControl->update([
                'currency_layer_access_key' => $request->currency_layer_access_key,
                'currency_layer_auto_update' => $request->currency_layer_auto_update,
                'currency_layer_auto_update_at' => $request->currency_layer_auto_update_at,
                'coin_market_cap_app_key' => $request->coin_market_cap_app_key,
                'coin_market_cap_auto_update' => $request->coin_market_cap_auto_update,
                'coin_market_cap_auto_update_at' => $request->coin_market_cap_auto_update_at,
            ]);
            return back()->with('success', 'Configuration changes successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
    public function basicControlTableViewUpdate(Request $request)
    {
        $this->validate($request, [
            'table_view' => 'required|in:flex,scrolling',
        ]);

        $basic = BasicControl();
        BasicControl::updateOrCreate([
            'id' => $basic->id ?? ''
        ], [
            'table_view' => $request->table_view,
        ]);

        return back()->with('success', ucfirst($request->table_view) . ' Version Applied Successfully');
    }
    public function appControl(Request $request)
    {
        $basicControl = basicControl();
        if ($request->method() == 'GET') {
            return view('admin.control_panel.app_control', compact('basicControl'));
        } elseif ($request->method() == 'POST') {
            try {
                $response = BasicControl::updateOrCreate([
                    'id' => $basicControl->id ?? ''
                ], [
                    'app_color' => $request->app_color,
                    'app_version' => $request->app_version,
                    'app_build' => $request->app_build,
                    'is_major' => $request->is_major,
                ]);

                if (!$response)
                    throw new Exception('Something went wrong, when updating the data.');

                session()->flash('success', 'App control has been successfully configured.');
                Artisan::call('optimize:clear');
                return back();
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }
}
PK     x\t0XM  M  .  Http/Controllers/Admin/SubscribeController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class SubscribeController extends Controller
{
    public function index(Request $request)
    {
        $data['subscribeRecord'] = collect(Subscriber::selectRaw('COUNT(id) AS totalSubscribe')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todaySubscribe')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todaySubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN WEEK(created_at, 1) = WEEK(CURDATE(), 1) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisWeekSubscribe')
            ->selectRaw('(COUNT(CASE WHEN WEEK(created_at, 1) = WEEK(CURDATE(), 1) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisWeekSubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthSubscribe')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthSubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisYearSubscribe')
            ->selectRaw('(COUNT(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisYearSubscribePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.subscribe.list', $data);
    }

    public function subscribeSearch(Request $request)
    {
        $filterName = $request->name;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $subscribes = Subscriber::orderBy('id', 'DESC')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('email', 'LIKE', '%' . $filterName . '%');
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($request->search['value']), function ($query) use ($request) {
                $query->where(function ($subquery) use ($request) {
                    $subquery->where('email', 'LIKE', '%' . $request->search['value'] . '%');
                });
            });


        return DataTables::of($subscribes)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })

            ->addColumn('email', function ($item) {
                return $item->email;
            })

            ->addColumn('subscribe_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })

            ->rawColumns(['no','email', 'subscribe_at'])
            ->make(true);
    }
}
PK     x\AA      8  Http/Controllers/Admin/AdminProfileSettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationTemplate;
use Illuminate\Support\Facades\Hash;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Exception;

class AdminProfileSettingController extends Controller
{
    use Upload;

    public function profile()
    {
        $basicControl = basicControl();
        $admin = Auth::guard('admin')->user();
        $templates = NotificationTemplate::where('notify_for', 1)->get()->unique('template_key');
        return view('admin.profile', compact('admin', 'basicControl', 'templates'));
    }

    public function profileUpdate(Request $request)
    {
        $request->validate([
            'name' => 'required|string|min:3',
            'username' => 'required|string|min:3',
            'email' => 'required|email|min:3|email:rfc,dns',
            'phone' => 'required|string|min:3',
            'addressLine' => 'required|string|min:3',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif'
        ]);

        try {
            $admin = Auth::guard('admin')->user();

            if ($request->file('image')) {
                $image = $this->fileUpload($request->image, config('filelocation.adminProfileImage.path'), null,null, 'webp', 60, $admin->image, $admin->image_driver);
                if ($image) {
                    $adminImage = $image['path'];
                    $adminImageDriver = $image['driver'] ?? 'local';
                }
            }

            $response = $admin->update([
                'name' => $request->name,
                'username' => $request->username,
                'email' => $request->email,
                'phone' => $request->phone,
                'address' => $request->addressLine,
                'image' => $adminImage ?? $admin->image,
                'image_driver' => $adminImageDriver ?? $admin->image_driver,
            ]);

            if (!$response) {
                throw new Exception("Something went wrong");
            }

            return back()->with("success", "Admin Profile Updated Successfully.");

        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function passwordUpdate(Request $request)
    {

        $request->validate([
            'current_password' => 'required',
            'password' => 'required|min:5|confirmed',
        ]);

        $admin = Auth::guard('admin')->user();

        if (!Hash::check($request->current_password, $admin->password)) {
            return back()->with('error', "Password didn't match");
        }
        $admin->update([
            'password' => bcrypt($request->password)
        ]);
        return back()->with('success', 'Password has been Changed');
    }

    public function notificationPermission(Request $request)
    {
        $templates = $request->input('templates', []);
        foreach ($templates as $templateId => $templateData) {
            $template = NotificationTemplate::findOrFail($templateId);
            $template->update([
                'status' => $templateData
            ]);
        }
        return back()->with('success', 'Permissions updated successfully.');
    }


}
PK     x\PM  M  /  Http/Controllers/Admin/PaymentLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Facades\App\Services\BasicService;
use Yajra\DataTables\Facades\DataTables;

class PaymentLogController extends Controller
{
    use Notify;

    public function index()
    {
        $paymentRecord = \Cache::get('paymentRecord');
        if (!$paymentRecord) {
            $paymentRecord = Deposit::selectRaw('COUNT(id) AS totalPaymentLog')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS paymentSuccess')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS paymentSuccessPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS pendingPayment')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS pendingPaymentPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS cancelPayment')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS cancelPaymentPercentage')
                ->get()
                ->toArray();
            \Cache::put('paymentRecord', $paymentRecord);
        }

        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.payment.logs', $data, compact('paymentRecord'));
    }


    public function search(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $deposit = Deposit::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'gateway:id,name,image,driver'])
            ->whereHas('user')
            ->whereHas('gateway')
            ->orderBy('id', 'desc')
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($deposit)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';


            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                if (optional($item->gateway)->id > 999) {
                    $icon = $item->status == 2 ? 'pencil' : 'eye';
                    return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                 data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
                } else {
                    return '-';
                }
            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);

    }

    public function pending()
    {
        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.payment.request', $data);
    }

    public function paymentRequest(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;


        $funds = Deposit::with('user', 'gateway')
            ->where('status', 2)->where('payment_method_id', '>', 999)->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->get();

        return DataTables::of($funds)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2 cursor-unset" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                $icon = $item->status == 2 ? 'pencil' : 'eye';
                return "<button type='button' class='btn btn-white btn-sm edit_btn'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";

            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);
    }

    public function action(Request $request, $id)
    {
        $this->validate($request, [
            'id' => 'required',
            'status' => ['required', Rule::in(['1', '3'])],
            'feedback' => 'required|string|min:3|max:300'
        ]);
        $data = Deposit::where('id', $id)->whereIn('status', [2])->with('user', 'gateway')->firstOrFail();

        if ($request->status == '1') {
            $data->update([
                'note' => $request->feedback
            ]);
            BasicService::preparePaymentUpgradation($data);
            session()->flash('success', 'Payment approved successfully.');
            return back();

        } elseif ($request->status == '3') {

            $data->update([
                'status' => 3,
                'note' => $request->feedback
            ]);

            $msg = [
                'username' => optional($data->user)->username,
                'amount' => currencyPosition($data->amount_in_base),
                'gateway' => optional($data->gateway)->name,
            ];
            $action = [
                "link" => '#',
                "icon" => "fas fa-money-bill-alt text-white"
            ];

            $this->userPushNotification($data->user, 'PAYMENT_REJECTED', $msg, $action);
            $this->userFirebasePushNotification('PAYMENT_REJECTED', $msg, $action);
            $this->sendMailSms($data->user, 'PAYMENT_REJECTED', [
                'gateway_name' => optional($data->gateway)->name,
                'amount' => currencyPosition($data->amount),
                'charge' => currencyPosition($data->charge),
                'transaction' => $data->trx_id,
                'feedback' => $data->note,
            ]);

            session()->flash('success', 'Payment rejected successfully.');
            return back();
        }
        return back();
    }
}


PK     x\>,  ,  )  Http/Controllers/Admin/BlogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Models\BlogCategory;
use App\Models\BlogDetails;
use App\Models\Language;
use App\Traits\Upload;
use Illuminate\Http\Request;
use App\Rules\AlphaDashWithoutSlashes;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class BlogController extends Controller
{
    use Upload;

    public function index()
    {
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        $data['blogs'] = Blog::with('category', 'details')->orderBy('id', 'desc')->paginate(10);
        return view('admin.blogs.list', $data);
    }


    public function create()
    {
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->get();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view('admin.blogs.create', $data);
    }

    public function store(Request $request)
    {

        $request->validate([
            'category_id' => 'required|numeric|not_in:0|exists:blog_categories,id',
            'title' => 'required|string|min:3|max:200',
            'slug' => 'required|string|min:3|max:200|alpha_dash|unique:blogs,slug',
            'description' => 'required|string|min:3',
            'description_image' => 'required|mimes:png,jpg,jpeg|max:50000',
        ]);
        try {
            if ($request->hasFile('description_image')) {
                $descriptionImage = $this->fileUpload($request->description_image, config('filelocation.blog.path'), null, config('filelocation.blog.preview_img'), 'webp', null);
                throw_if(empty($descriptionImage['path']), 'Description image could not be uploaded.');
            }
            if ($request->hasFile('banner_image')) {
                $bannerImage = $this->fileUpload($request->banner_image, config('filelocation.blog.path'), null, config('filelocation.blog.banner_img'), 'webp', null);
                throw_if(empty($bannerImage['path']), 'Banner image could not be uploaded.');
            }

            $response = Blog::create([
                'category_id' => $request->category_id,
                'slug' => $request->slug,
                'blog_image' => $descriptionImage['path'] ?? null,
                'blog_image_driver' => $descriptionImage['driver'] ?? null,
                'banner_image' => $bannerImage['path'] ?? null,
                'banner_image_driver' => $bannerImage['driver'] ?? null,
            ]);

            throw_if(!$response, 'Something went wrong while storing blog data. Please try again later.');


            $response->details()->create([
                "title" => $request->title,
                'language_id' => $request->language_id,
                'description' => $request->description,
            ]);

            return back()->with('success', 'Blog saved successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function blogEdit($id, $language = null)
    {
        $blog = Blog::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])
            ->where('id', $id)
            ->firstOr(function () {
                throw new \Exception('Blog not found');
            });

        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->get();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view('admin.blogs.edit', $data, compact('blog', 'language'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function blogUpdate(Request $request, $id, $language)
    {
        $request->validate([
            'category_id' => 'required|numeric|not_in:0|exists:blog_categories,id',
            'title' => 'required|string|min:3|max:1000',
            'description' => 'nullable|string|min:3',
            'description_image' => 'nullable|mimes:png,jpg,jpeg|max:50000',
            'banner_image' => 'nullable|mimes:png,jpg,jpeg|max:50000',
        ]);

        try {
            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });

            if ($request->hasFile('description_image')) {
                $descriptionImage = $this->fileUpload($request->description_image, config('filelocation.blog.path'), null, config('filelocation.blog.preview_img'), 'webp', null, $blog->blog_image, $blog->blog_image_driver);
                throw_if(empty($descriptionImage['path']), 'Description image could not be uploaded.');
            }

            if ($request->hasFile('banner_image')) {
                $bannerImage = $this->fileUpload($request->banner_image, config('filelocation.blog.path'), null, config('filelocation.blog.banner_img'), 'webp', null, $blog->banner_image, $blog->banner_image_driver);
                throw_if(empty($bannerImage['path']), 'Banner image could not be uploaded.');
            }

            $response = $blog->update([
                'category_id' => $request->category_id,
                'slug' => $request->slug ?? $blog->slug,
                'blog_image' => $descriptionImage['path'] ?? $blog->blog_image,
                'blog_image_driver' => $descriptionImage['driver'] ?? $blog->blog_image_driver,
                'banner_image' => $bannerImage['path'] ?? $blog->banner_image,
                'banner_image_driver' => $bannerImage['driver'] ?? $blog->banner_image_driver,
            ]);

            throw_if(!$response, 'Something went wrong while storing blog data. Please try again later.');

            $blog->details()->updateOrCreate([
                'language_id' => $language,
            ],
                [
                    "title" => $request->title,
                    'description' => $request->description,
                ]
            );

            return back()->with('success', 'Blog saved successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function destroy(string $id)
    {
        try {
            $blog = Blog::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog data found.');
            });

            $blogDetails = BlogDetails::where('blog_id', $id)->get();
            if ($blogDetails->count() > 0) {
                foreach ($blogDetails as $blogDetail) {
                    $blogDetail->delete();
                }
            }

            $blog->delete();
            return redirect()->back()->with('success', 'Blog deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function slugUpdate(Request $request)
    {

        $rules = [
            "blogId" => "required|exists:blogs,id",
            "newSlug" => ["required", "min:1", "max:100",
                new AlphaDashWithoutSlashes(),
                Rule::unique('blogs', 'slug')->ignore($request->blogId),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up'])
            ],
        ];
        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()]);
        }
        $blogId = $request->blogId;

        $newSlug = $request->newSlug;
        $blog = Blog::find($blogId);

        if (!$blog) {
            return back()->with("error", "Blog not found");
        }

        $blog->slug = $newSlug;
        $blog->save();

        return response([
            'success' => true,
            'slug' => $blog->slug
        ]);
    }

    public function blogSeo(Request $request, $id)
    {
        try {
            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });
            return view('admin.blogs.seo', compact('blog'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function blogSeoUpdate(Request $request, $id)
    {
        $request->validate([
            'page_title' => 'required|string|min:3|max:100',
            'meta_title' => 'required|string|min:3|max:100',
            'meta_keywords' => 'required|array',
            'meta_keywords.*' => 'required|string|min:1|max:300',
            'meta_description' => 'required|string|min:1|max:300',
            'seo_meta_image' => 'sometimes|required|mimes:jpeg,png,jpeg|max:10240'
        ]);

        try {

            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });

            if ($request->hasFile('meta_image')) {
                try {
                    $image = $this->fileUpload($request->meta_image, config('filelocation.pageSeo.path'), null, null, 'webp', 80,$blog->meta_image, $blog->meta_image_driver);
                    if ($image) {
                        $pageSEOImage = $image['path'];
                        $pageSEODriver = $image['driver'] ?? 'local';
                    }
                } catch (\Exception $exp) {
                    return back()->with('error', 'Meta image could not be uploaded.');
                }
            }

            $blog->update([
                'page_title' => $request->page_title,
                'meta_title' => $request->meta_title,
                'meta_keywords' => $request->meta_keywords,
                'meta_description' => $request->meta_description,
                'meta_image' => $pageSEOImage ?? $blog->meta_image,
                'meta_image_driver' => $pageSEODriver ?? $blog->meta_image_driver,
            ]);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
        return back()->with('success', 'Seo has been updated.');
    }
    public function status($id){

        try {
            $blog = Blog::select('id', 'status')
                ->where('id', $id)
                ->firstOr(function () {
                    throw new \Exception('Blog not found.');
                });

            $blog->status = ($blog->status == 1) ? 0 : 1;
            $blog->save();

            return back()->with('success','Blog Status Changed Successfully.');
        }catch (\Exception $e){
            return back()->with('error', $e->getMessage());
        }

    }

}
PK     x\J  J  3  Http/Controllers/Admin/TransactionLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TransactionLogController extends Controller
{
    public function transaction()
    {
        return view('admin.transaction.index');
    }

    public function transactionSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterTransactionId = $request->filterTransactionID;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = Transaction::query()->with(['user:id,username,firstname,lastname,image,image_driver'])
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('trx_id', 'LIKE', "%$search%")
                        ->orWhere('remarks', 'LIKE', "%{$search}%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            });

        return DataTables::of($transaction)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('base_amount', function ($item) {
                $statusClass = $item->trx_type == '+' ? 'text-success' : 'text-danger';
                return "<h6 class='mb-0 $statusClass '>" . $item->trx_type . ' ' . currencyPosition(getAmount($item->amount_in_base)) . "</h6>";
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.view.profile", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                    ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username ?? 'Unknown' . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('type', function ($item) {
                if ($item->transactional_type == Deposit::class) {
                    return 'Deposit';
                } elseif ($item->transactional_type == Order::class) {
                    return 'Order';
                }elseif ($item->transactional_type == Payout::class) {
                    return 'Payout';
                } else {
                    return '-';
                }
            })
            ->addColumn('remarks', function ($item) {
                return $item->remarks;
            })
            ->addColumn('date-time', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->rawColumns(['trx', 'base_amount', 'user', 'type', 'remarks', 'date-time'])
            ->make(true);
    }
}
PK     x\KI	  	  8  Http/Controllers/Admin/TranslateAPISettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Facades\App\Services\BasicService;
use App\Traits\Upload;

class TranslateAPISettingController extends Controller
{

    use Upload;

    public function translateAPISetting()
    {
        $translateMethod = Config('translateconfig.translate_method');
        $activeMethod = Config('translateconfig.default');
        return view('admin.translate_controls.index', compact('translateMethod', 'activeMethod'));
    }

    public function translateAPISettingEdit($method)
    {
        try {
            $data['basicControl'] = basicControl();
            $translateControlMethod = config('translateconfig.translate_method');
            $translateMethodParameters = $translateControlMethod[$method] ?? null;

            return view('admin.translate_controls.translate_api_config', $data, compact('translateMethodParameters', 'method'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function translateAPISettingUpdate(Request $request, $method)
    {
        $rules = [];
        $translateControlMethod = config('translateconfig.translate_method');
        $translateMethodParameters = $translateControlMethod[$method] ?? null;

        foreach ($request->except('_token', '_method') as $key => $value) {
            if (array_key_exists($key, $translateMethodParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }

        $request->validate($rules);

        try {
            $env = [
                'END_POINT_URL' => $request->end_point_url ?? $translateControlMethod['azure']['end_point_url']['value'],
                'SUBSCRIPTION_KEY' => $request->subscription_key ?? $translateControlMethod['azure']['subscription_key']['value'],
                'SUBSCRIPTION_REGION' => $request->subscription_region ?? $translateControlMethod['azure']['subscription_region']['value'],
            ];

            BasicService::setEnv($env);

            return back()->with('success', 'Translate Configuration has been updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function translateSetAsDefault($method)
    {
        $env = [
            'TRANSLATE_METHOD' => $method
        ];

        BasicService::setEnv($env);

        return back()->with('success', 'Translate method set as default successfully.');
    }


}
PK     x\O5  5  -  Http/Controllers/Admin/TempleteController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BasicControl;
use App\Models\Page;
use Illuminate\Http\Request;

class TempleteController extends Controller
{
    public function index()
    {

        return view('admin.templete.home');
    }

    public function selectTemplete(Request $request)
    {
        $theme = $request->input('theme');
        if (!in_array($theme, array_keys(config('themes')))) {
            return response()->json(['error' => "Invalid Request"], 422);
        }

        $basic = BasicControl::firstOrCreate();
        $basic->theme = $theme;
        $basic->save();

        session()->forget('theme');

        $message = request()->theme_name . ' theme selected.';
        return response()->json(['message' => $message], 200);
    }
}
PK     x\Ol[n  n  1  Http/Controllers/Admin/PusherConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;

class PusherConfigController extends Controller
{
    public function pusherConfig()
    {
        $basicControl = basicControl();
        $data['pusherAppId'] = env('pusher_app_id');
        $data['pusherAppKey'] = env('pusher_app_key');
        $data['pusherAppSecret'] = env('pusher_app_secret');
        $data['pusherAppCluster'] = env('pusher_app_cluster');
        return view('admin.control_panel.pusher_config', $data, compact('basicControl'));
    }

    public function pusherConfigUpdate(Request $request)
    {
        $request->validate([
            'pusher_app_id' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_key' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_secret' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_cluster' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'push_notification' => 'nullable|integer|min:0|in:0,1',
        ]);

        $env = [
            'PUSHER_APP_ID' => $request->pusher_app_id,
            'PUSHER_APP_KEY' => $request->pusher_app_key,
            'PUSHER_APP_SECRET' => $request->pusher_app_secret,
            'PUSHER_APP_CLUSTER' => $request->pusher_app_cluster,
        ];

        BasicService::setEnv($env);

        $basicControl = basicControl();
        $basicControl->update([
           'in_app_notification' => $request->in_app_notification
        ]);

        return back()->with('success', 'Pusher Configuration Successfully');

    }
}
PK     x\]    2  Http/Controllers/Admin/Module/CouponController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Coupon;
use App\Models\TopUp;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    public function couponList()
    {
        $data['coupons'] = Coupon::latest()->get();
        return view('admin.coupon.list', $data);
    }

    public function couponStore(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('admin.coupon.create');
        } elseif ($request->method() == 'POST') {
            $this->validate($request, [
                'title' => 'required',
                'code' => 'required|min:6|unique:coupons,code',
                'discount' => 'required|min:0',
                'discount_type' => 'required|in:percent,flat',
                'start_date' => 'required',
            ]);


            $coupon = Coupon::create([
                'title' => $request->title,
                'code' => $request->code,
                'discount' => $request->discount,
                'discount_type' => $request->discount_type,
                'used_limit' => $request->used_limit??0,
                'is_unlimited' => $request->is_unlimited == 'yes' ? 1 : 0,
                'start_date' => Carbon::createFromFormat('d M Y H:i', $request->start_date)->format('Y-m-d H:i:s'),
                'end_date' => $request->is_expired == 'no' ? null : Carbon::createFromFormat('d M Y H:i', $request->end_date)->format('Y-m-d H:i:s'),
            ]);

            return redirect()->route('admin.couponEdit', $coupon->id)->with('success', 'Coupon generated successfully');
        }
    }

    public function couponEdit(Request $request, $id)
    {
        $coupon = Coupon::findOrFail($id);
        if ($request->method() == 'GET') {
            $data['topups'] = TopUp::latest()->get();
            $data['cards'] = Card::latest()->get();
            return view('admin.coupon.edit', $data, compact('coupon'));
        } elseif ($request->method() == 'POST') {
            $this->validate($request, [
                'title' => 'required',
                'code' => 'required|min:6|unique:coupons,code,' . $coupon->id,
                'discount' => 'required|min:0',
                'discount_type' => 'required|in:percent,flat',
                'start_date' => 'required',
            ]);


            $coupon->update([
                'title' => $request->title,
                'code' => $request->code,
                'apply_module' => $request->apply_module ?? [],
                'discount' => $request->discount,
                'discount_type' => $request->discount_type,
                'used_limit' => $request->used_limit,
                'is_unlimited' => $request->is_unlimited == 'yes' ? 1 : 0,
                'start_date' => Carbon::createFromFormat('d M Y H:i', $request->start_date)->format('Y-m-d H:i:s'),
                'end_date' => $request->is_expired == 'no' ? null : Carbon::createFromFormat('d M Y H:i', $request->end_date)->format('Y-m-d H:i:s'),
            ]);

            return back()->with('success', 'Updated Successfully');
        }
    }

    public function couponDelete($id)
    {
        $coupon = Coupon::findOrFail($id);
        $coupon->delete();
        return back()->with('success', 'Deleted Successfully');
    }

    public function couponMultipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Coupon.');
            return response()->json(['error' => 1]);
        } else {
            Coupon::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been change');
            return response()->json(['success' => 1]);
        }
    }

    public function couponMultipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Coupon.');
            return response()->json(['error' => 1]);
        } else {
            Coupon::whereIn('id', $request->strIds)->get()->delete();
            session()->flash('success', 'Deleted Successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function topUpTypeChange(Request $request, $type)
    {
        if ($type == 'permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->top_up_list??[];
                    $mergeData = array_merge($existingLists, $request->strIds);
                    $coupon->top_up_list = array_unique($mergeData);
                    $coupon->save();

                    session()->flash('success', 'Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }

        if ($type == 'not_permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->top_up_list??[];
                    $coupon->top_up_list = array_diff($existingLists, $request->strIds);;
                    $coupon->save();

                    session()->flash('success', 'Not Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }
    }

    public function cardTypeChange(Request $request, $type)
    {
        if ($type == 'permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->card_list??[];
                    $mergeData = array_merge($existingLists, $request->strIds);
                    $coupon->card_list = array_unique($mergeData);
                    $coupon->save();

                    session()->flash('success', 'Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }

        if ($type == 'not_permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->card_list??[];
                    $coupon->card_list = array_diff($existingLists, $request->strIds);;
                    $coupon->save();

                    session()->flash('success', 'Not Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }
    }
}
PK     x\pH  H  0  Http/Controllers/Admin/Module/CardController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\CardStoreRequest;
use App\Models\Card;
use App\Models\Category;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CardController extends Controller
{
    use Upload;

    public function list(Request $request)
    {
        $data['cards'] = collect(Card::with(['category'])
            ->when(isset($request->category_id), function ($query) use ($request) {
                $query->where('category_id', $request->category_id);
            })
            ->selectRaw('COUNT(id) AS totalCard')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCard')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCardPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCard')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCardPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCard')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCardPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCard')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCardPercentage')
            ->get()
            ->toArray())->collapse();

        $data['category_id'] = $request->category_id ?? null;
        return view('admin.card.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $categoryId = $request->category_id;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $cards = Card::with(['category'])->orderBy('sort_by', 'ASC')
            ->withCount([
                'activeServices',
            ])
            ->when(isset($categoryId), function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('region', 'LIKE', "%{$search}%")
                        ->orWhereHas('category', function ($categoryQuery) use ($search) {
                            $categoryQuery->where('name', 'LIKE', "%{$search}%");
                        });
                });
            })->get();

        return DataTables::of($cards)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image->preview_driver ?? null, $item->image->preview ?? null);
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                              <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                              </div>
                            <div class="flex-shrink-0">
                                <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                <p class="text-hover-primary mb-0">' . $item->region . '</p>
                            </div>
                        </a>
                    ';

            })
            ->addColumn('active_service', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_services_count) . '</span>';
            })
            ->addColumn('active_code', function ($item) {
                return '<span class="badge bg-soft-secondary text-dark">' . number_format($item->activeCodeCount()) . '</span>';
            })
            ->addColumn('instant_delivery', function ($item) {
                if ($item->instant_delivery == 1) {
                    return '<span class="badge bg-soft-primary text-primary">' . trans('Yes') . '</span>';

                } else {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('No') . '</span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="'.$item->category?->icon.'"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('trending', function ($item) {
                if ($item->trending == 1) {
                    return '<span class="badge bg-soft-primary text-primary">
                    <span class="legend-indicator bg-primary"></span>' . trans('Yes') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('No') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="'.$item->category?->icon.'"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.card.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.card.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.card.delete', $item->id);
                $trending = route('admin.card.trending', $item->id);
                $edit = route('admin.card.edit', $item->id);
                $service = route('admin.cardService.list') . '?card_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $service . '" class="dropdown-item">
                            <i class="fas fa-dice dropdown-item-icon"></i> ' . trans("Service List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item trending_btn" href="javascript:void(0)" data-bs-target="#trending"
                           data-bs-toggle="modal" data-route="' . $trending . '">
                          <i class="fal fa-chart-line-up dropdown-item-icon"></i> ' . trans("Manage Trending") . '
                       </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_service', 'active_code','trending', 'instant_delivery', 'status', 'category', 'created_at', 'action'])
            ->make(true);
    }

    public function store(CardStoreRequest $request)
    {
        if ($request->method() == 'GET') {
            $data['categories'] = Category::active()->type('card')->sort()->get();
            return view('admin.card.create', $data);
        } elseif ($request->method() == 'POST') {
            try {
                $card = new Card();
                $fillData = $request->except('_token');
                $fillData['image'] = $this->processImages($fillData);

                $card->fill($fillData)->save();

                return back()->with('success', 'Card Created Successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function statusChange(Request $request)
    {
        $card = Card::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $card->status = 1;
            } else {
                $card->status = 0;
            }
            $card->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function sort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Card::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function trending($id){
        try {
            $card = Card::select(['id', 'trending'])->findOrFail($id);

            $card->trending = ($card->trending == 0) ? 1 : 0;
            $card->save();

            $message = ($card->trending == 0) ? 'Removed From Trending List.' : 'Added To Trending List.';

            return back()->with('success', $message);
        }catch (\Exception $exception){
            return back()->with('error', $exception->getMessage());
        }

    }
    public function delete($id)
    {
        try {
            $card = Card::findOrFail($id);
            $images = [
                ['driver' => $card->image->image_driver ?? null, 'path' => $card->image->image ?? null],
                ['driver' => $card->image->preview_driver ?? null, 'path' => $card->image->preview ?? null],
                ['driver' => $card->image->banner_driver ?? null, 'path' => $card->image->banner ?? null],
            ];
            foreach ($images as $image) {
                $this->fileDelete($image['driver'], $image['path']);
            }
            $card->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit(CardStoreRequest $request, $id)
    {
        $card = Card::FindOrFail($id);
        if ($request->method() == 'GET') {
            $categories = Category::active()->type('card')->sort()->get();
            return view('admin.card.edit', compact('card', 'categories'));
        } elseif ($request->method() == 'POST') {
            try {
                $fillData = $request->except('_token');
                $fillData['image'] = $this->processImages($fillData, $card);

                $card->fill($fillData)->save();

                return back()->with('success', 'Card has been updated successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Card::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $images = [
                    ['driver' => $query->image->image_driver ?? null, 'path' => $query->image->image ?? null],
                    ['driver' => $query->image->preview_driver ?? null, 'path' => $query->image->preview ?? null],
                    ['driver' => $query->image->banner_driver ?? null, 'path' => $query->image->banner ?? null],
                ];
                foreach ($images as $image) {
                    $this->fileDelete($image['driver'], $image['path']);
                }
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Card has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }
    public function multipleTrending(Request $request)
    {
        if (empty($request->strIds)) {
            session()->flash('error', 'No rows were selected.');
            return response()->json(['error' => 1]);
        }

        Card::whereIn('id', $request->strIds)->each(function ($card) {
            $card->trending = !$card->trending;
            $card->save();
        });

        session()->flash('success', 'Trending status has been updated successfully.');
        return response()->json(['success' => 1]);
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Card::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Card has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    private function processImages($fillData, $topUP = null)
    {
        $images = [
            'image' => $fillData['image'] ?? null,
            'preview' => $fillData['preview_image'] ?? null,
        ];

        $imageData = [];
        foreach ($images as $key => $image) {
            if ($image) {
                $uploadedImage = $this->uploadImage($image, $key, $topUP);
                if ($uploadedImage) {
                    $imageData[$key] = $uploadedImage['path'];
                    $imageData[$key . '_driver'] = $uploadedImage['driver'];
                }
            } else {
                $imageData[$key] = $topUP->image->{$key} ?? null;
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null;
            }
        }

        return $imageData;
    }

    private function uploadImage($image, $key, $topUP = null)
    {
        try {
            return $this->fileUpload(
                $image,
                config('filelocation.card.path'),
                null,
                config('filelocation.card.' . $key . '_size'),
                'webp',
                60,
                $topUP->image->{$key} ?? null,
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null,

            );
        } catch (\Exception $e) {
            return null;
        }
    }
}
PK     x\yk5  5  8  Http/Controllers/Admin/Module/TopUpServiceController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\TopUpServiceExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopUpServiceRequest;
use App\Imports\TopUpServiceImport;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\Sample;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class TopUpServiceController extends Controller
{
    use Upload, Sample;

    public function serviceList(Request $request)
    {
        $data['topUp'] = TopUp::select(['id', 'name'])->findOrFail($request->top_up_id);
        $data['services'] = collect(TopUpService::with(['topUp'])->where('top_up_id', $request->top_up_id)->selectRaw('COUNT(id) AS totalService')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeService')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeServicePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveService')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveServicePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayService')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayServicePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthService')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthServicePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.topUp.service.index', $data);
    }

    public function serviceSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $services = TopUpService::orderBy('sort_by', 'ASC')->where('top_up_id', $request->top_up_id)
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%");
                    $subquery->orWhere('price', 'LIKE', "%$search%");
                    $subquery->orWhere('discount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($services)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image_driver ?? null, $item->image ?? null);
                $offerContent = $item->is_offered ? '<div class="trending-content"><i class="fa-light fa-badge-percent"></i>' . trans('Campaign') . '</div>' : '';
                return '<a class="d-flex align-items-center me-2">
                                <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                 </div>
                                <div class="flex-shrink-0 trending-notification">
                                ' . $offerContent . '
                                  <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                  </div>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('price', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . basicControl()->currency_symbol . formatAmount($item->price - $item->getDiscount()) . '</span> <sup class="badge bg-soft-dark text-dark ms-1">' . basicControl()->currency_symbol . formatAmount($item->getDiscount()) . ' off</sup>';
            })
            ->addColumn('discount', function ($item) {
                $showType = "%";
                if ($item->discount_type == 'flat') {
                    $showType = basicControl()->base_currency;
                }
                return '<span class="badge bg-soft-danger text-danger">' . $item->discount . ' ' . $showType . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.topUpService.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.topUpService.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.topUpService.delete', $item->id);
                $edit = route('admin.topUpService.update', $item->id);
                $image = getFile($item->image_driver ?? null, $item->image ?? null);
                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                      data-route="' . $edit . '" data-name="' . $item->name . '" data-price="' . $item->price . '" data-discount="' . $item->discount . '"
                      data-discount_type="' . $item->discount_type . '" data-image="' . $image . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $statusChange . '" class="dropdown-item">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'price', 'discount', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function serviceStore(TopUpServiceRequest $request)
    {
        TopUp::select(['id'])->findOrFail($request->top_up_id);
        try {
            $service = new TopUpService();
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceUpdate(TopUpServiceRequest $request, $id)
    {
        $service = TopUpService::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Updated Successfully');
        } catch (\Exception $e) {
            return back() > with('error', $e->getMessage());
        }
    }

    public function serviceStatusChange(Request $request)
    {
        $service = TopUpService::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $service->status = 1;
            } else {
                $service->status = 0;
            }
            $service->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            TopUpService::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function serviceDelete($id)
    {
        $service = TopUpService::findOrFail($id);
        try {
            $this->fileDelete($service->image_driver, $service->image);
            $service->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUpService::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $this->fileDelete($query->image_driver, $query->image);
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Service has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUpService::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Service has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function serviceExport(Request $request)
    {
        try {
            return Excel::download(new TopUpServiceExport($request), 'services.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSample()
    {
        try {
            return $this->csvSampleDownload('topUp-service-sample.csv', 'topUp-service-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceImport(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        $topUp = TopUp::select(['id'])->findOrFail($request->topUp);
        try {
            Excel::import(new TopUpServiceImport($topUp->id), $request->file('importFile'));
            return back()->with('success', 'Services Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\Wz	D8  D8  7  Http/Controllers/Admin/Module/CardServiceController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\CardServiceExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\CardServiceRequest;
use App\Imports\CardServiceImport;
use App\Models\Card;
use App\Models\CardService;
use App\Traits\Sample;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class CardServiceController extends Controller
{
    use Upload, Sample;

    public function serviceList(Request $request)
    {
        $data['card'] = Card::select(['id', 'name'])->findOrFail($request->card_id);
        $data['services'] = collect(CardService::with(['card'])->where('card_id', $request->card_id)->selectRaw('COUNT(id) AS totalService')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeService')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeServicePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveService')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveServicePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayService')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayServicePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthService')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthServicePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.card.service.index', $data);
    }

    public function serviceSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $services = CardService::orderBy('sort_by', 'ASC')->where('card_id', $request->card_id)->withCount(['codes' => function ($query) {
            $query->where('status', 1);
        }])
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%")
                        ->orWhere('price', 'LIKE', "%$search%")
                        ->orWhere('discount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($services)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image_driver ?? null, $item->image ?? null);
                $offerContent = $item->is_offered ? '<div class="trending-content"><i class="fa-light fa-badge-percent"></i>' . trans('Campaign') . '</div>' : '';
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="list-group-item">
                                  <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                </div>
                                <div class="flex-shrink-0 trending-notification">
                                ' . $offerContent . '
                                  <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                  </div>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('active_code', function ($item) {
                return '<span class="badge bg-soft-secondary text-dark">' . number_format($item->codes_count) . '</span>';
            })
            ->addColumn('price', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . basicControl()->currency_symbol . formatAmount($item->price - $item->getDiscount()) . '</span> <sup class="badge bg-soft-dark text-dark ms-1">' . basicControl()->currency_symbol . formatAmount($item->getDiscount()) . ' off</sup>';
            })
            ->addColumn('discount', function ($item) {
                $showType = "%";
                if ($item->discount_type == 'flat') {
                    $showType = basicControl()->base_currency;
                }
                return '<span class="badge bg-soft-danger text-danger">' . $item->discount . ' ' . $showType . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.cardService.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.cardService.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.cardService.delete', $item->id);
                $edit = route('admin.cardService.update', $item->id);
                $image = getFile($item->image_driver ?? null, $item->image ?? null);
                $code = route('admin.cardServiceCode.list') . '?service_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                      data-route="' . $edit . '" data-name="' . $item->name . '" data-price="' . $item->price . '" data-discount="' . $item->discount . '"
                      data-discount_type="' . $item->discount_type . '" data-image="' . $image . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $code . '" class="dropdown-item">
                            <i class="fal fa-dice-d20 dropdown-item-icon"></i> ' . trans("Code List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_code', 'price', 'discount', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function serviceStore(CardServiceRequest $request)
    {
        Card::select(['id'])->findOrFail($request->card_id);
        try {
            $service = new CardService();
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceUpdate(CardServiceRequest $request, $id)
    {
        $service = CardService::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Updated Successfully');
        } catch (\Exception $e) {
            return back() > with('error', $e->getMessage());
        }
    }

    public function serviceStatusChange(Request $request)
    {
        $service = CardService::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $service->status = 1;
            } else {
                $service->status = 0;
            }
            $service->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            CardService::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function serviceDelete($id)
    {
        $service = CardService::findOrFail($id);
        try {
            $this->fileDelete($service->image_driver, $service->image);
            $service->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            CardService::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $this->fileDelete($query->image_driver, $query->image);
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Service has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            CardService::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Service has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function serviceExport(Request $request)
    {
        try {
            return Excel::download(new CardServiceExport($request), 'services.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSample()
    {
        try {
            return $this->csvSampleDownload('card-service-sample.csv', 'card-service-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceImport(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        $card = Card::select(['id','category_id'])->findOrFail($request->card_id);

        try {
            Excel::import(new CardServiceImport($card->id), $request->file('importFile'));
            return back()->with('success', 'Services Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\Ͼ)  )  7  Http/Controllers/Admin/Module/SellSummaryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\GiftCardSell;
use App\Models\SellPostPayment;
use App\Models\TopUpSell;
use App\Models\VoucherSell;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class SellSummaryController extends Controller
{
    use Notify;

    public function postSellTran()
    {
        $data['sell'] = collect(SellPostPayment::selectRaw('COUNT(id) AS totalSell')
            ->selectRaw('COUNT(CASE WHEN payment_release = 1 THEN id END) AS releaseSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 1 THEN id END) / COUNT(id)) * 100 AS releaseSellPercentage')
            ->selectRaw('COUNT(CASE WHEN payment_release = 0 THEN id END) AS upcomingSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 0 THEN id END) / COUNT(id)) * 100 AS upcomingSellPercentage')
            ->selectRaw('COUNT(CASE WHEN payment_release = 2 THEN id END) AS holdSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 2 THEN id END) / COUNT(id)) * 100 AS holdSellPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todaySell')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todaySellPercentage')
            ->wherePayment_status(1)
            ->get()
            ->toArray())->collapse();

        return view('admin.sell_summary.postSell', $data);
    }

    public function postSellSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $sells = SellPostPayment::with(['user', 'sellPost', 'sellPost.user'])->wherePayment_status(1)->latest()
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where(function ($subquery) use ($filterName) {
                    $subquery->where('transaction', 'LIKE', '%' . $filterName . '%')
                        ->orWhereHas('sellPost', function ($qq) use ($filterName) {
                            $qq->where('title', 'LIKE', '%' . $filterName . '%');
                        })
                        ->orWhereHas('user', function ($qq) use ($filterName) {
                            $qq->where('firstname', 'LIKE', '%' . $filterName . '%')
                                ->orWhere('lastname', 'LIKE', '%' . $filterName . '%')
                                ->orWhere('username', 'LIKE', '%' . $filterName . '%');
                        });
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', '%' . $search . '%')
                        ->orWhere('price', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('sellPost', function ($qq) use ($search) {
                            $qq->where('title', 'LIKE', '%' . $search . '%');
                        })
                        ->orWhereHas('user', function ($qq) use ($search) {
                            $qq->where('firstname', 'LIKE', '%' . $search . '%')
                                ->orWhere('lastname', 'LIKE', '%' . $search . '%')
                                ->orWhere('username', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($sells)
            ->addColumn('trx', function ($item) {
                return $item->transaction;
            })
            ->addColumn('title', function ($item) {
                $route = route('sellPost.details', [slug(optional(@$item->sellPost)->title), optional(@$item->sellPost)->id]);
                return '<a href="' . $route . '">' . optional($item->sellPost)->title . '</a>';
            })
            ->addColumn('payment', function ($item) {
                return currencyPosition($item->price);
            })
            ->addColumn('seller_get', function ($item) {
                $extra = null;
                if (0 < $item->admin_amount) {
                    $extra = '<span class="badge bg-soft-danger text-danger ms-1">
                     ' . currencyPosition($item->admin_amount) . ' Charges</span>';
                }
                return currencyPosition($item->seller_amount) . $extra;
            })
            ->addColumn('seller', function ($item) {
                $url = route('admin.user.edit', optional($item->sellPost)->user_id);

                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                            <div class="flex-shrink-0">
                                ' . optional(optional($item->sellPost)->user)->profilePicture() . '
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->user?->fullname . '</h5>
                                <span class="fs-6 text-body">' . $item->user?->username . '</span>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('buyer', function ($item) {
                $url = route('admin.user.edit', $item->user_id);

                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                            <div class="flex-shrink-0">
                                ' . optional($item->user)->profilePicture() . '
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->user?->fullname . '</h5>
                                <span class="fs-6 text-body">' . $item->user?->username . '</span>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('status', function ($item) {
                if ($item->payment_release == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Released') . '
                  </span>';

                } elseif ($item->payment_release == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Upcoming') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Hold') . '
                  </span>';
                }
            })
            ->addColumn('payment_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {

                $resourceJson = htmlspecialchars(json_encode($item->sellPost->credential), ENT_QUOTES, 'UTF-8');

                if ($item->payment_release == 0) {
                    $btnName = 'Hold Payment';
                    $icon = 'fa-light fa-lock dropdown-item-icon';
                    $modalTarget = '#hold-modal';
                    $class = 'holdBtn';
                } elseif ($item->payment_release == 2) {
                    $btnName = 'Unhold Payment';
                    $icon = 'fa-light fa-unlock dropdown-item-icon';
                    $modalTarget = '#unhold-modal';
                    $class = 'unholdBtn';
                }


                $html = '<div class="btn-group" role="group">
                      <a href="#" class="btn btn-white btn-sm edit_button" data-bs-toggle="modal" data-bs-target="#myModal"
                                        data-info=\'' . $resourceJson . '\'>
                        <i class="fal fa-eye me-1"></i> ' . trans('Credentials') . '
                      </a>';
                if (in_array($item->payment_release, [0, 2])) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="javascript:void(0)" class="dropdown-item ' . $class . '" data-resource="' . $item->id . '"
                            data-bs-target="' . $modalTarget . '" data-bs-toggle="modal">
                            <i class="' . $icon . '"></i> ' . trans($btnName) . '
                        </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['trx', 'title', 'payment', 'seller_get', 'seller', 'buyer', 'status', 'payment_at', 'action'])
            ->make(true);
    }

    public function paymentHold(Request $request)
    {
        $hold = SellPostPayment::findOrFail($request->id);
        $hold->payment_release = 2;
        $hold->save();

        return back()->with('success', 'Update Successfully');
    }

    public function paymentUnhold(Request $request)
    {
        $hold = SellPostPayment::findOrFail($request->id);
        $hold->payment_release = 0;
        $hold->save();

        return back()->with('success', 'Update Successfully');
    }

}
PK     x\F  F  1  Http/Controllers/Admin/Module/TopUpController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\TopUpStoreRequest;
use App\Models\Category;
use App\Models\TopUp;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TopUpController extends Controller
{
    use Upload;

    public function topUpList(Request $request)
    {
        $data['topUps'] = collect(TopUp::when(isset($request->category_id), function ($query) use ($request) {
            $query->where('category_id', $request->category_id);
        })
            ->selectRaw('COUNT(id) AS totalTopUp')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeTopUp')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveTopUp')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayTopUp')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthTopUp')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthTopUpPercentage')
            ->get()
            ->toArray())->collapse();

        $data['category_id'] = $request->category_id ?? null;
        return view('admin.topUp.index', $data);
    }

    public function topUpListSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $categoryId = $request->category_id;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $topUps = TopUp::with(['category'])->orderBy('sort_by', 'ASC')
            ->withCount('activeServices')
            ->when(isset($categoryId), function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('region', 'LIKE', "%{$search}%")
                        ->orWhereHas('category', function ($categoryQuery) use ($search) {
                            $categoryQuery->where('name', 'LIKE', "%{$search}%");
                        });
                });
            });
        return DataTables::of($topUps)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image->preview_driver ?? null, $item->image->preview ?? null);
                return '<a class="d-flex align-items-center me-2">
                            <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                              </div>
                            <div class="flex-shrink-0">
                                <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                <p class="text-hover-primary mb-0">' . $item->region . '</p>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('active_service', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_services_count) . '</span>';
            })
            ->addColumn('instant_delivery', function ($item) {
                if ($item->instant_delivery == 1) {
                    return '<span class="badge bg-soft-primary text-primary">' . trans('Yes') . '</span>';

                } else {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('No') . '</span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="' . $item->category?->icon . '"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.topUpStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.topUpStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.topUpDelete', $item->id);
                $edit = route('admin.topUpEdit', $item->id);
                $service = route('admin.topUpService.list') . '?top_up_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $service . '" class="dropdown-item">
                            <i class="fas fa-dice dropdown-item-icon"></i> ' . trans("Service List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_service', 'instant_delivery', 'status', 'category', 'created_at', 'action'])
            ->make(true);
    }

    public function topUpStore(TopUpStoreRequest $request)
    {
        if ($request->method() == 'GET') {
            $data['categories'] = Category::active()->type('top_up')->sort()->get();
            return view('admin.topUp.create', $data);
        } elseif ($request->method() == 'POST') {
            try {
                $topUp = new TopUp();
                $fillData = $request->except('_token');
                $orderFields = [
                    'field_value', 'field_placeholder', 'field_note',
                    'field_type', 'field_option_name', 'field_option_value'
                ];

                $fillData = $this->processOrderFields($fillData, $orderFields);
                $fillData['image'] = $this->processImages($fillData);

                $topUp->fill($fillData)->save();

                return back()->with('success', 'Top Up Created Successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function topUpStatusChange(Request $request)
    {
        $topUp = TopUp::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $topUp->status = 1;
            } else {
                $topUp->status = 0;
            }
            $topUp->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function topUpSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            TopUp::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function topUpDelete($id)
    {
        try {
            $topUp = TopUp::findOrFail($id);
            $images = [
                ['driver' => $topUp->image->image_driver ?? null, 'path' => $topUp->image->image ?? null],
                ['driver' => $topUp->image->preview_driver ?? null, 'path' => $topUp->image->preview ?? null],
                ['driver' => $topUp->image->banner_driver ?? null, 'path' => $topUp->image->banner ?? null],
            ];
            foreach ($images as $image) {
                $this->fileDelete($image['driver'], $image['path']);
            }
            $topUp->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function topUpEdit(TopUpStoreRequest $request, $id)
    {
        $topUp = TopUp::FindOrFail($id);
        if ($request->method() == 'GET') {
            $categories = Category::active()->type('top_up')->sort()->get();
            return view('admin.topUp.edit', compact('topUp', 'categories'));
        } elseif ($request->method() == 'POST') {
            try {
                $fillData = $request->except('_token');
                $orderFields = [
                    'field_value', 'field_placeholder', 'field_note',
                    'field_type', 'field_option_name', 'field_option_value'
                ];

                $fillData = $this->processOrderFields($fillData, $orderFields);
                $fillData['image'] = $this->processImages($fillData, $topUp);

                $topUp->fill($fillData)->save();

                return back()->with('success', 'Top Up has been updated successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUp::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $images = [
                    ['driver' => $query->image->image_driver ?? null, 'path' => $query->image->image ?? null],
                    ['driver' => $query->image->preview_driver ?? null, 'path' => $query->image->preview ?? null],
                    ['driver' => $query->image->banner_driver ?? null, 'path' => $query->image->banner ?? null],
                ];
                foreach ($images as $image) {
                    $this->fileDelete($image['driver'], $image['path']);
                }
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Top Up has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUp::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Top Up has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    private function processOrderFields($fillData, $orderFields)
    {
        foreach ($orderFields as $field) {
            if (!empty($fillData[$field])) {
                foreach ($fillData[$field] as $key => $fieldNames) {
                    if ($field === 'field_option_name' || $field === 'field_option_value') {
                        $fillData = $this->processOptionFields($fillData, $field, $fieldNames, $key);
                    } else {
                        foreach ($fieldNames as $fieldValue) {
                            $fillData['order_information'][$key][$field] = $fieldValue;
                            if ($field == 'field_value') {
                                $fillData['order_information'][$key]['field_name'] = title2snake($fieldValue);
                            }
                        }
                    }
                }
            }
        }

        return $fillData;
    }

    private function processOptionFields($fillData, $field, $fieldNames, $key)
    {
        if (!empty($fieldNames[0])) {
            if ($field === 'field_option_name') {
                $fillData['optionNames'][$key] = $fieldNames;
            } else {
                $optionNames = isset($fillData['optionNames'][$key]) ? $fillData['optionNames'][$key] : [];
                foreach ($fieldNames as $i => $fieldValue) {
                    if (isset($optionNames[$i])) {
                        $fillData['order_information'][$key]['option'][$optionNames[$i]] = $fieldValue;
                    }
                }
            }
        }

        return $fillData;
    }

    private function processImages($fillData, $topUP = null)
    {

        $images = [
            'image' => $fillData['image'] ?? null,
            'preview' => $fillData['preview_image'] ?? null,
        ];

        $imageData = [];
        foreach ($images as $key => $image) {
            if ($image) {
                $uploadedImage = $this->uploadImage($image, $key, $topUP);
                if ($uploadedImage) {
                    $imageData[$key] = $uploadedImage['path'];
                    $imageData[$key . '_driver'] = $uploadedImage['driver'];
                }
            } else {
                $imageData[$key] = $topUP->image->{$key} ?? null;
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null;
            }
        }

        return $imageData;
    }

    private function uploadImage($image, $key, $topUP = null)
    {
        try {
            return $this->fileUpload(
                $image,
                config('filelocation.topUp.path'),
                null,
                config('filelocation.topUp.' . $key . '_size'),
                'webp',
                60,
                $topUP->image->{$key} ?? null,
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null,

            );
        } catch (\Exception $e) {
            return null;
        }
    }
}
PK     x\b9z<  z<  5  Http/Controllers/Admin/Module/CardOrderController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Traits\MakeOrder;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CardOrderController extends Controller
{
    use Notify, MakeOrder;

    public function list(Request $request)
    {
        $status = -1;
        if ($request->type == 'pending') {
            $status = 3;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = collect(Order::payment()->type('card')->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS completeOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS completeOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS refundOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS refundOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayOrder')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayOrderPercentage')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->get()
            ->toArray())->collapse();

        $data['status'] = $status;
        return view('admin.card.order.index', $data);
    }

    public function listSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterService = $request->service;
        $status = $request->type;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::with(['user:id,firstname,lastname,username,image,image_driver', 'gateway:id,name',
         'orderDetails','orderDetails.detailable.card:id,name'])
            ->payment()->type('card')->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterService), function ($query) use ($filterService) {
                $query->whereHas('orderDetails', function ($qq) use ($filterService) {
                    $qq->where('name', 'LIKE', '%' . $filterService . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                })
                    ->orWhereHas('user', function ($query) use ($search) {
                        $query->where('firstname', 'LIKE', "%$search%")
                            ->orWhere('lastname', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('card', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 3) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending (stock-short)') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderCard.complete');
                $cancel = route('admin.orderCard.cancel');
                $view = route('admin.orderCard.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 3) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date','card', 'total_amount', 'payment_method', 'user', 'status', 'action'])
            ->make(true);
    }

    public function view(Request $request)
    {
        $data['order'] = Order::with(['orderDetails',
            'user:id,firstname,lastname,email,phone_code,phone,image_driver,image,balance', 'gateway:id,name'])
            ->where('utr', $request->orderId)->firstOrFail();

        $data['userTotalOrderCount'] = Order::type('card')->where('user_id', $data['order']->user_id)->count();
        return view('admin.card.order.view', $data);
    }

    public function complete(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('card')
            ->where('status', 3)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 1;
            $order->save();

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 1;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=complete',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'CARD_ORDER_COMPLETE', $params);
            $this->userPushNotification($order->user, 'CARD_ORDER_COMPLETE', $params, $action);
            $this->userFirebasePushNotification($order->user, 'CARD_ORDER_COMPLETE', $params);

            return back()->with('success', 'Order has been completed');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('card')
            ->where('status', 3)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 2;
            $order->save();

            $order->user->balance += $order->amount;
            $order->user->save();

            $this->newTransaction($order->user_id, $order->amount, 'Order Refund For Card', '+', $order->id, Order::class);

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 2;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=refund',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'CARD_ORDER_CANCEL', $params);
            $this->userPushNotification($order->user, 'CARD_ORDER_CANCEL', $params, $action);
            $this->userFirebasePushNotification($order->user, 'CARD_ORDER_CANCEL', $params);

            return back()->with('success', 'Order has been canceled');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function codeSend(Request $request)
    {
        if (!$request->orderDetailsId) {
            return back()->with('error', 'Something went wrong. Please try again');
        }

        if (!$request->passcode) {
            return back()->with('error', 'Passcode is required');
        }

        $passcodes = array_filter($request->passcode);

        $orderDetail = OrderDetail::select(['id', 'user_id', 'order_id', 'name', 'qty', 'stock_short', 'status', 'card_codes'])
            ->with(['order:id,status,utr', 'user'])->findOrFail($request->orderDetailsId);

        try {
            $stock_short = max(0, $orderDetail->qty - count($passcodes));

            $orderDetail->card_codes = $passcodes;
            $orderDetail->stock_short = $stock_short;
            $orderDetail->status = ($stock_short == 0) ? 1 : 3;
            $orderDetail->save();

            $isStockShortExits = OrderDetail::where('order_id', $orderDetail->order_id)->where('status', 3)->exists();

            if (!$isStockShortExits) {
                $orderDetail->order->status = 1;
                $orderDetail->order->save();
            }

            $params = [
                'order_id' => $orderDetail->order?->utr,
                'service_name' => $orderDetail->name ?? null,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=all',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($orderDetail->user, 'CARD_CODE_SEND', $params);
            $this->userPushNotification($orderDetail->user, 'CARD_CODE_SEND', $params, $action);
            $this->userFirebasePushNotification($orderDetail->user, 'CARD_CODE_SEND', $params);

            return back()->with('success', 'Code has been send');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     x\@5]    4  Http/Controllers/Admin/Module/CampaignController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Campaign;
use App\Models\CardService;
use App\Models\TopUpService;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CampaignController extends Controller
{
    public function view()
    {
        $data['campaign'] = Campaign::firstOrNew();

        $data['topUpServices'] = TopUpService::select(['id', 'name', 'image', 'image_driver', 'status', 'sort_by', 'is_offered'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get();

        $data['cardServices'] = CardService::select(['id', 'name', 'image', 'image_driver', 'status', 'sort_by', 'is_offered'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get();

        return view('admin.campaign.view', $data);
    }

    public function getTopUpService(Request $request)
    {
        $offeredTopUpServices = TopUpService::whereIn('id', $request->selectedIds)->where('status', 1)
            ->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->price = $query->campaign_data->price ?? $query->price;
                $query->discount = $query->campaign_data->discount ?? $query->discount;
                $query->discount_type = $query->campaign_data->discount_type ?? $query->discount_type;
                $query->max_sell = $query->campaign_data->max_sell ?? $query->max_sell;

                return $query;
            });
        return response()->json(['status' => true, 'offerServices' => $offeredTopUpServices]);
    }

    public function getCardService(Request $request)
    {
        $offeredCardServices = CardService::whereIn('id', $request->selectedIds)->where('status', 1)
            ->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->price = $query->campaign_data->price ?? $query->price;
                $query->discount = $query->campaign_data->discount ?? $query->discount;
                $query->discount_type = $query->campaign_data->discount_type ?? $query->discount_type;
                $query->max_sell = $query->campaign_data->max_sell ?? $query->max_sell;

                return $query;
            });
        return response()->json(['status' => true, 'offerServices' => $offeredCardServices]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'date' => 'required',
        ]);

        $filterDate = explode('to', $request->date);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $campaign = Campaign::firstOrNew();
        $campaign->name = $request->name;
        $campaign->start_date = Carbon::parse($startDate);
        $campaign->end_date = Carbon::parse($endDate);
        $campaign->status = $request->status;
        $campaign->save();

        //Top Up
        $allTopUpServices = TopUpService::where('status', 1)->get();

        $topUpServicesToOffer = $allTopUpServices->whereIn('id', $request->topups);
        $topUpServicesNotOffered = $allTopUpServices->whereNotIn('id', $request->topups);

        TopUpService::whereIn('id', $topUpServicesNotOffered->pluck('id'))->update(['is_offered' => 0]);

        foreach ($topUpServicesToOffer as $service) {
            $this->campaignDataStore($service, $request->topup_price[$service->id], $request->topup_discount[$service->id],
                $request->topup_discount_type[$service->id], $request->topup_max_sell[$service->id]);

            $service->is_offered = 1;
            $service->save();
        }

        //Card
        $allCardServices = CardService::where('status', 1)->get();

        $cardServicesToOffer = $allCardServices->whereIn('id', $request->cards);
        $cardServicesNotOffered = $allCardServices->whereNotIn('id', $request->cards);

        CardService::whereIn('id', $cardServicesNotOffered->pluck('id'))->update(['is_offered' => 0]);

        foreach ($cardServicesToOffer as $service) {
            $this->campaignDataStore($service, $request->card_price[$service->id], $request->card_discount[$service->id],
                $request->card_discount_type[$service->id], $request->card_max_sell[$service->id]);

            $service->is_offered = 1;
            $service->save();
        }

        return back()->with('success', 'Campaign Updated Successfully');
    }


    protected function campaignDataStore($service, $price, $discount, $discount_type, $max_sell): void
    {
        $campaignData = [
            'price' => $price,
            'discount' => $discount,
            'discount_type' => $discount_type,
            'max_sell' => $max_sell,
        ];

        $service->campaign_data = $campaignData;
        $service->save();
    }
}
PK     x\И"  "  2  Http/Controllers/Admin/Module/ReviewController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Review;
use App\Models\TopUp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class ReviewController extends Controller
{
    public function list()
    {
        $data['reviews'] = collect(Review::selectRaw('COUNT(id) AS totalReview')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeReview')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveReview')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayReview')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthReview')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthReviewPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.review.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterRating = $request->filterRating;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $cards = Review::with(['user:id,firstname,lastname,username,image,image_driver','reviewable'])->latest()
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->whereHas('reviewable', function ($reviewQuery) use ($filterName) {
                    $reviewQuery->where('name', 'LIKE', '%' . $filterName . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(isset($filterRating), function ($query) use ($filterRating) {
                if ($filterRating != "all") {
                    return $query->where('rating', $filterRating);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('comment', 'LIKE', "%{$search}%")
                        ->orWhereHas('reviewable', function ($reviewQuery) use ($search) {
                            $reviewQuery->where('name', 'LIKE', "%{$search}%");
                        })
                        ->orWhereHas('user', function ($reviewerQuery) use ($search) {
                            $reviewerQuery->where('firstname', 'LIKE', "%{$search}%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%");
                        });
                });
            });
        return DataTables::of($cards)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('game', function ($item) {
                if ($item->reviewable_type == TopUp::class) {
                    $url = route('admin.topUpEdit', $item->reviewable_id);
                } elseif ($item->reviewable_type == Card::class) {
                    $url = route('admin.card.edit', $item->reviewable_id);
                }
                $img = getFile($item->reviewable->image->preview_driver ?? null, $item->reviewable->image->preview ?? null);
                return '<a class="d-flex align-items-center" href="' . $url . '">
                    <div class="avatar">
                      <img class="avatar-img" src="' . $img . '" alt="Image Description">
                    </div>
                    <div class="flex-grow-1 ms-3">
                      <span class="card-title h5 text-dark text-inherit">' . $item->reviewable?->name . '</span>
                    </div>
                  </a>
                 ';

            })
            ->addColumn('reviewer', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('review', function ($item) {
                $star = asset('assets/admin/img/star.svg');
                $starRating = '';
                for ($i = 0; $i < $item->rating; $i++) {
                    $starRating .= '<img src="' . $star . '" alt="Review rating" width="14">';
                }
                return '<div class="text-wrap" style="width: 18rem;">
                          <div class="d-flex gap-1 mb-2">
                            ' . $starRating . '
                          </div>
                         <p>' . $item->comment . '</p>
                        </div>';
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Publish') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Hold') . '
                  </span>';
                }
            })
            ->rawColumns(['checkbox', 'game', 'reviewer', 'review', 'date', 'status'])
            ->make(true);
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Review::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Review has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Review::whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Review has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }
}
PK     x\?"  "  ;  Http/Controllers/Admin/Module/CardServiceCodeController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\CodeExport;
use App\Http\Controllers\Controller;
use App\Imports\CodeImport;
use App\Models\CardService;
use App\Models\Code;
use App\Traits\Sample;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class CardServiceCodeController extends Controller
{
    use Sample;

    public function list(Request $request)
    {
        $data['service'] = CardService::with('card')->select(['id', 'name', 'card_id'])->findOrFail($request->service_id);
        $data['services'] = CardService::select(['id', 'name', 'card_id', 'sort_by', 'created_at'])
            ->where('card_id', $data['service']->card_id)->orderBy('sort_by', 'ASC')->get();
        $data['codes'] = collect(Code::serviceWise(CardService::class, $request->service_id)
            ->selectRaw('COUNT(id) AS totalCode')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCode')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCodePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCode')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCodePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCode')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCodePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCode')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCodePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.card.code.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $codes = Code::serviceWise(CardService::class, $request->service_id)->orderBy('id', 'desc')->when(isset($filterName), function ($query) use ($filterName) {
            return $query->where('passcode', 'LIKE', '%' . $filterName . '%');
        })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('passcode', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($codes)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('passcode', function ($item) {
                $element = "referralsKeyCode" . $item->id;
                return '<div class="input-group input-group-sm input-group-merge table-input-group">
                        <input id="' . $element . '" type="text" class="form-control" readonly value="' . $item->passcode . '">
                        <a class="js-clipboard input-group-append input-group-text" onclick="copyFunction(\'' . $element . '\')" href="javascript:void(0)" title="Copy to clipboard">
                            <i id="referralsKeyCodeIcon' . $item->id . '" class="bi-clipboard"></i>
                        </a>
                    </div>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->rawColumns(['checkbox', 'passcode', 'status', 'created_at'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $service = CardService::select(['id'])->findOrFail($request->service_id);
        try {
            if ($request->passcode && 0 < count($request->passcode)) {
                foreach ($request->passcode as $code) {
                    Code::firstOrCreate([
                        'codeable_type' => CardService::class,
                        'codeable_id' => $service->id,
                        'passcode' => $code
                    ]);
                }
            }
            return back()->with('success', 'Code Added Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Code::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Code has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Code::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Code Status has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function export(Request $request)
    {
        try {
            $data = collect([
                'codeable_id' => $request->service_id,
                'codeable_type' => CardService::class,
            ])->all();
            return Excel::download(new CodeExport($data), 'codes.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function sample()
    {
        try {
            return $this->csvSampleDownload('code.csv', 'code-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function import(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        CardService::select(['id'])->findOrFail($request->service_id);

        try {
            $data = collect([
                'codeable_id' => $request->service_id,
                'codeable_type' => CardService::class,
            ])->all();
            Excel::import(new CodeImport($data), $request->file('importFile'));
            return back()->with('success', 'Codes Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\Ǝ5  5  6  Http/Controllers/Admin/Module/TopUpOrderController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Traits\MakeOrder;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TopUpOrderController extends Controller
{
    use Notify, MakeOrder;

    public function list(Request $request)
    {
        $status = -1;
        if ($request->type == 'pending') {
            $status = 0;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = collect(Order::payment()->type('topup')->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS completeOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS completeOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS refundOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS refundOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayOrder')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayOrderPercentage')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->get()
            ->toArray())->collapse();

        $data['status'] = $status;
        return view('admin.topUp.order.index', $data);
    }

    public function listSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterService = $request->service;
        $status = $request->type;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::with(['user:id,firstname,lastname,username,image,image_driver',
            'gateway:id,name', 'orderDetails', 'orderDetails.detailable.topUp:id,name'])
            ->payment()->type('topup')->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterService), function ($query) use ($filterService) {
                $query->whereHas('orderDetails', function ($qq) use ($filterService) {
                    $qq->where('name', 'LIKE', '%' . $filterService . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                })
                    ->orWhereHas('user', function ($query) use ($search) {
                        $query->where('firstname', 'LIKE', "%$search%")
                            ->orWhere('lastname', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('top_up', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderTopUp.complete');
                $cancel = route('admin.orderTopUp.cancel');
                $view = route('admin.orderTopUp.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 0) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'top_up', 'total_amount', 'payment_method', 'user', 'status', 'action'])
            ->make(true);
    }

    public function view(Request $request)
    {
        $data['order'] = Order::with(['orderDetails',
            'user:id,firstname,lastname,email,phone_code,phone,image_driver,image,balance', 'gateway:id,name'])
            ->where('utr', $request->orderId)->firstOrFail();

        $data['userTotalOrderCount'] = Order::type('topup')->where('user_id', $data['order']->user_id)->count();
        return view('admin.topUp.order.view', $data);
    }

    public function complete(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('topup')
            ->where('status', 0)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 1;
            $order->save();

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 1;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
                'service_name' => $order->orderDetails[0]->name ?? null,
            ];

            $action = [
                "link" => route('user.topUpOrder') . '?type=complete',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'TOP_UP_ORDER_COMPLETE', $params);
            $this->userPushNotification($order->user, 'TOP_UP_ORDER_COMPLETE', $params, $action);
            $this->userFirebasePushNotification($order->user, 'TOP_UP_ORDER_COMPLETE', $params);

            return back()->with('success', 'Order has been completed');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('topup')
            ->where('status', 0)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 2;
            $order->save();

            $order->user->balance += $order->amount;
            $order->user->save();

            $this->newTransaction($order->user_id, $order->amount, 'Order Refund For TopUp', '+', $order->id, Order::class);

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 2;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
                'service_name' => $order->orderDetails[0]->name ?? null,
            ];

            $action = [
                "link" => route('user.topUpOrder') . '?type=refund',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'TOP_UP_ORDER_CANCEL', $params);
            $this->userPushNotification($order->user, 'TOP_UP_ORDER_CANCEL', $params, $action);
            $this->userFirebasePushNotification($order->user, 'TOP_UP_ORDER_CANCEL', $params);

            return back()->with('success', 'Order has been canceled');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     x\W,'  '  4  Http/Controllers/Admin/Module/CategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryStoreRequest;
use App\Http\Requests\CategoryUpdateRequest;
use App\Models\Category;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CategoryController extends Controller
{
    use Upload;

    public function categoryList(Request $request)
    {
        if (!in_array($request->type, ['top_up', 'card'])) {
            return back()->with('error', 'Something went wrong');
        }
        $data['categories'] = collect(Category::selectRaw('COUNT(id) AS totalCategory')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCategory')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCategory')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCategory')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCategory')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCategoryPercentage')
            ->where('type', $request->type)
            ->get()
            ->toArray())->collapse();
        $data['pageTitle'] = snake2Title($request->type) . ' Category';
        $data['type'] = $request->type;
        return view('admin.category.index', $data);
    }


    public function categoryListSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $categories = Category::orderBy('sort_by', 'ASC')->where('type', $request->type)
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($categories)
            ->addColumn('name', function ($item) {
                return '<a class="d-flex align-items-center me-2">
                                <div class="list-group-item">
                                    <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                  </div>
                                <i class="' . $item->icon . '"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('active_service', function ($item) use ($request) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_children) . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.categoryStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.categoryStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.categoryDelete', $item->id);
                if ($item->type == 'top_up') {
                    $childRoute = route('admin.topUpList') . '?category_id=' . $item->id;
                } elseif ($item->type == 'card') {
                    $childRoute = route('admin.card.list') . '?category_id=' . $item->id;
                } elseif ($item->type == 'game') {
                    $childRoute = route('admin.game.list') . '?category_id=' . $item->id;
                }
                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                       data-name="' . $item->name . '" data-icon="' . $item->icon . '"
                       data-route="' . route('admin.categoryEdit', $item->id) . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item" href="' . $childRoute . '">
                          <i class="fal fa-eye dropdown-item-icon"></i> ' . trans("Child") . '
                       </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['name', 'active_service', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function categoryCreate(CategoryStoreRequest $request)
    {
        if (!in_array($request->type, ['top_up', 'card'])) {
            return back()->with('error', 'Something went wrong');
        }
        try {
            $category = new Category();
            $fillData = $request->except('_token');
            $category->fill($fillData)->save();
            return back()->with('success', 'Category Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit(CategoryUpdateRequest $request, $id)
    {
        $category = Category::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $category->fill($fillData)->save();
            return back()->with('success', 'Category Updated Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryStatusChange(Request $request)
    {
        $category = Category::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $category->status = 1;
            } else {
                $category->status = 0;
            }
            $category->save();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
        return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
    }

    public function categorySort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Category::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function categoryDelete($id)
    {
        try {
            Category::findOrFail($id)->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\SY6g  g  <  Http/Controllers/Admin/Module/SellPostCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\SellPost;
use App\Models\Language;
use App\Models\SellPostCategory;
use App\Models\SellPostCategoryDetail;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Traits\Notify;
use App\Traits\SellPostTrait;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SellPostCategoryController extends Controller
{
    use Upload, Notify, SellPostTrait;

    public function category()
    {
        $manageCategory = SellPostCategory::with(['details'])->withCount('activePost')->latest()->get();
        return view('admin.sellPostCategory.categoryList', compact('manageCategory'));
    }

    public function categoryCreate()
    {
        $languages = Language::all();
        return view('admin.sellPostCategory.categoryCreate', compact('languages'));
    }

    public function categoryStore(Request $request, $language)
    {

        $purifiedData = $request->all();
        DB::beginTransaction();
        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
                'image' => 'required|mimes:jpg,jpeg,png',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'image.required' => 'Image is required',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $category = new SellPostCategory();

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if ($request->has('status')) {
                $category->status = $request->status;
            }

            if ($request->has('sell_charge')) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->hasFile('image')) {
                try {
                    $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp');
                    $category->image = $imageUp['path'];
                    $category->image_driver = $imageUp['driver'];
                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            $category->save();

            $category->details()->create([
                'language_id' => $language,
                'name' => $purifiedData["name"][$language],
            ]);

            DB::commit();

            return back()->with('success', 'Category Successfully Saved');
        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit($id)
    {
        $languages = Language::all();
        $categoryDetails = SellPostCategoryDetail::with('sellPostCategory')->where('sell_post_category_id', $id)->get()->groupBy('language_id');
        return view('admin.sellPostCategory.categoryEdit', compact('languages', 'categoryDetails', 'id'));
    }


    public function categoryUpdate(Request $request, $id, $language_id)
    {
        $purifiedData = $request->all();
        DB::beginTransaction();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            $category = SellPostCategory::findOrFail($id);

            if ($request->hasFile('image')) {
                $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp', null, $category->image, $category->image_driver);
                $category->image = $imageUp['path'];
                $category->image_driver = $imageUp['driver'];
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if (isset($purifiedData['sell_charge'])) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->has('status')) {
                $category->status = $request->status;
            }
            $category->save();

            $category->details()->updateOrCreate([
                'language_id' => $language_id
            ],
                [
                    'name' => $purifiedData["name"][$language_id],
                ]
            );
            DB::commit();

            return back()->with('success', 'Category Successfully Updated');

        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function statusSellMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Category.');
            return response()->json(['error' => 1]);
        } else {
            SellPostCategory::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been active');
            return response()->json(['success' => 1]);
        }
    }

    public function categoryDelete($id)
    {
        $categoryData = SellPostCategory::findOrFail($id);
        if (0 < $categoryData->post->count()) {
            session()->flash('warning', 'This Category has a lot of post');
            return back();
        }

        $this->fileDelete($categoryData->image_driver, $categoryData->image);

        $categoryData->delete();
        return back()->with('success', 'Category has been deleted');
    }

    public function sellList($status = null)
    {
        $data['value'] = $this->getValueByStatus($status);
        abort_if(!isset($data['value']), 404);

        $data['sellPost'] = collect(SellPost::selectRaw('COUNT(id) AS totalPost')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvalPost')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvalPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingPost')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS holdPost')
            ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS holdPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 5 THEN id END) AS hardPost')
            ->selectRaw('(COUNT(CASE WHEN status = 5 THEN id END) / COUNT(id)) * 100 AS hardPostPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.sellPostList.index', $data);
    }

    public function sellListSearch(Request $request, $status = null)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterUser = $request->user;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $posts = SellPost::status($status)->latest()
            ->has('user')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('title', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterUser), function ($query) use ($filterUser) {
                $query->whereHas('user', function ($qq) use ($filterUser) {
                    $qq->where('firstname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('lastname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('username', 'LIKE', '%' . $filterUser . '%');
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('title', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('category.details', function ($qq) use ($search) {
                            $qq->where('name', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($posts)
            ->addColumn('title', function ($item) {
                $extra = null;
                if ($item->payment_status) {
                    $extra = '<span class="badge bg-success">' . trans('Sold') . '</span>
                             <span class="badge bg-secondary">' . $item->sellPostPayment?->transaction . '</span>';
                }
                return $item->title . ' ' . $extra;

            })
            ->addColumn('category', function ($item) {
                return optional($item->category)->details->name??null;
            })
            ->addColumn('price', function ($item) {
                return '<h5>' . currencyPosition($item->price) . '</h5>';
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.edit", $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('status', function ($item) {
                return $item->statusMessage;
            })
            ->addColumn('date_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                $conversion = route('admin.sellPost.offer', [$item->id]);
                $edit = route('admin.sell.details', $item->id);

                $html = '<div class="btn-group sortable" role="group">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $conversion . '" class="dropdown-item">
                            <i class="fas fa-comments dropdown-item-icon"></i> ' . trans("Conversation") . '
                        </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['title', 'category', 'price', 'user', 'status', 'date_at', 'action'])
            ->make(true);
    }

    public function sellDetails($id)
    {
        $data['activity'] = ActivityLog::whereSell_post_id($id)->with('activityable:id,username,image,image_driver')->orderBy('id', 'desc')->get();

        $data['category'] = SellPostCategory::with('details')->whereStatus(1)->get();
        $data['sellPost'] = SellPost::findOrFail($id);

        return view('admin.sellPostList.edit', $data);
    }

    public function SellUpdate(Request $request, $id)
    {
        $purifiedData = $request->all();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'title' => 'required|max:40',
                'price' => 'required',
                'details' => 'required',
            ];
            $message = [
                'title.required' => 'Title field is required',
                'price.required' => 'Price field is required',
                'details.required' => 'Details field is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }


            $gameSell = SellPost::findOrFail($id);
            $gameSell->category_id = $request->category;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }

            $collection = collect($request);
            $reqField = [];
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }


            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqFieldSpecification[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }


            $images = array();
            if ($request->hasFile('image')) {

                try {
                    $gameImage = $purifiedData['image'];
                    $gamesellDriver = $gameSell->image_driver ?? 'local';
                    $oldImages = $request->oldImage ?? [];
                    $images = [];
                    $imagesDriver = [];

                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver[] = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $key => $imageOld) {
                            if ($imageOld == 'changed') {
                                $this->fileDelete($gamesellDriver, $oldImages[$key]);
                                unset($oldImages[$key]);
                            }
                        }
                    }

                    $mergedImages = array_merge($oldImages, $images);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver['0'];

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            if (isset($purifiedData['title'])) {
                $gameSell->title = $request->title;
            }
            if (isset($purifiedData['price'])) {
                $gameSell->price = $request->price;
            }

            if (isset($purifiedData['credential'])) {
                $gameSell->credential = $request->credential;
            }

            if (isset($purifiedData['details'])) {
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['status'])) {
                $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
            }


            $gameSell->save();


            return back()->with('success', 'Successfully Updated');
        } catch (\Exception$e) {

            return back();
        }
    }

    public function sellAction(Request $request)
    {
        DB::beginTransaction();
        try {
            $gameSell = SellPost::findOrFail($request->sell_post_id);
            $gameSell->status = $request->status;
            $gameSell->save();


            $title = $gameSell->activityTitle;
            $admin = Auth::user();

            $activity = new ActivityLog();
            $activity->title = $title;
            $activity->sell_post_id = $request->sell_post_id;
            $activity->description = $request->comments;

            $admin->activities()->save($activity);
            DB::commit();

            $user = $gameSell->user;
            $msg = [
                'title' => $gameSell->title,
                'status' => $title,
                'comments' => $request->comments

            ];
            $action = [
                "link" => route('sellPost.details', [@$gameSell->title, $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_APPROVE', $msg, $action);

            $this->sendMailSms($user, 'SELL_APPROVE', [
                'title' => $gameSell->title,
                'status' => $title,
                'short_comment' => $request->comments
            ]);

            return back()->with('success', 'Update Successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function SellDelete($id, $imgDelete)
    {
        $images = [];
        $galleryImage = SellPost::findOrFail($id);
        $old_images = $galleryImage->image;

        if (!empty($old_images)) {
            foreach ($old_images as $file) {
                $newString = Str::replaceFirst('sellingPost/', '', $file);
                if ($newString == $imgDelete) {
                    $this->fileDelete($galleryImage->image_driver, $file);
                } else {
                    $images[] = $file;
                }
            }
        }
        $galleryImage->image = $images;
        $galleryImage->save();
        return back()->with('success', 'Image has been deleted');
    }

    public function sellPostOffer($sellPostId)
    {
        $sellPostOffer = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($sellPostId)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $offer = null;
        if (0 < count($sellPostOffer)) {
            $offer = $sellPostOffer->first();

            if (!$offer->uuid) {
                $offer->uuid = Str::uuid();
                $offer->save();
            }

            return redirect()->route('admin.sellPost.conversation', $offer->uuid);
        } else {
            $offer = null;
        }


        $data['sellPostOffer'] = $sellPostOffer;
        $data['offer'] = $offer;
        return view('admin.sellPostList.offerList', $data);
    }

    public function conversation($uuid)
    {
        $offer = SellPostOffer::with(['user', 'lastMessage'])->where('uuid', $uuid)
            ->firstOrFail();

        $data['sellPostOffer'] = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($offer->sell_post_id)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $data['persons'] = SellPostChat::where([
            'offer_id' => $offer->id,
            'sell_post_id' => $offer->sell_post_id
        ])
            ->with('chatable')
            ->get()->pluck('chatable')->unique('chatable');

        $data['offer'] = $offer;

        return view('admin.sellPostList.offerList', $data);
    }

}
PK     x\Fև    5  Http/Controllers/Admin/GoogleApiSettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GoogleSheetApi;
use Illuminate\Http\Request;
use App\Traits\Upload;

class GoogleApiSettingController extends Controller
{
    use Upload;
    public function googleAPISetting()
    {
        return view('admin.control_panel.google_api_setting');
    }

    public function googleAPICredentialUpload(Request $request)
    {

        $googleSheetCredential = GoogleSheetApi::firstOrFail();

        $request->validate([
              'credential' => 'nullable',
        ]);

        if ($request->hasFile('credential')) {
            try {
                $file = $this->fileUpload($request->credential, config('filelocation.googleTranslateCredential.path'), config('filesystems.default'));
                if ($file) {
                    $file_credential = $file['path'];
                    $file_driver = 'local';
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'File could not be uploaded.');
            }
        }

        $response = $googleSheetCredential->update([
            'api_credential_file' => $file_credential,
            'file_driver' => $file_driver,
        ]);

        if (!$response){
            throw  new \Exception('Something went wrong');
        }


        return back()->with('success', 'File uploaded successfully.');

    }
}
PK     x\X=% =% *  Http/Controllers/Admin/UsersController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\UserAllRecordDeleteJob;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Gateway;
use App\Models\Investment;
use App\Models\Language;
use App\Models\Order;
use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Referral;
use App\Models\ReferralBonus;
use App\Models\Transaction;
use App\Models\User;
use App\Models\UserKyc;
use App\Models\UserLogin;
use App\Models\UserTracking;
use App\Models\UserWallet;
use App\Rules\PhoneLength;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Stevebauman\Purify\Facades\Purify;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Validation\Rule;
use App\Traits\Upload;
use App\Traits\Notify;
use Exception;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;

class UsersController extends Controller
{
    use Upload, Notify;

    public function index(Request $request)
    {
        $data['reqVal'] = $request->status;
        $data['basic'] = basicControl();
        $userRecord = \Cache::get('userRecord');
        if (!$userRecord) {
            $userRecord = User::withTrashed()->selectRaw('COUNT(id) AS totalUserWithTrashed')
                ->selectRaw('COUNT(CASE WHEN deleted_at IS NULL THEN id END) AS totalUser')
                ->selectRaw('(COUNT(CASE WHEN deleted_at IS NULL THEN id END) / COUNT(id)) * 100 AS totalUserPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeUser')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeUserPercentage')
                ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS todayJoin')
                ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) / COUNT(id)) * 100 AS todayJoinPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS deactivateUser')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS deactivateUserPercentage')
                ->get()
                ->toArray();
            \Cache::put('userRecord', $userRecord);
        }
        $data['languages'] = Language::all();
        $data['allCountry'] = config('country');
        return view('admin.user_management.list', $data, compact('userRecord'));

    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterStatus = $request->filterStatus;
        $filterName = $request->filterName;
        $filterEmailVerification = $request->filterEmailVerification;
        $filterSMSVerification = $request->filterSMSVerification;
        $filterTwoFaSecurity = $request->filterTwoFaVerification;
        $reqVal = $request->reqVal;

        $users = User::query()->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('email', 'LIKE', "%{$search}%")
                    ->orWhere('username', 'LIKE', "%{$search}%")
                    ->orWhere('firstname', 'LIKE', "%{$search}%")
                    ->orWhere('lastname', 'LIKE', "%{$search}%")
                    ->orWhere('phone', 'LIKE', "%{$search}%");
            })
            ->when(isset($filterName) && !empty($filterName), function ($query) use ($filterName) {
                return $query->where('username', 'LIKE', "%{$filterName}%")
                    ->orWhere('firstname', 'LIKE', "%{$filterName}%")
                    ->orWhere('lastname', 'LIKE', "%{$filterName}%");
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == 'all') {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterEmailVerification) && !empty($filterEmailVerification), function ($query) use ($filterEmailVerification) {
                return $query->where('email_verification', $filterEmailVerification);
            })
            ->when(isset($filterSMSVerification) && !empty($filterSMSVerification), function ($query) use ($filterSMSVerification) {
                return $query->where('sms_verification', $filterSMSVerification);
            })
            ->when(isset($filterTwoFaSecurity) && !empty($filterTwoFaSecurity), function ($query) use ($filterTwoFaSecurity) {
                return $query->where('two_fa_verify', $filterTwoFaSecurity);
            })
            ->when(isset($reqVal) && !empty($reqVal), function ($query) use ($reqVal) {
                if ($reqVal == 'activeUser') {
                    return $query->where('status', 1);
                } elseif ($reqVal == 'blocked') {
                    return $query->where('status', 0);
                } elseif ($reqVal == 'emailUnVerify') {
                    return $query->where('email_verification', 0);
                } elseif ($reqVal == 'smsUnVerify') {
                    return $query->where('sms_verification', 0);
                } elseif ($reqVal == 'all') {
                    return $query->where('status', '!=', null);
                }
            });

        return DataTables::of($users)
            ->addColumn('checkbox', function ($item) {
                return ' <input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', $item->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->firstname . ' ' . $item->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . $item->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('email-phone', function ($item) {
                return '<span class="d-block h5 mb-0">' . $item->email . '</span>
                            <span class="d-block fs-5">' . $item->phone . '</span>';
            })
            ->addColumn('balance', function ($item) {
                return currencyPosition($item->balance);
            })
            ->addColumn('country', function ($item) {
                return $item->country ?? 'N/A';
            })
            ->addColumn('email_v', function ($item) {
                if ($item->email_verification == 1) {
                    return '<span class="badge bg-soft-primary text-primary">
                    <span class="legend-indicator bg-primary"></span>' . trans('Verified') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Unverified') . '
                  </span>';
                }
            })
            ->addColumn('sms_v', function ($item) {
                if ($item->sms_verification == 1) {
                    return '<span class="badge bg-soft-info text-info">
                    <span class="legend-indicator bg-info"></span>' . trans('Verified') . '
                  </span>';
                } else {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg--warning"></span>' . trans('Unverified') . '
                  </span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Inactive') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $editUrl = route('admin.user.edit', $item->id);
                $viewProfile = route('admin.user.view.profile', $item->id);
                return '<div class="btn-group" role="group">
                      <a href="' . $editUrl . '" class="btn btn-white btn-sm edit_user_btn">
                        <i class="bi-pencil-fill me-1"></i> ' . trans("Edit") . '
                      </a>
                    <div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                       <a class="dropdown-item" href="' . $viewProfile . '">
                          <i class="bi-eye-fill dropdown-item-icon"></i> ' . trans("View Profile") . '
                        </a>
                          <a class="dropdown-item" href="' . route('admin.send.email', $item->id) . '"> <i
                                class="bi-envelope dropdown-item-icon"></i> ' . trans("Send Mail") . ' </a>
                          <a class="dropdown-item loginAccount" href="javascript:void(0)"
                           data-route="' . route('admin.login.as.user', $item->id) . '"
                           data-bs-toggle="modal" data-bs-target="#loginAsUserModal">
                            <i class="bi bi-box-arrow-in-right dropdown-item-icon"></i>
                           ' . trans("Login As User") . '
                        </a>
                         <a class="dropdown-item addBalance" href="javascript:void(0)"
                           data-route="' . route('admin.user.update.balance', $item->id) . '"
                           data-balance="' . currencyPosition($item->balance) . '"
                           data-bs-toggle="modal" data-bs-target="#addBalanceModal">
                            <i class="bi bi-cash-coin dropdown-item-icon"></i>
                            ' . trans("Manage Balance") . '
                        </a>
                      </div>
                    </div>
                  </div>';
            })->rawColumns(['action', 'checkbox', 'name', 'email_v', 'sms_v', 'balance', 'email-phone', 'status'])
            ->make(true);
    }


    public function deleteMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select User.');
            return response()->json(['error' => 1]);
        } else {
            User::whereIn('id', $request->strIds)->get()->map(function ($user) {
                UserAllRecordDeleteJob::dispatch($user);
                $user->forceDelete();
            });
            session()->flash('success', 'User has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function userEdit($id)
    {
        $data['languages'] = Language::all();
        $data['basicControl'] = basicControl();
        $data['allCountry'] = config('country');
        $data['userLoginInfo'] = UserLogin::where('user_id', $id)->orderBy('id', 'desc')->limit(5)->get();

        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.edit_user', $data);
    }

    public function userUpdate(Request $request, $id)
    {
        $languages = Language::all()->map(function ($item) {
            return $item->id;
        });

        $request->validate([
            'firstName' => 'required|string|min:2|max:100',
            'lastName' => 'required|string|min:2|max:100',
            'phone' => 'required|unique:users,phone,' . $id,
            'country' => 'required|string|min:2|max:100',
            'city' => 'required|string|min:2|max:100',
            'state' => 'required|string|min:2|max:100',
            'addressOne' => 'required|string|min:2|max:100',
            'addressTwo' => 'nullable|string|min:2',
            'zipCode' => 'required|string|min:2|max:100',
            'status' => 'nullable|integer|in:0,1',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif',
            'language_id' => Rule::in($languages),
        ]);


        $user = User::where('id', $id)->firstOr(function () {
            throw new \Exception('User not found!');
        });
        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.profileImage.path'), null, null, 'webp', 70, $user->image, $user->image_driver);
                if ($image) {
                    $profileImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $user->update([
                'firstname' => $request->firstName,
                'lastname' => $request->lastName,
                'phone' => $request->phone,
                'language_id' => $request->language_id,
                'address_one' => $request->addressOne,
                'address_two' => $request->addressTwo,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zipCode,
                'country' => $request->country,
                'image' => $profileImage ?? $user->image,
                'image_driver' => $driver ?? $user->image_driver,
                'status' => $request->status
            ]);

            return back()->with('success', 'Basic Information Updated Successfully.');
        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }


    public function passwordUpdate(Request $request, $id)
    {
        $request->validate([
            'newPassword' => 'required|min:5|same:confirmNewPassword',
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'password' => bcrypt($request->newPassword)
            ]);

            return back()->with('success', 'Password Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function EmailUpdate(Request $request, $id)
    {
        $request->validate([
            'new_email' => 'required|email:rfc,dns|unique:users,email,' . $id
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'email' => $request->new_email,
            ]);

            return back()->with('success', 'Email Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }

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


        $request->validate([
            'username' => 'required|unique:users,username,' . $id
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'username' => $request->username,
            ]);

            return back()->with('success', 'Username Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }

    public function updateBalanceUpdate(Request $request, $id)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1'
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });
            $basic = basicControl();

            if ($request->balance_operation == 1) {

                $user->balance += $request->amount;
                $user->save();

                $fund = new Deposit();
                $fund->user_id = $user->id;
                $fund->percentage_charge = 0;
                $fund->fixed_charge = 0;
                $fund->charge = 0;
                $fund->amount = $request->amount;
                $fund->status = 1;
                $fund->save();

                $transaction = new Transaction();
                $transaction->user_id = $user->id;
                $transaction->amount_in_base = $request->amount;
                $transaction->trx_type = '+';
                $transaction->remarks = 'Add Balance to wallet';
                $transaction->trx_id = $fund->trx_id;
                $fund->transactional()->save($transaction);

                $msg = [
                    'amount' => currencyPosition($fund->amount),
                    'main_balance' => currencyPosition($user->balance),
                    'transaction' => $transaction->trx_id
                ];

                $action = [
                    "link" => '#',
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $firebaseAction = '#';
                $this->userFirebasePushNotification($user, 'ADD_BALANCE', $msg, $firebaseAction);
                $this->userPushNotification($user, 'ADD_BALANCE', $msg, $action);
                $this->sendMailSms($user, 'ADD_BALANCE', $msg);

                return redirect()->route('admin.user.transaction', $user->id)->with('success', 'Balance Updated Successfully.');

            } else {

                if ($request->amount > $user->balance) {
                    return back()->with('error', 'Insufficient Balance to deducted.');
                }
                $user->balance -= $request->amount;
                $user->save();

                $transaction = new Transaction();
                $transaction->user_id = $user->id;
                $transaction->amount_in_base = $request->amount;
                $transaction->trx_type = '-';
                $transaction->trx_id = Str::random(12);
                $transaction->remarks = 'Deduction Balance from wallet';
                $transaction->save();

                $msg = [
                    'amount' => currencyPosition($request->amount),
                    'main_balance' => currencyPosition($user->balance),
                    'transaction' => $transaction->trx_id
                ];
                $action = [
                    "link" => route('user.transaction'),
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $firebaseAction = route('user.transaction');
                $this->userFirebasePushNotification($user, 'DEDUCTED_BALANCE', $msg, $firebaseAction);
                $this->userPushNotification($user, 'DEDUCTED_BALANCE', $msg, $action);
                $this->sendMailSms($user, 'DEDUCTED_BALANCE', $msg);

                return redirect()->route('admin.user.transaction', $user->id)->with('success', 'Balance Updated Successfully.');

            }

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }


    public function preferencesUpdate(Request $request, $id)
    {
        $languages = Language::all()->map(function ($item) {
            return $item->id;
        });

        $request->validate([
            'language_id' => Rule::in($languages),
            'time_zone' => 'required|string|min:1|max:100',
            'email_verification' => 'nullable|integer|in:0,1',
            'sms_verification' => 'nullable|integer|in:0,1',
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'language_id' => $request->language_id,
                'time_zone' => $request->time_zone,
                'email_verification' => $request->email_verification,
                'sms_verification' => $request->sms_verification,
            ]);

            return back()->with('success', 'Preferences Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }


    }

    public function userTwoFaUpdate(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });
            $user->update([
                'two_fa_verify' => ($request->two_fa_security == 1) ? 0 : 1
            ]);

            return back()->with('success', 'Two Fa Security Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userDelete(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            UserAllRecordDeleteJob::dispatch($user);
            $user->forceDelete();
            return redirect()->route('admin.users')->with('success', 'User Account Deleted Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userAdd()
    {
        $data['allCountry'] = config('country');
        return view('admin.user_management.add_user', $data);
    }

    public function userStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstName' => 'required|string|min:2|max:255',
            'lastName' => 'required|string|min:2|max:255',
            'username' => 'required|string|unique:users,username|min:2|max:255',
            'password' => 'required|min:2|max:255',
            'email' => 'required|email:rfc,dns|unique:users,email|min:2|max:255',
            'phone' => ['required', 'string', 'unique:users,phone'],
            'phone_code' => 'required|max:15',
            'country_code' => 'nullable|string|max:80',
            'country' => 'required|string|max:80',
            'city' => 'required|string|min:2|max:255',
            'state' => 'nullable|string|min:2|max:255',
            'zipCode' => 'nullable|string|min:2|max:20',
            'addressOne' => 'required|string|min:2',
            'addressTwo' => 'nullable|string|min:2',
            'status' => 'nullable|integer|in:0,1',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.profileImage.path'), null, null, 'webp', 60);
                if ($image) {
                    $profileImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $response = User::create([
                'firstname' => $request->firstName,
                'lastname' => $request->lastName,
                'username' => $request->username,
                'password' => Hash::make($request->password),
                'email' => $request->email,
                'phone' => $request->phone,
                'phone_code' => $request->phone_code,
                'country' => $request->country,
                'country_code' => $request->country_code,
                'language_id' => $request->language_id,
                'address_one' => $request->addressOne,
                'address_two' => $request->addressTwo,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zipCode,
                'image' => $profileImage ?? null,
                'image_driver' => $driver ?? 'local',
                'status' => $request->status
            ]);

            if (!$response) {
                throw new Exception('Something went wrong, Please try again.');
            }

            return redirect()->route('admin.user.create.success.message', $response->id)->with('success', 'User created successfully');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userCreateSuccessMessage($id)
    {
        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.components.user_add_success_message', $data);
    }

    public function userViewProfile($id)
    {
        $data['user'] = User::findOrFail($id);
        $data['basic'] = basicControl();
        $data['transactions'] = Transaction::with('user')->where('user_id', $id)->orderBy('id', 'DESC')
            ->limit(5)->get();

        $data['paymentLog'] = Deposit::with('user', 'gateway')->where('user_id', $id)
            ->where('status', '!=', 0)
            ->orderBy('id', 'DESC')
            ->limit(5)
            ->get();

        $data['withDraws'] = Payout::with('user')->where('user_id', $id)
            ->where('status', '!=', 0)
            ->orderBy('id', 'DESC')
            ->limit(5)->get();

        return view('admin.user_management.user_view_profile', $data);
    }

    public function transaction($id)
    {
        $user = User::findOrFail($id);
        return view('admin.user_management.transactions', compact('user'));
    }

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

        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;

        $filterTransactionId = $request->filterTransactionID;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = Transaction::with('user')
            ->has('user')
            ->where('user_id', $id)
            ->when(!empty($search), function ($query) use ($search) {
                $query->where(function ($innerQuery) use ($search) {
                    $innerQuery->where('trx_id', 'LIKE', "%{$search}%")
                        ->orWhere('remarks', 'LIKE', "%{$search}%");
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->orderBy('id', 'DESC')
            ->get();


        return DataTables::of($transaction)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('base_amount', function ($item) {
                $statusClass = $item->trx_type == '+' ? 'text-success' : 'text-danger';
                return "<h6 class='mb-0 $statusClass '>" . $item->trx_type . ' ' . currencyPosition($item->amount_in_base) . "</h6>";

            })
            ->addColumn('remarks', function ($item) {
                return $item->remarks;
            })
            ->addColumn('date-time', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->rawColumns(['amount', 'charge', 'no', 'trx', 'base_amount', 'remarks', 'date-time'])
            ->make(true);
    }


    public function payment($id)
    {
        $data['user'] = User::findOrFail($id);
        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.user_management.payment_log', $data);
    }

    public function userPaymentSearch(Request $request, $id)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $deposit = Deposit::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'gateway:id,name,image,driver'])
            ->whereHas('user')
            ->whereHas('gateway')
            ->orderBy('id', 'desc')
            ->where('user_id', $id)
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($deposit)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';


            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                if (optional($item->gateway)->id > 999) {
                    $icon = $item->status == 2 ? 'pencil' : 'eye';
                    return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                 data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
                } else {
                    return '-';
                }
            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);

    }

    public function payout($id)
    {
        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.payout_log', $data);
    }

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

        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $payout = Payout::with('user')
            ->has('user')
            ->where('user_id', $id)
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('trx_id', 'LIKE', "%$search%")
                        ->orWhereHas('method', function ($q) use ($search) {
                            $q->where('name', 'LIKE', "%$search%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($payout)
            ->addColumn('No', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . currencyPosition($item->amount, $item->payout_currency_code) . "</h6>";

            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . currencyPosition($item->charge, $item->payout_currency_code) . "</span>";
            })
            ->addColumn('net-amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base_currency) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->addColumn('action', function ($item) use ($basicControl) {

                $details = null;
                if ($item->information) {
                    $information = json_decode($item->information, true);
                    if (is_array($information)) {
                        $details = [];
                        foreach ($information as $k => $v) {
                            if ($v['type'] == "file") {
                                $details[kebab2Title($k)] = [
                                    'type' => $v['type'],
                                    'field_name' => $v['field_name'],
                                    'field_value' => getFile(config('filesystems.default'), @$v['field_value'] ?? $v['field_name']),
                                ];
                            } else {
                                $details[kebab2Title($k)] = [
                                    'type' => $v['type'],
                                    'field_name' => $v['field_name'],
                                    'field_value' => @$v['field_value'] ?? $v['field_name']
                                ];
                            }
                        }
                    }
                }

                $icon = $item->status == 1 ? 'pencil' : 'eye';

                $statusColor = '';
                $statusText = '';
                if ($item->status == 0) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 1) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 2) {
                    $statusColor = 'badge bg-soft-success text-success';
                    $statusText = 'Success';
                } else if ($item->status == 3) {
                    $statusColor = 'badge bg-soft-danger text-danger';
                    $statusText = 'Cancel';
                }

                return "<button type='button' class='btn btn-white btn-sm edit_btn'
                data-id='$item->id'
                data-info='" . json_encode($details) . "'
                data-sendername='" . $item->user->firstname . ' ' . $item->user->lastname . "'
                data-transactionid='$item->trx_id'
                data-feedback='$item->feedback'
                data-amount=' " . currencyPosition($item->amount) . "'
                data-datepaid='" . dateTime($item->created_at, 'd M Y') . "'
                data-status='$item->status'

                 data-status_color='$statusColor'
                data-status_text='$statusText'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payout.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
            })
            ->rawColumns(['amount', 'charge', 'net-amount', 'status', 'action'])
            ->make(true);
    }

    public function userKyc($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.user_kyc', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function KycSearch(Request $request, $id)
    {
        $filterVerificationType = $request->filterVerificationType;
        $filterStatus = $request->filterStatus;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = UserKyc::with('user')
            ->where('user_id', $id)
            ->orderBy('id', 'DESC')
            ->when(!empty($filterVerificationType), function ($query) use ($filterVerificationType) {
                return $query->where('kyc_type', $filterVerificationType);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->get();

        return DataTables::of($transaction)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('verification type', function ($item) {
                return $item->kyc_type;

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Verified') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Rejected') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);

            })
            ->addColumn('action', function ($item) {
                $url = route('admin.kyc.view', $item->id);
                return '<a href="' . $url . '" class="btn btn-white btn-sm">
                    <i class="bi-eye-fill me-1"></i>
                  </a>';
            })
            ->rawColumns(['name', 'status', 'action'])
            ->make(true);
    }


    public function loginAsUser($id)
    {
        Auth::guard('web')->loginUsingId($id);
        return redirect()->route('user.dashboard');
    }


    public function blockProfile(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('No User found.');
            });

            $user->status = $user->status == 1 ? 0 : 1;
            $user->save();


            $message = $user->status == 1 ? 'Unblock Profile Successfully' : 'Block Profile Successfully';

            return back()->with('success', $message);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function mailAllUser()
    {
        return view('admin.user_management.mail_all_user');
    }

    public function sendEmail($id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('No User found.');
            });
            return view('admin.user_management.send_mail_form', compact('user'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function sendMailUser(Request $request, $id = null)
    {

        $request->validate([
            'subject' => 'required|min:5',
            'description' => 'required|min:10',
        ]);

        try {

            $user = User::where('id', $id)->first();

            $subject = $request->subject;
            $template = $request->description;

            if (isset($user)) {
                Mail::to($user)->send(new SendMail(basicControl()->sender_email, $subject, $template));
            } else {
                $users = User::where('email_verification', 1)->where('status', 1)->get();
                foreach ($users as $user) {
                    Mail::to($user)->queue(new SendMail(basicControl()->sender_email, $subject, $template));
                }
            }

            return back()->with('success', 'Email Sent Successfully');

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function countData()
    {
        $userData = User::selectRaw(
            'COUNT(*) as totalUsers,
             SUM(status = 1) as totalActiveUsers,
             SUM(status = 0) as totalBannedUsers,
             SUM(email_verification = 0) as totalEmailUnverified,
             SUM(sms_verification = 0) as totalSmsUnverified'
        )->first();

        $data['total_users'] = $userData->totalUsers ?? 0;
        $data['active_users'] = $userData->totalActiveUsers ?? 0;
        $data['banned_users'] = $userData->totalBannedUsers ?? 0;
        $data['email_unverified'] = $userData->totalEmailUnverified ?? 0;
        $data['sms_unverified'] = $userData->totalSmsUnverified ?? 0;

        return $data;
    }

    public function userActivity()
    {
        return view('admin.user_management.user_activity');
    }

    public function userActivitySearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->filterName;
        $filterIp = $request->filterIp;
        $filterOther = $request->filterOther;

        $activities = UserTracking::query()->has('user')->with('user')->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('ip', 'LIKE', "%{$search}%")
                    ->orWhere('country_name', 'LIKE', "%{$search}%")
                    ->orWhere('region_name', 'LIKE', "%{$search}%")
                    ->orWhere('city_name', 'LIKE', "%{$search}%")
                    ->orWhere('latitude', 'LIKE', "%{$search}%")
                    ->orWhere('longitude', 'LIKE', "%{$search}%")
                    ->orWhere('timezone', 'LIKE', "%{$search}%")
                    ->orWhere('browser', 'LIKE', "%{$search}%")
                    ->orWhere('os', 'LIKE', "%{$search}%")
                    ->orWhere('device', 'LIKE', "%{$search}%")
                    ->orWhere('remark', 'LIKE', "%{$search}%")
                    ->orWhereHas('user', function ($qq) use ($search) {
                        $qq->where('firstname', 'LIKE', "%{$search}%")
                            ->orWhere('lastname', 'LIKE', "%{$search}%")
                            ->orWhere('username', 'LIKE', "%{$search}%");
                    });
            })
            ->when(isset($filterName) && !empty($filterName), function ($query) use ($filterName) {
                return $query->whereHas('user', function ($qq) use ($filterName) {
                    $qq->where('username', 'LIKE', "%{$filterName}%")
                        ->orWhere('firstname', 'LIKE', "%{$filterName}%")
                        ->orWhere('lastname', 'LIKE', "%{$filterName}%");
                });
            })
            ->when(isset($filterIp) && !empty($filterIp), function ($query) use ($filterIp) {
                return $query->where('ip', $filterIp);
            })
            ->when(isset($filterOther) && !empty($filterOther), function ($query) use ($filterOther) {
                return $query->where('country_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('region_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('city_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('latitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('longitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('timezone', 'LIKE', "%{$filterOther}%")
                    ->orWhere('browser', 'LIKE', "%{$filterOther}%")
                    ->orWhere('os', 'LIKE', "%{$filterOther}%")
                    ->orWhere('device', 'LIKE', "%{$filterOther}%")
                    ->orWhere('remark', 'LIKE', "%{$filterOther}%");
            });

        return DataTables::of($activities)
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user->firstname . ' ' . $item->user->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('ip', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->ip . '</span>';
            })
            ->addColumn('city', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->city_name . ' (' . $item->region_name . ') </span>
                  <span class="d-block fs-5">' . $item->country_name . ' (' . $item->country_code . ') </span > ';
            })
            ->addColumn('lat_lon', function ($item) {
                return $item->latitude . ' - ' . $item->longitude;
            })
            ->addColumn('timezone', function ($item) {
                return $item->timezone;
            })
            ->addColumn('browser', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->browser . ' (' . $item->os . ') </span>
                  <span class="d-block fs-5">' . $item->device . ' </span > ';
            })
            ->addColumn('remark', function ($item) {
                return $item->remark;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->rawColumns(['user', 'ip', 'city', 'lat_lon', 'timezone', 'browser', 'remark', 'date'])
            ->make(true);
    }

    public function topUpOrder($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.topUp-order', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function topUpOrderSearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $status = $request->type ?? '-1';
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::payment()->type('topup')
            ->with(['gateway:id,name', 'orderDetails', 'orderDetails.detailable.topUp:id,name'])
            ->where('user_id', $id)->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                });
            });

        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('top_up', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderTopUp.complete');
                $cancel = route('admin.orderTopUp.cancel');
                $view = route('admin.orderTopUp.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 0) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'top_up', 'total_amount', 'payment_method', 'status', 'action'])
            ->make(true);
    }

    public function cardOrder($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.card-order', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function cardOrderSearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $status = $request->type ?? '-1';
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::payment()->type('card')
            ->with(['gateway:id,name', 'orderDetails', 'orderDetails.detailable.card:id,name'])
            ->where('user_id', $id)->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('card', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 3) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending (stock-short)') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderCard.complete');
                $cancel = route('admin.orderCard.cancel');
                $view = route('admin.orderCard.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 3) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'card', 'total_amount', 'payment_method', 'status', 'action'])
            ->make(true);
    }

    public function specificActivity($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.specific_activity', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function specificActivitySearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterIp = $request->filterIp;
        $filterOther = $request->filterOther;

        $activities = UserTracking::query()->where('user_id', $id)->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('ip', 'LIKE', "%{$search}%")
                    ->orWhere('country_name', 'LIKE', "%{$search}%")
                    ->orWhere('region_name', 'LIKE', "%{$search}%")
                    ->orWhere('city_name', 'LIKE', "%{$search}%")
                    ->orWhere('latitude', 'LIKE', "%{$search}%")
                    ->orWhere('longitude', 'LIKE', "%{$search}%")
                    ->orWhere('timezone', 'LIKE', "%{$search}%")
                    ->orWhere('browser', 'LIKE', "%{$search}%")
                    ->orWhere('os', 'LIKE', "%{$search}%")
                    ->orWhere('device', 'LIKE', "%{$search}%")
                    ->orWhere('remark', 'LIKE', "%{$search}%");
            })
            ->when(isset($filterIp) && !empty($filterIp), function ($query) use ($filterIp) {
                return $query->where('ip', $filterIp);
            })
            ->when(isset($filterOther) && !empty($filterOther), function ($query) use ($filterOther) {
                return $query->where('country_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('region_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('city_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('latitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('longitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('timezone', 'LIKE', "%{$filterOther}%")
                    ->orWhere('browser', 'LIKE', "%{$filterOther}%")
                    ->orWhere('os', 'LIKE', "%{$filterOther}%")
                    ->orWhere('device', 'LIKE', "%{$filterOther}%")
                    ->orWhere('remark', 'LIKE', "%{$filterOther}%");
            });

        return DataTables::of($activities)
            ->addColumn('ip', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->ip . '</span>';
            })
            ->addColumn('city', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->city_name . ' (' . $item->region_name . ') </span>
                  <span class="d-block fs-5">' . $item->country_name . ' (' . $item->country_code . ') </span > ';
            })
            ->addColumn('browser', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->browser . ' (' . $item->os . ') </span>
                  <span class="d-block fs-5">' . $item->device . ' </span > ';
            })
            ->addColumn('remark', function ($item) {
                return $item->remark;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->rawColumns(['ip', 'city', 'browser', 'remark', 'date'])
            ->make(true);
    }
}
PK     x\Yʎ
  
  .  Http/Controllers/Admin/SmsConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ManualSmsConfig;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;


class SmsConfigController extends Controller
{
    public function index()
    {
        $data['smsControlMethod'] = config('SMSConfig.SMS');
        $data['smsMethodDefault'] = config('SMSConfig.default');
        return view('admin.sms_controls.index', $data);
    }

    public function smsConfigEdit($method)
    {
        try {
            $basicControl = basicControl();
            $smsControlMethod = config('SMSConfig.SMS');
            $smsMethodParameters = $smsControlMethod[$method] ?? null;

            if ($method == "manual") {
                $manualSMSMethod = ManualSmsConfig::first();
                return view('admin.sms_controls.manual_sms_config', compact("method", "manualSMSMethod", "basicControl"));
            }

            return view('admin.sms_controls.sms_config', compact('smsMethodParameters', 'method', 'basicControl'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function smsConfigUpdate(Request $request, $method)
    {
        $rules = [
            'method_name' => 'required|string|min:3|max:100',
            'sms_notification' => 'nullable|integer|min:0|in:0,1',
            'sms_verification' => 'nullable|integer|min:0|in:0,1',
        ];

        $smsControlMethod = config('SMSConfig.SMS');
        $smsMethodParameters = $smsControlMethod[$method] ?? null;

        foreach ($request->except('_token', '_method', 'method_name', 'sms_notification', 'sms_verification') as $key => $value) {
            if (array_key_exists($key, $smsMethodParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }

        $request->validate($rules);

        try {
            $env = [
                'TWILIO_ACCOUNT_SID' => $request->twilio_account_sid ?? $smsControlMethod['twilio']['twilio_account_sid']['value'],
                'TWILIO_AUTH_TOKEN' => $request->twilio_auth_token ?? $smsControlMethod['twilio']['twilio_auth_token']['value'],
                'TWILIO_PHONE_NUMBER' => $request->twilio_phone_number ?? $smsControlMethod['twilio']['twilio_phone_number']['value'],
                'INFOBIP_API_KEY' => $request->infobip_api_key ?? $smsControlMethod['infobip']['infobip_api_key']['value'],
                'INFOBIP_URL_BASE_PATH' => $request->infobip_url_base_path ?? $smsControlMethod['infobip']['infobip_url_base_path']['value'],
                'PLIVO_ID' => $request->plivo_id ?? $smsControlMethod['plivo']['plivo_id']['value'],
                'PLIVO_AUTH_ID' => $request->plivo_auth_id ?? $smsControlMethod['plivo']['plivo_auth_id']['value'],
                'PLIVO_AUTH_TOKEN' => $request->plivo_auth_token ?? $smsControlMethod['plivo']['plivo_auth_token']['value'],
                'VONAGE_FROM' => "VONAGE_FROM",
                'VONAGE_API_KEY' => $request->vonage_api_key ?? $smsControlMethod['vonage']['vonage_api_key']['value'],
                'VONAGE_API_SECRET' => $request->vonage_api_secret ?? $smsControlMethod['vonage']['vonage_api_secret']['value'],
            ];

            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                'sms_notification' => $request->sms_notification,
                'sms_verification' => $request->sms_verification

            ]);

            return back()->with('success', 'SMS Configuration has been updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function manualSmsMethodUpdate(Request $request, $method)
    {

        $this->validate($request, [
            'actionMethod' => 'required|in:GET,POST',
            'actionUrl' => 'required|url',
            'headerDataKeys.*' => 'nullable|string|min:2|required_with:headerValue.*',
            'headerDataValues.*' => 'nullable|string|min:2|required_with:headerKey.*',
            'paramKeys.*' => 'nullable|string|min:2|required_with:paramValue.*',
            'paramValues.*' => 'nullable|string|min:2|required_with:paramKey.*',
            'formDataKeys.*' => 'nullable|string|min:2|required_with:formDataValue.*',
            'formDataValues.*' => 'nullable|string|min:2|required_with:formDataKey.*',
            'sms_notification' => 'nullable|integer|in:0,1',
            'sms_verification' => 'nullable|integer|in:0,1'
        ], [
            'min' => 'This field must be at least :min characters.',
            'string' => 'This field must be :string.',
            'required_with' => 'This field is requird',
        ]);

        $headerData = array_combine($request->headerDataKeys, $request->headerDataValues);
        $paramData = array_combine($request->paramKeys, $request->paramValues);
        $formData = array_combine($request->formDataKeys, $request->formDataValues);

        $headerData = (empty(array_filter($headerData))) ? null : json_encode(array_filter($headerData));
        $paramData = (empty(array_filter($paramData))) ? null : json_encode(array_filter($paramData));
        $formData = (empty(array_filter($formData))) ? null : json_encode(array_filter($formData));


        $smsControl = ManualSmsConfig::firstOrCreate(['id' => 1]);
        $smsControl->action_method = $request->actionMethod;
        $smsControl->action_url = $request->actionUrl;
        $smsControl->form_data = $formData;
        $smsControl->param_data = $paramData;
        $smsControl->header_data = $headerData;
        $smsControl->save();

        $basicControl = basicControl();
        $basicControl->sms_notification = $request->sms_notification;
        $basicControl->sms_verification = $request->sms_verification;
        $basicControl->save();

        return back()->with('success', 'SMS Configuration has been updated successfully.');
    }

    public function smsSetAsDefault($method)
    {
        try {
            $env = [
                'SMS_METHOD' => $method
            ];
            BasicService::setEnv($env);

            return back()->with('success', 'SMS method set as default successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\^r    0  Http/Controllers/Admin/EmailConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\sendTestMail;
use App\Models\NotificationTemplate;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Exception;

class EmailConfigController extends Controller
{
    public function emailControls()
    {
        $data['mailMethod'] = config('mailconfig');
        $data['mailMethodDefault'] = config('mail.default');
        return view('admin.email_controls.index', $data);
    }

    public function emailConfigEdit($method)
    {
        try {
            $data['basicControl'] = basicControl();
            $mailMethod = config('mailconfig');
            $mailParameters = $mailMethod[$method] ?? null;
            return view('admin.email_controls.email_config', $data, compact('mailParameters', 'method'));

        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function emailConfigUpdate(Request $request, $method)
    {
        $rules = [
            'sender_email' => 'required|email:rfc,dns',
            'email_method' => 'required|string',
            'email_notification' => 'nullable|integer|in:0,1',
            'email_verification' => 'nullable|integer|in:0,1',
        ];

        $mailMethod = config('mailconfig');
        $mailParameters = $mailMethod[$method] ?? null;

        foreach ($request->except('_token', '_method') as $key => $value) {
            if (array_key_exists($key, $mailParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }
        $request->validate($rules);

        try {
            $env = [
                'MAIL_FROM_ADDRESS' => $request->sender_email,
                'MAIL_HOST' => $request->mail_host ?? $mailMethod['SMTP']['mail_host']['value'],
                'MAIL_PORT' => $request->mail_port ?? $mailMethod['SMTP']['mail_port']['value'],
                'MAIL_USERNAME' => $request->mail_username ?? $mailMethod['SMTP']['mail_username']['value'],
                'MAIL_PASSWORD' => isset($request->mail_password) ? '"' . $request->mail_password . '"' : $mailMethod['SMTP']['mail_password']['value'],
                'MAILGUN_DOMAIN' => $request->mailgun_domain ?? $mailMethod['mailgun']['mailgun_domain']['value'],
                'MAILGUN_SECRET' => $request->mailgun_secret ?? $mailMethod['mailgun']['mailgun_secret']['value'],
                'POSTMARK_TOKEN' => $request->postmark_token ?? $mailMethod['postmark']['postmark_token']['value'],
                'AWS_ACCESS_KEY_ID' => $request->aws_secret_access_key ?? $mailMethod['SES']['aws_access_key_id']['value'],
                'AWS_SECRET_ACCESS_KEY' => $request->aws_default_region ?? $mailMethod['SES']['aws_secret_access_key']['value'],
                'AWS_DEFAULT_REGION' => $request->aws_default_region ?? $mailMethod['SES']['aws_default_region']['value'],
                'AWS_SESSION_TOKEN' => $request->aws_session_token ?? $mailMethod['SES']['aws_session_token']['value'],
                'MAILERSEND_API_KEY' => $request->mailersend_api_key ?? $mailMethod['mailersend']['mailersend_api_key']['value'],
                'SENDINBLUE_API_KEY' => $request->sendinblue_api_key ?? $mailMethod['sendinblue']['sendinblue_api_key']['value'],
                'SENDGRID_API_KEY' => $request->sendgrid_api_key ?? $mailMethod['sendgrid']['sendgrid_api_key']['value'],
                'MAILCHIMP_API_KEY' => $request->mailchimp_api_key ?? $mailMethod['mailchimp']['mailchimp_api_key']['value'],
            ];


            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                "email_notification" => $request->email_notification,
                "email_verification" => $request->email_verification,
                "sender_email" => $request->sender_email,
            ]);

            NotificationTemplate::get()->map(function ($item) use ($request){
                $item->email_from = $request->sender_email;
                $item->save();

            });

            return back()->with('success', 'Email Configuration has been updated successfully.');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function emailSetAsDefault(Request $request, $method)
    {
        try {
            $env = [
                'MAIL_MAILER' => $method
            ];
            BasicService::setEnv($env);

            return back()->with('success', 'Mail method set as default successfully.');
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }


    public function testEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email:rfc,dns',
        ]);

        $basic = basicControl();

        if ($basic->email_notification !== 1) {
            return back()->with('warning', 'Your email notification is disabled');
        }

        $email_from = $basic->sender_email;
        Mail::to($request->email)->send(new sendTestMail($email_from, "Test Email", "Your " . $_SERVER['SERVER_NAME'] . " email is working."));

        return back()->with('success', 'Email has been sent successfully.');
    }

}
PK     x\IZgg  g  5  Http/Controllers/Admin/SellPostCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\SellPost;
use App\Models\Language;
use App\Models\SellPostCategory;
use App\Models\SellPostCategoryDetail;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Traits\Notify;
use App\Traits\SellPostTrait;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SellPostCategoryController extends Controller
{
    use Upload, Notify, SellPostTrait;

    public function category()
    {
        $manageCategory = SellPostCategory::with(['details'])->withCount('activePost')->latest()->get();
        return view('admin.sellPostCategory.categoryList', compact('manageCategory'));
    }

    public function categoryCreate()
    {
        $languages = Language::all();
        return view('admin.sellPostCategory.categoryCreate', compact('languages'));
    }

    public function categoryStore(Request $request, $language)
    {

        $purifiedData = $request->all();
        DB::beginTransaction();
        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
                'image' => 'required|mimes:jpg,jpeg,png',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'image.required' => 'Image is required',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $category = new SellPostCategory();

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if ($request->has('status')) {
                $category->status = $request->status;
            }

            if ($request->has('sell_charge')) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->hasFile('image')) {
                try {
                    $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp');
                    $category->image = $imageUp['path'];
                    $category->image_driver = $imageUp['driver'];
                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            $category->save();

            $category->details()->create([
                'language_id' => $language,
                'name' => $purifiedData["name"][$language],
            ]);

            DB::commit();

            return back()->with('success', 'Category Successfully Saved');
        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit($id)
    {
        $languages = Language::all();
        $categoryDetails = SellPostCategoryDetail::with('sellPostCategory')->where('sell_post_category_id', $id)->get()->groupBy('language_id');
        return view('admin.sellPostCategory.categoryEdit', compact('languages', 'categoryDetails', 'id'));
    }


    public function categoryUpdate(Request $request, $id, $language_id)
    {
        $purifiedData = $request->all();
        DB::beginTransaction();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            $category = SellPostCategory::findOrFail($id);

            if ($request->hasFile('image')) {
                $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp', null, $category->image, $category->image_driver);
                $category->image = $imageUp['path'];
                $category->image_driver = $imageUp['driver'];
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if (isset($purifiedData['sell_charge'])) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->has('status')) {
                $category->status = $request->status;
            }
            $category->save();

            $category->details()->updateOrCreate([
                'language_id' => $language_id
            ],
                [
                    'name' => $purifiedData["name"][$language_id],
                ]
            );
            DB::commit();

            return back()->with('success', 'Category Successfully Updated');

        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function statusSellMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Category.');
            return response()->json(['error' => 1]);
        } else {
            SellPostCategory::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been active');
            return response()->json(['success' => 1]);
        }
    }

    public function categoryDelete($id)
    {
        $categoryData = SellPostCategory::findOrFail($id);
        if (0 < $categoryData->post->count()) {
            session()->flash('warning', 'This Category has a lot of post');
            return back();
        }

        $this->fileDelete($categoryData->image_driver, $categoryData->image);

        $categoryData->delete();
        return back()->with('success', 'Category has been deleted');
    }

    public function sellList($status = null)
    {
        $data['value'] = $this->getValueByStatus($status);
        abort_if(!isset($data['value']), 404);

        $data['sellPost'] = collect(SellPost::selectRaw('COUNT(id) AS totalPost')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvalPost')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvalPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingPost')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS holdPost')
            ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS holdPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 5 THEN id END) AS hardPost')
            ->selectRaw('(COUNT(CASE WHEN status = 5 THEN id END) / COUNT(id)) * 100 AS hardPostPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.sellPostList.index', $data);
    }

    public function sellListSearch(Request $request, $status = null)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterUser = $request->user;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $posts = SellPost::status($status)->latest()
            ->has('user')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('title', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterUser), function ($query) use ($filterUser) {
                $query->whereHas('user', function ($qq) use ($filterUser) {
                    $qq->where('firstname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('lastname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('username', 'LIKE', '%' . $filterUser . '%');
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('title', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('category.details', function ($qq) use ($search) {
                            $qq->where('name', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($posts)
            ->addColumn('title', function ($item) {
                $extra = null;
                if ($item->payment_status) {
                    $extra = '<span class="badge bg-success">' . trans('Sold') . '</span>
                             <span class="badge bg-secondary">' . $item->sellPostPayment?->transaction . '</span>';
                }
                return $item->title . ' ' . $extra;

            })
            ->addColumn('category', function ($item) {
                return optional($item->category)->details->name??null;
            })
            ->addColumn('price', function ($item) {
                return '<h5>' . currencyPosition($item->price) . '</h5>';
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.edit", $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('status', function ($item) {
                return $item->statusMessage;
            })
            ->addColumn('date_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                $conversion = route('admin.sellPost.offer', [$item->id]);
                $edit = route('admin.sell.details', $item->id);

                $html = '<div class="btn-group sortable" role="group">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $conversion . '" class="dropdown-item">
                            <i class="fas fa-comments dropdown-item-icon"></i> ' . trans("Conversation") . '
                        </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['title', 'category', 'price', 'user', 'status', 'date_at', 'action'])
            ->make(true);
    }

    public function sellDetails($id)
    {
        $data['activity'] = ActivityLog::whereSell_post_id($id)->with('activityable:id,username,image,image_driver')->orderBy('id', 'desc')->get();

        $data['category'] = SellPostCategory::with('details')->whereStatus(1)->get();
        $data['sellPost'] = SellPost::findOrFail($id);

        return view('admin.sellPostList.edit', $data);
    }

    public function SellUpdate(Request $request, $id)
    {
        $purifiedData = $request->all();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'title' => 'required|max:40',
                'price' => 'required',
                'details' => 'required',
            ];
            $message = [
                'title.required' => 'Title field is required',
                'price.required' => 'Price field is required',
                'details.required' => 'Details field is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }


            $gameSell = SellPost::findOrFail($id);
            $gameSell->category_id = $request->category;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }

            $collection = collect($request);
            $reqField = [];
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }


            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqFieldSpecification[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }


            $images = array();
            if ($request->hasFile('image')) {

                try {
                    $gameImage = $purifiedData['image'];
                    $gamesellDriver = $gameSell->image_driver ?? 'local';
                    $oldImages = $request->oldImage ?? [];
                    $images = [];
                    $imagesDriver = [];

                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver[] = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $key => $imageOld) {
                            if ($imageOld == 'changed') {
                                $this->fileDelete($gamesellDriver, $oldImages[$key]);
                                unset($oldImages[$key]);
                            }
                        }
                    }

                    $mergedImages = array_merge($oldImages, $images);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver['0'];

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            if (isset($purifiedData['title'])) {
                $gameSell->title = $request->title;
            }
            if (isset($purifiedData['price'])) {
                $gameSell->price = $request->price;
            }

            if (isset($purifiedData['credential'])) {
                $gameSell->credential = $request->credential;
            }

            if (isset($purifiedData['details'])) {
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['status'])) {
                $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
            }


            $gameSell->save();


            return back()->with('success', 'Successfully Updated');
        } catch (\Exception$e) {

            return back();
        }
    }

    public function sellAction(Request $request)
    {
        DB::beginTransaction();
        try {
            $gameSell = SellPost::findOrFail($request->sell_post_id);
            $gameSell->status = $request->status;
            $gameSell->save();


            $title = $gameSell->activityTitle;
            $admin = Auth::user();

            $activity = new ActivityLog();
            $activity->title = $title;
            $activity->sell_post_id = $request->sell_post_id;
            $activity->description = $request->comments;

            $admin->activities()->save($activity);
            DB::commit();

            $user = $gameSell->user;
            $msg = [
                'title' => $gameSell->title,
                'status' => $title,
                'comments' => $request->comments

            ];
            $action = [
                "link" => route('sellPost.details', [@$gameSell->title, $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_APPROVE', $msg, $action);

            $this->sendMailSms($user, 'SELL_APPROVE', [
                'title' => $gameSell->title,
                'status' => $title,
                'short_comment' => $request->comments
            ]);

            return back()->with('success', 'Update Successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function SellDelete($id, $imgDelete)
    {
        $images = [];
        $galleryImage = SellPost::findOrFail($id);
        $old_images = $galleryImage->image;

        if (!empty($old_images)) {
            foreach ($old_images as $file) {
                $newString = Str::replaceFirst('sellingPost/', '', $file);
                if ($newString == $imgDelete) {
                    $this->fileDelete($galleryImage->image_driver, $file);
                } else {
                    $images[] = $file;
                }
            }
        }
        $galleryImage->image = $images;
        $galleryImage->save();
        return back()->with('success', 'Image has been deleted');
    }

    public function sellPostOffer($sellPostId)
    {
        $sellPostOffer = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($sellPostId)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $offer = null;
        if (0 < count($sellPostOffer)) {
            $offer = $sellPostOffer->first();

            if (!$offer->uuid) {
                $offer->uuid = Str::uuid();
                $offer->save();
            }

            return redirect()->route('admin.sellPost.conversation', $offer->uuid);
        } else {
            $offer = null;
        }


        $data['sellPostOffer'] = $sellPostOffer;
        $data['offer'] = $offer;
        return view('admin.sellPostList.offerList', $data);
    }

    public function conversation($uuid)
    {
        $offer = SellPostOffer::with(['user', 'lastMessage'])->where('uuid', $uuid)
            ->firstOrFail();

        $data['sellPostOffer'] = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($offer->sell_post_id)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $data['persons'] = SellPostChat::where([
            'offer_id' => $offer->id,
            'sell_post_id' => $offer->sell_post_id
        ])
            ->with('chatable')
            ->get()->pluck('chatable')->unique('chatable');

        $data['offer'] = $offer;

        return view('admin.sellPostList.offerList', $data);
    }

}
PK     x\7<  <  1  Http/Controllers/Admin/PayoutMethodController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PayoutMethod;
use Facades\App\Services\CurrencyLayerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Exception;
use App\Traits\Upload;

class PayoutMethodController extends Controller
{
    use Upload;

    public function index()
    {
        $data['payoutMethods'] = PayoutMethod::latest()->paginate(config('basic.paginate'));
        return view('admin.payout_methods.list', $data);
    }

    public function create()
    {
        $data['basicControl'] = basicControl();
        return view('admin.payout_methods.manual.create', $data);
    }

    public function store(Request $request)
    {

        $rules = [
            'name' => 'required|min:3|max:50|unique:payout_methods',
            'description' => 'required|min:3|max:50',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'is_active' => 'nullable|integer|min:0|in:0,1',
            'payout_currencies' => 'required|array',
            'payout_currencies.*.currency_symbol' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'payout_currencies.*.conversion_rate' => 'required|numeric',
            'payout_currencies.*.min_limit' => 'required|numeric',
            'payout_currencies.*.max_limit' => 'required|numeric',
            'payout_currencies.*.percentage_charge' => 'required|numeric',
            'payout_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'required|mimes:png,jpeg,gif|max:10240',
        ];


        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'payout_currencies.*.currency_symbol.required' => 'The payout currency  field is required.',
            'payout_currencies.*.currency_symbol.regex' => 'The payout currency field is invalid',
            'payout_currencies.*.conversion_rate.required' => 'The payout currency convention rate field is required.',
            'payout_currencies.*.conversion_rate.numeric' => 'The convention rate for payout currency must be a number.',
            'payout_currencies.*.min_limit.required' => 'The payout currency min limit field is required.',
            'payout_currencies.*.min_limit.numeric' => 'The min limit for payout currency must be a number.',
            'payout_currencies.*.max_limit.required' => 'The payout currency max limit field is required.',
            'payout_currencies.*.max_limit.numeric' => 'The max limit for payout currency must be a number.',
            'payout_currencies.*.percentage_charge.required' => 'The payout currency percentage charge field is required.',
            'payout_currencies.*.percentage_charge.numeric' => 'The percentage charge for payout currency must be a number.',
            'payout_currencies.*.fixed_charge.required' => 'The payout currency fixed charge is required.',
            'payout_currencies.*.fixed_charge.numeric' => 'The fixed charge for payout currency must be a number.',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessages);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $inputForm = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $inputForm[$arr['field_name']] = $arr;
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.payoutMethod.path'), null, null, 'webp', 70);
                if ($image) {
                    $payoutGatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        $collection = collect($request->payout_currencies);
        $supportedCurrency = $collection->pluck('currency_symbol')->all();
        $response = PayoutMethod::create([
            'name' => $request->name,
            'code' => Str::slug($request->name),
            'description' => $request->description,
            'banks' => $request->banks ?? null,
            'supported_currency' => $supportedCurrency,
            'payout_currencies' => $request->payout_currencies,
            'is_active' => $request->status,
            'inputForm' => $inputForm,
            'logo' => $payoutGatewayImage ?? null,
            'driver' => $driver ?? null
        ]);

        if (!$response) {
            throw new Exception('Something went wrong.Please try again');
        }

        return redirect()->back()->with('success', 'Payout Method Successfully Saved');

    }

    public function edit($id)
    {
        $basicControl = basicControl();
        $payoutMethod = PayoutMethod::findOrFail($id);

        $banks = $payoutMethod->banks ?? [];

        return view('admin.payout_methods.edit', compact('payoutMethod', 'banks', 'basicControl'));
    }


    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|min:3|max:50|unique:payout_methods,name,' . $id,
            'description' => 'required|min:3|max:50',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'is_active' => 'nullable|integer|min:0|in:0,1',
            'payout_currencies' => 'required|array',
            'payout_currencies.*.currency_symbol' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'payout_currencies.*.conversion_rate' => 'required|numeric',
            'payout_currencies.*.min_limit' => 'required|numeric',
            'payout_currencies.*.max_limit' => 'required|numeric',
            'payout_currencies.*.percentage_charge' => 'required|numeric',
            'payout_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
            'auto_update_currency' => 'nullable|integer|in:0,1'
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'payout_currencies.*.currency_symbol.required' => 'The payout currency  field is required.',
            'payout_currencies.*.currency_symbol.regex' => 'The payout currency symbol must contain only uppercase letters.',
            'payout_currencies.*.conversion_rate.required' => 'The payout currency convention rate field is required.',
            'payout_currencies.*.conversion_rate.numeric' => 'The convention rate for payout currency must be a number.',
            'payout_currencies.*.min_limit.required' => 'The payout currency min limit field is required.',
            'payout_currencies.*.min_limit.numeric' => 'The min limit for payout currency must be a number.',
            'payout_currencies.*.max_limit.required' => 'The payout currency max limit field is required.',
            'payout_currencies.*.max_limit.numeric' => 'The max limit for payout currency must be a number.',
            'payout_currencies.*.percentage_charge.required' => 'The payout currency percentage charge field is required.',
            'payout_currencies.*.percentage_charge.numeric' => 'The percentage charge for payout currency must be a number.',
            'payout_currencies.*.fixed_charge.required' => 'The payout currency fixed charge is required.',
            'payout_currencies.*.fixed_charge.numeric' => 'The fixed charge for payout currency must be a number.',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessages);

        if ($validator->fails()) {
            $names = collect(request()->payout_currencies)
                ->filter(function ($item) {
                    return isset($item['name']) && $item['name'] !== null;
                })
                ->pluck('name')
                ->toArray();
            return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput($request->input())
                ->with('selectedCurrencyList', $names);
        }

        $payoutMethod = PayoutMethod::findOrFail($id);

        $inputForm = [];
        if (isset($request->field_name)) {
            $inputs = [];
            for ($i = 0; $i < count($request->field_name); $i++) {
                $inputs['field_name'] = strtolower(Str::snake($request->field_name[$i]));
                $inputs['field_label'] = $request->field_name[$i];
                $inputs['type'] = $request->input_type[$i];
                $inputs['validation'] = $request->is_required[$i];
                $inputForm[$inputs['field_name']] = $inputs;
            }
        }

        $parameters = [];
        if ($payoutMethod->parameters) {
            foreach ($request->except('_token', '_method', 'image') as $k => $v) {
                foreach ($payoutMethod->parameters as $key => $cus) {
                    if ($k != $key) {
                        continue;
                    } else {
                        $rules[$key] = 'required|max:191';
                        $parameters[$key] = $v;
                    }
                }
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.payoutMethod.path'), null, null, 'webp', 70, $payoutMethod->logo, $payoutMethod->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }


        $collection = collect($request->payout_currencies);
        if ($payoutMethod->is_automatic == 1) {
            $supportedCurrency = $collection->pluck('name')->all();
        } else {

            $supportedCurrency = $collection->pluck('currency_symbol')->all();
        }


        $response = $payoutMethod->update([
            'name' => $request->name,
            'banks' => $request->banks,
            'parameters' => $parameters,
            'description' => $request->description,
            'supported_currency' => $supportedCurrency,
            'payout_currencies' => $request->payout_currencies,
            'is_active' => $request->status,
            'is_auto_update' => $request->auto_update_currency,
            'environment' => $request->environment ?? 1,
            'inputForm' => $inputForm ?? $payoutMethod->inputForm,
            'logo' => $gatewayImage ?? $payoutMethod->logo,
            'driver' => $driver ?? $payoutMethod->driver,
        ]);

        if (!$response) {
            throw new Exception('Something went wrong.Please try again');
        }

        return redirect()->back()->with('success', 'Withdraw Method Updated Successfully');
    }


    public function activeDeactivate(Request $request)
    {
        try {
            $payoutMethod = PayoutMethod::where('code', $request->code)->firstOrFail();
            $payoutMethod->update([
                'is_active' => $payoutMethod->is_active == 1 ? 0 : 1
            ]);
            return back()->with('success', 'Payout method status updated successfully.');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function autoUpdate(Request $request, $id)
    {
        $updateForMethods = PayoutMethod::where('code', '!=', 'coinbase')
            ->where('is_automatic', 1)
            ->where('is_auto_update', 1)
            ->where('id', $id)->firstOrFail();

        $autoCurrencyUpdate = CurrencyLayerService::getCurrencyRate();

        $autoUp = [];
        foreach ($autoCurrencyUpdate->quotes as $key => $quote) {
            $strReplace = str_replace($autoCurrencyUpdate->source, '', $key);
            $autoUp[$strReplace] = $quote;
        }

        $usdToBase = 1.00;
        $currenciesArr = [];
        foreach ($updateForMethods->payout_currencies as $key => $payout_currency) {
            foreach ($payout_currency as $key1 => $item) {
                $resRate = $this->getCheck($payout_currency->name, $autoUp);
                $curRate = round($resRate / $usdToBase, 2);
                if ($resRate && $key1 == 'conversion_rate') {
                    $currenciesArr[$key][$key1] = $curRate;
                } else {
                    $currenciesArr[$key][$key1] = $item;
                }
            }
        }
        $updateForMethods->payout_currencies = $currenciesArr;
        $updateForMethods->save();
        return back()->with('success', 'Auto Currency Updated Successfully');
    }


    public function withdrawDays()
    {
        $data['withdrawalConfig'] = config("withdrawaldays");
        return view('admin.payout_methods.withdraw_days', $data);
    }

    public function withdrawDaysUpdate(Request $request)
    {
        $request->validate([
            "monday" => "nullable|integer|in:0,1",
            "tuesday" => "nullable|integer|in:0,1",
            "wednesday" => "nullable|integer|in:0,1",
            "thursday" => "nullable|integer|in:0,1",
            "friday" => "nullable|integer|in:0,1",
            "saturday" => "nullable|integer|in:0,1",
            "sunday" => "nullable|integer|in:0,1",
        ]);

        config(['withdrawaldays.Monday' => (int)$request->monday]);
        config(['withdrawaldays.Tuesday' => (int)$request->tuesday]);
        config(['withdrawaldays.Wednesday' => (int)$request->wednesday]);
        config(['withdrawaldays.Thursday' => (int)$request->thursday]);
        config(['withdrawaldays.Friday' => (int)$request->friday]);
        config(['withdrawaldays.Saturday' => (int)$request->saturday]);
        config(['withdrawaldays.Sunday' => (int)$request->sunday]);

        $fp = fopen(base_path() . '/config/withdrawaldays.php', 'w');
        fwrite($fp, '<?php return ' . var_export(config('withdrawaldays'), true) . ';');
        fclose($fp);

        Artisan::call('config:clear');

        return back()->with("success", "Successfully Updated");
    }

    public function getCheck($currency, $autoUp)
    {
        foreach ($autoUp as $key => $auto) {
            if ($key == $currency) {
                return $auto;
            }
        }
    }

}
PK     x\b    1  Http/Controllers/Admin/CookiePolicyController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Traits\Notify;
use App\Traits\Upload;
use Illuminate\Http\Request;

class CookiePolicyController extends Controller
{
    use Upload, Notify;
    public function cookiePolicySetting(){
        return view('admin.control_panel.cookie_policy_settings');
    }

    public function cookiePolicyUpdate (Request $request){

        $basic = basicControl();

        if ($request->hasFile('cookie_image')) {
            $photo = $this->fileUpload($request->cookie_image, config('filelocation.cookie.path'), null, null, 'webp', 60);

            $basic->cookie_image = $photo['path'] ?? null;
            $basic->cookie_image_driver = $photo['driver'] ?? null;
            $basic->save();
        }

        $basic->cookie_status = $request->cookie_status;
        $basic->cookie_heading = $request->cookie_heading;
        $basic->cookie_description = $request->cookie_description;
        $basic->cookie_button = $request->cookie_button;
        $basic->cookie_button_link = $request->cookie_button_link;
        $basic->save();


        return back()->with('success', 'cookie settings changed.');
    }
}
PK     x\@Wݺn  n  3  Http/Controllers/Admin/FirebaseConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class FirebaseConfigController extends Controller
{
    public function firebaseConfig()
    {
        $data['basicControl'] = basicControl();
        $data['firebaseNotify'] = config('firebase');
        return view('admin.control_panel.firebase_config', $data);
    }

    public function firebaseConfigUpdate(Request $request)
    {
        $request->validate([
            'api_key' => 'required|string',
            'vapid_key' => 'required|string',
            'auth_domain' => 'required|string',
            'project_id' => 'required|string',
            'storage_bucket' => 'required|string',
            'messaging_sender_id' => 'required|string',
            'app_id' => 'required|string',
            'measurement_id' => 'required|string',
            'push_notification' => 'nullable|integer|in:0,1',
            'user_foreground' => 'nullable|integer|in:0,1',
            'user_background' => 'nullable|integer|in:0,1',
            'admin_foreground' => 'nullable|integer|in:0,1',
            'admin_background' => 'nullable|integer|in:0,1',
        ]);

        try {
            $env = [
                'FIREBASE_API_KEY' => $request->api_key,
                'FIREBASE_VAPID_KEY' => $request->vapid_key,
                'FIREBASE_AUTH_DOMAIN' => $request->auth_domain,
                'FIREBASE_PROJECT_ID' => $request->project_id,
                'FIREBASE_STORAGE_BUCKET' => $request->storage_bucket,
                'FIREBASE_MESSAGING_SENDER_ID' => $request->messaging_sender_id,
                'FIREBASE_API_ID' => $request->app_id,
                'FIREBASE_MEASUREMENT_ID' => $request->measurement_id,
                'USER_FOREGROUND' => $request->user_foreground,
                'USER_BACKGROUND' => $request->user_background,
                'ADMIN_FOREGROUND' => $request->admin_foreground,
                'ADMIN_BACKGROUND' => $request->admin_background,
            ];

            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                'push_notification' => $request->push_notification
            ]);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Firebase Configure Successfully.');
    }

    public function firebaseConfigFileUpload(Request $request)
    {
        $this->validate($request, [
            'file' => 'required|file|mimetypes:application/json|mimes:json',
        ]);

        $file = $request->file('file');
        $file->move(base_path(), getFirebaseFileName());

        return back()->with('success', 'Uploaded Successfully');
    }

    public function firebaseConfigFileDownload()
    {
        $filePath = base_path(getFirebaseFileName());
        if (File::exists($filePath)) {
            return response()->download($filePath, getFirebaseFileName());
        } else {
            return response()->json(['error' => 'File not found!'], 404);
        }
    }

}
PK     x\hU)    9  Http/Controllers/Admin/Auth/ConfirmPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ConfirmsPasswords;

class ConfirmPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Confirm Password Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password confirmations and
    | uses a simple trait to include the behavior. You're free to explore
    | this trait and override any functions that require customization.
    |
    */

    use ConfirmsPasswords;

    /**
     * Where to redirect users when the intended url fails.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::ADMIN;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
}
PK     x\    8  Http/Controllers/Admin/Auth/ForgotPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Mail\SendMail;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;

    /**
     * Display the form to request a password reset link.
     *
     * @return \Illuminate\View\View
     */
    public function showLinkRequestForm()
    {
        return view('admin.auth.passwords.email');
    }

    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function sendResetLinkEmail(Request $request)
    {

        $this->validateEmail($request);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $this->credentials($request)
        );

        return $response == Password::RESET_LINK_SENT
            ? $this->sendResetLinkResponse($request, $response)
            : $this->sendResetLinkFailedResponse($request, $response);

    }

    /**
     * Get the response for a successful password reset link.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    protected function sendResetLinkResponse(Request $request, $response)
    {
        $userEmail = $request->get('email');
        $passwordReset = DB::table('password_reset_tokens')->where('email', $userEmail)->first();
        if (!$passwordReset) {
            return back()->with('error','Password reset token not found. Please try again.');
        }
        $token = $passwordReset->token;
        $resetUrl = url(basicControl()->admin_prefix.'/password/reset', rawurlencode($token)) . '?email='.$userEmail;
        $message = 'Your Password Recovery Link: <a href="' . $resetUrl . '" target="_blank">Click To Reset Password</a>';
        $emailFrom = basicControl()->sender_email;

        try {
            Mail::to($userEmail)->send(new SendMail($emailFrom, 'Password Recovery', $message));
        } catch (\Exception $e) {
            return back()->with('error','Failed to send the password reset email. Please try again later.');
        }

        return back()->with('success','Password reset email successfully sent.');
    }


    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('admins');
    }
}
PK     x\+q  q  6  Http/Controllers/Admin/Auth/VerificationController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::ADMIN;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}
PK     x\TS  S  /  Http/Controllers/Admin/Auth/LoginController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Facades\App\Services\Google\GoogleRecaptchaService;


class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    protected $redirectTo = 'admin/dashboard';

    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }

    public function showLoginForm()
    {
        $data['basicControl'] = basicControl();
        return view('admin.auth.login', $data);
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }

    public function login(Request $request)
    {
        $basicControl = basicControl();
        $input = $request->all();

        $rules[$this->username()] = 'required';
        $rules ['password'] = 'required';
        if ($basicControl->manual_recaptcha == 1 && $basicControl->manual_recaptcha_admin_login == 1) {
            $rules['captcha'] = ['required',
                Rule::when((!empty($request->captcha) && strcasecmp(session()->get('captcha'), $_POST['captcha']) != 0), ['confirmed']),
            ];
        }

        if ($basicControl->google_recaptcha_admin_login == 1 && $basicControl->google_recaptcha == 1) {
            GoogleRecaptchaService::responseRecaptcha($request['g-recaptcha-response']);
            $rules['g-recaptcha-response'] = 'sometimes|required';
        }

        $message['captcha.confirmed'] = "The captcha does not match.";
        $validator = Validator::make($request->all(), $rules, $message);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $remember_me = $request->has('remember_me') ? true : false;
        $fieldType = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        if (auth()->guard('admin')->attempt(array($fieldType => $input['username'], 'password' => $input['password']), $remember_me)) {
            return $this->sendLoginResponse($request);
        } else {
            return redirect()->route('admin.login')
                ->with('error', 'Email-Address And Password Are Wrong.');
        }
    }

    public function username()
    {
        $login = request()->input('username');
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        request()->merge([$field => $login]);
        return $field;
    }

    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    public function logout(Request $request)
    {
        $this->guard('guard')->logout();
        $request->session()->invalidate();
        return $this->loggedOut($request) ?: redirect()->route('admin.login');
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard('admin')->user())) {
            return $response;
        }

        return $request->wantsJson()
            ? new JsonResponse([], 204)
            : redirect()->intended($this->redirectPath());
    }


    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user->status == 0) {
            $this->guard('guard')->logout();
            return redirect()->route('admin.login')->with('error', 'You are banned from this application. Please contact with system Administrator.');
        }
        $user->last_login = Carbon::now();
        $user->save();

        if (config('demo.IS_DEMO') == true) {
            $checkUser = \App\Models\User::firstOrNew(['id' => 1]);
            $checkUser->username = 'demouser';
            $checkUser->password = bcrypt('demouser');
            $checkUser->sms_verification = 1;
            $checkUser->email_verification = 1;
            $checkUser->two_fa = 0;
            $checkUser->two_fa_verify = 1;
            $checkUser->status = 1;
            $checkUser->save();
        }
    }
}
PK     x\V9[O  O  7  Http/Controllers/Admin/Auth/ResetPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */
    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = 'admin/dashboard';

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $token
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showResetForm(Request $request, $token = null)
    {

        return view('admin.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }

    public function reset(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|confirmed|min:5',
            'token' => 'required',
        ]);
        $token = rawurldecode($request->token);

        $passwordReset = DB::table('password_reset_tokens')->where('email', $request->email)->first();
        if (!$passwordReset || $passwordReset->token != $token) {
            return back()->withErrors(['email' => 'This password reset token is invalid.']);
        }

        $user = Admin::where('email', $request->email)->first();
        $user->password = bcrypt($request->password);
        $user->save();
        //DB::table('password_reset_tokens')->where('email', $request->email)->delete();

        return redirect()->route('admin.login')->with('success', 'Your password has been reset!');
    }


    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('admins');
    }


    /**
     * Get the guard to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }
}
PK     x\"t^  ^  .  Http/Controllers/Admin/SocialiteController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Stevebauman\Purify\Facades\Purify;

class SocialiteController extends Controller
{
    public function index()
    {
        return view('admin.control_panel.socialiteConfig');
    }

    public function githubConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.githubControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'github_client_id' => 'required|min:3',
                'github_client_secret' => 'required|min:3',
                'github_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;
            config(['socialite.github_status' => $purifiedData->github_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('GITHUB_CLIENT_ID', $purifiedData->github_client_id, $env);
            $env = $this->set('GITHUB_CLIENT_SECRET', $purifiedData->github_client_secret, $env);
            $env = $this->set('GITHUB_REDIRECT_URL', route('socialiteCallback', 'github'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    public function googleConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.googleControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'google_client_id' => 'required|min:3',
                'google_client_secret' => 'required|min:3',
                'google_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;
            config(['socialite.google_status' => $purifiedData->google_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('GOOGLE_CLIENT_ID', $purifiedData->google_client_id, $env);
            $env = $this->set('GOOGLE_CLIENT_SECRET', $purifiedData->google_client_secret, $env);
            $env = $this->set('GOOGLE_REDIRECT_URL', route('socialiteCallback', 'google'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    public function facebookConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.facebookControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'facebook_client_id' => 'required|min:3',
                'facebook_client_secret' => 'required|min:3',
                'facebook_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;

            config(['socialite.facebook_status' => $purifiedData->facebook_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('FACEBOOK_CLIENT_ID', $purifiedData->facebook_client_id, $env);
            $env = $this->set('FACEBOOK_CLIENT_SECRET', $purifiedData->facebook_client_secret, $env);
            $env = $this->set('FACEBOOK_REDIRECT_URL', route('socialiteCallback', 'facebook'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    private function set($key, $value, $env)
    {
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            if ($entry[0] == $key) {
                $env[$env_key] = $key . "=" . $value . "\n";
            } else {
                $env[$env_key] = $env_value;
            }
        }
        return $env;
    }
}
PK     x\( 4#  4#  &  Http/Controllers/PaymentController.phpnu [        <?php

namespace App\Http\Controllers;

use App\Jobs\UserTrackingJob;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\PayoutMethod;
use App\Traits\Notify;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Facades\App\Services\BasicService;
use Exception;
use Illuminate\Support\Facades\Validator;


class PaymentController extends Controller
{

    use Upload, Notify;


    public function depositConfirm($trx_id)
    {
        try {
            $deposit = Deposit::with('user', 'depositable')->where(['trx_id' => $trx_id, 'status' => 0])->first();
            if ($deposit->depositable_type) {
                $extends = template() . 'layouts.app';
            } else {
                $extends = 'themes.dark.layouts.user';
            }
            if (!$deposit) {
                throw new Exception('Invalid Payment Request.');
            }
            $gateway = Gateway::findOrFail($deposit->payment_method_id);
            if (!$gateway) {
                throw new Exception('Invalid Payment Gateway.');
            }

            if (999 < $gateway->id) {
                return view('payment.manual', compact('deposit', 'extends'));
            }

            $gatewayObj = 'App\\Services\\Gateway\\' . $gateway->code . '\\Payment';
            $data = $gatewayObj::prepareData($deposit, $gateway);
            $data = json_decode($data);

        } catch (Exception $exception) {
            session()->flash('warning', 'Something went wrong. Please try again.');
            return back()->with('error', $exception->getMessage());
        }

        if (isset($data->error)) {
            return back()->with('error', $data->message);
        }

        if (isset($data->redirect)) {
            return redirect($data->redirect_url);
        }

        $page_title = 'Payment Confirm';
        return view('payment.' . $data->view, compact('data', 'page_title', 'deposit', 'extends'));

    }

    public function gatewayIpn(Request $request, $code, $trx = null, $type = null)
    {
        if (isset($request->m_orderid)) {
            $trx = $request->m_orderid;
        }

        if ($code == 'coinbasecommerce') {
            $gateway = Gateway::where('code', $code)->first();
            $postdata = file_get_contents("php://input");
            $res = json_decode($postdata);

            if (isset($res->event)) {
                $deposit = Deposit::with('user')->where('trx_id', $res->event->data->metadata->trx)->orderBy('id', 'DESC')->first();
                $sentSign = $request->header('X-Cc-Webhook-Signature');
                $sig = hash_hmac('sha256', $postdata, $gateway->parameters->secret);

                if ($sentSign == $sig) {
                    if ($res->event->type == 'charge:confirmed' && $deposit->status == 0) {
                        BasicService::preparePaymentUpgradation($deposit);
                    }
                }
            }
            session()->flash('success', 'You request has been processing.');

            return redirect()->route('success');
        }

        try {
            $gateway = Gateway::where('code', $code)->first();
            if (!$gateway) {
                throw new Exception('Invalid Payment Gateway.');
            }
            if (isset($trx)) {
                $deposit = Deposit::with('user')->where('trx_id', $trx)->first();
                if (!$deposit) throw new Exception('Invalid Payment Request.');
            }

            $gatewayObj = 'App\\Services\\Gateway\\' . $code . '\\Payment';
            $data = $gatewayObj::ipn($request, $gateway, $deposit ?? null, $trx ?? null, $type ?? null);

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
        if (isset($data['redirect'])) {
            return redirect($data['redirect'])->with($data['status'], $data['msg']);
        }
    }

    public function payoutIpn(Request $request, $code)
    {
        $payoutGateway = PayoutMethod::where('code', $code)->first();
        if ($payoutGateway) {
            $gatewayObj = 'App\\Services\\Payout\\' . $code . '\\Card';
            $gatewayObj::webhook($request);
        }
    }


    public function fromSubmit(Request $request, $trx_id)
    {
        $data = Deposit::where('trx_id', $trx_id)->orderBy('id', 'DESC')->with(['gateway', 'user'])->first();
        if (is_null($data)) {
            return redirect()->route('failed')->with('error', 'Invalid Request');
        }
        if ($data->status != 0) {
            return redirect()->route('failed')->with('error', 'Invalid Request');
        }

        $params = optional($data->gateway)->parameters;
        $reqData = $request->except('_token', '_method');
        $rules = [];
        if ($params !== null) {
            foreach ($params as $key => $cus) {
                $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                if ($cus->type === 'file') {
                    $rules[$key][] = 'image';
                    $rules[$key][] = 'mimes:jpeg,jpg,png';
                    $rules[$key][] = 'max:10240';
                } elseif ($cus->type === 'text') {
                    $rules[$key][] = 'max:191';
                } elseif ($cus->type === 'number') {
                    $rules[$key][] = 'integer';
                } elseif ($cus->type === 'textarea') {
                    $rules[$key][] = 'min:3';
                    $rules[$key][] = 'max:300';
                }
            }
        }

        $validator = Validator::make($reqData, $rules);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $reqField = [];
        if ($params != null) {
            foreach ($request->except('_token', '_method', 'type') as $k => $v) {
                foreach ($params as $inKey => $inVal) {
                    if ($k == $inKey) {
                        if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                            try {
                                $file = $this->fileUpload($request[$inKey], config('filelocation.deposit.path'), null, null, 'webp', null, null, 40);
                                $reqField[$inKey] = [
                                    'field_name' => $inVal->field_name,
                                    'field_value' => $file['path'],
                                    'field_driver' => $file['driver'],
                                    'validation' => $inVal->validation,
                                    'type' => $inVal->type,
                                ];
                            } catch (\Exception $exp) {
                                session()->flash('error', 'Could not upload your ' . $inKey);
                                return back()->withInput();
                            }
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inVal->field_name,
                                'validation' => $inVal->validation,
                                'field_value' => $v,
                                'type' => $inVal->type,
                            ];
                        }
                    }
                }
            }
        }

        $data->update([
            'information' => $reqField,
            'created_at' => Carbon::now(),
            'status' => 2,
        ]);

        $remark = 'Sent manual payment request by ' . $data->gateway->name . ' <h5>Trx: ' . $data->trx_id . '</h5><a href="' . route('admin.payment.log') . '">Click here</a> to see payment details';
        UserTrackingJob::dispatch(auth()->id(), request()->ip(), $remark);

        $msg = [
            'username' => optional($data->user)->username,
            'amount' => currencyPosition($data->amount_in_base),
            'gateway' => optional($data->gateway)->name
        ];
        $action = [
            "name" => optional($data->user)->firstname . ' ' . optional($data->user)->lastname,
            "image" => getFile(optional($data->user)->image_driver, optional($data->user)->image),
            "link" => route('admin.user.payment', $data->user_id),
            "icon" => "fa fa-money-bill-alt text-white"
        ];

        $this->adminPushNotification('PAYMENT_REQUEST', $msg, $action);
        $this->adminFirebasePushNotification('PAYMENT_REQUEST', $msg, $action);
        $this->adminMail('PAYMENT_REQUEST', $msg);

        session()->flash('success', 'You request has been taken.');
        return redirect()->route('user.fund.index');

    }

    public function success()
    {
        return view('success');
    }

    public function failed()
    {
        return view('failed');
    }

}
PK     x\[      3  Http/Controllers/Auth/ConfirmPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ConfirmsPasswords;

class ConfirmPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Confirm Password Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password confirmations and
    | uses a simple trait to include the behavior. You're free to explore
    | this trait and override any functions that require customization.
    |
    */

    use ConfirmsPasswords;

    /**
     * Where to redirect users when the intended url fails.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
}
PK     x\*1    ,  Http/Controllers/Auth/RegisterController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Helpers\UserSystemInfo;
use App\Http\Controllers\Controller;
use App\Jobs\UpdateReviewAndRatingJob;
use App\Jobs\UserNotificationTempletes;
use App\Models\ContentDetails;
use App\Models\Language;
use App\Models\NotificationTemplate;
use App\Models\TopUp;
use App\Models\User;
use App\Models\UserLogin;
use Illuminate\Auth\Events\Registered;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Facades\App\Services\Google\GoogleRecaptchaService;
use App\Rules\PhoneLength;

class RegisterController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Register Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users as well as their
    | validation and creation. By default this controller uses a trait to
    | provide this functionality without requiring any additional code.
    |
    */

    use RegistersUsers;

    /**
     * Where to redirect users after registration.
     *
     * @var string
     */
    protected $redirectTo = '/user/dashboard';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->theme = template();
        $this->middleware('guest');
    }

    /**
     * Show the application registration form.
     *
     * @return \Illuminate\View\View
     */
    public function showRegistrationForm()
    {
        $basic = basicControl();
        if ($basic->registration == 0) {
            return redirect('/')->with('warning', 'Registration Has Been Disabled.');
        }
        $template = ContentDetails::whereHas('content', function ($query) {
            $query->whereIn('name', ['authentication']);
        })->get()->groupBy('content.name');
        return view(template() . 'auth.register', compact('template'));
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        $basicControl = basicControl();
        $validateData = [
            'first_name' => ['required', 'string', 'max:255'],
            'last_name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
            'username' => ['required', 'string', 'max:50', 'unique:users,username'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
            'phone_code' => ['required', 'string', 'max:15'],
            'phone' => ['required', 'string', 'unique:users,phone', new PhoneLength($data['phone_code'])],
            'country' => ['required', 'string', 'max:80'],
            'country_code' => ['required', 'string', 'max:80'],
        ];

        // Recaptcha
        if ($basicControl->google_recaptcha && ($basicControl->google_reCaptcha_status_registration)) {
            GoogleRecaptchaService::responseRecaptcha($_POST['g-recaptcha-response']);
            $validateData['g-recaptcha-response'] = 'sometimes|required';
        }

        // Manual Recaptcha
        if (($basicControl->manual_recaptcha == 1) && ($basicControl->reCaptcha_status_registration == 1)) {
            $validateData['captcha'] = ['required',
                Rule::when((!empty(request()->captcha) && strcasecmp(session()->get('captcha'), $_POST['captcha']) != 0), ['confirmed']),
            ];
        }

        return Validator::make($data, $validateData, [
            'name.required' => 'Full Name field is required',
            'g-recaptcha-response.required' => 'The reCAPTCHA field is required',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param array $data
     * @return \App\Models\User
     */
    protected function create(array $data)
    {
        $basic = basicControl();
        return User::create([
            'firstname' => $data['first_name'],
            'lastname' => $data['last_name'],
            'username' => $data['username'],
            'email' => $data['email'],
            'active_dashboard' => 'nightfall',
            'phone_code' => '+' . $data['phone_code'],
            'phone' => $data['phone'],
            'country' => $data['country'],
            'country_code' => strtoupper($data['country_code']),
            'password' => Hash::make($data['password']),
            'email_verification' => ($basic->email_verification) ? 0 : 1,
            'sms_verification' => ($basic->sms_verification) ? 0 : 1,
            'language_id' => Language::where('default_status', 1)->first()->id ?? null
        ]);
    }

    public function register(Request $request)
    {

        $this->validator($request->all())->validate();

        $user = $this->create($request->all());

        $this->guard()->login($user);

        if ($response = $this->registered($request, $user)) {
            return $response;
        }

        if ($request->ajax()) {
            return route('user.dashboard');
        }

        return $request->wantsJson()
            ? new JsonResponse([], 201)
            : redirect($this->redirectPath());
    }

    protected function registered(Request $request, $user)
    {
        $user->last_login = Carbon::now();
        $user->last_seen = Carbon::now();
        $user->timezone = basicControl()->time_zone;
        $user->two_fa_verify = ($user->two_fa == 1) ? 0 : 1;
        $user->save();

        $info = @json_decode(json_encode(getIpInfo()), true);
        $ul['user_id'] = $user->id;

        $ul['longitude'] = (!empty(@$info['long'])) ? implode(',', $info['long']) : null;
        $ul['latitude'] = (!empty(@$info['lat'])) ? implode(',', $info['lat']) : null;
        $ul['country_code'] = (!empty(@$info['code'])) ? implode(',', $info['code']) : null;
        $ul['location'] = (!empty(@$info['city'])) ? implode(',', $info['city']) . (" - " . @implode(',', @$info['area']) . "- ") . @implode(',', $info['country']) . (" - " . @implode(',', $info['code']) . " ") : null;
        $ul['country'] = (!empty(@$info['country'])) ? @implode(',', @$info['country']) : null;

        $ul['ip_address'] = UserSystemInfo::get_ip();
        $ul['browser'] = UserSystemInfo::get_browsers();
        $ul['os'] = UserSystemInfo::get_os();
        $ul['get_device'] = UserSystemInfo::get_device();

        UserLogin::create($ul);

        event(new Registered($user));

        UserNotificationTempletes::dispatch($user->id);
    }

    protected function guard()
    {
        return Auth::guard();
    }

}
PK     x\>a1    2  Http/Controllers/Auth/ForgotPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\ContentDetails;
use App\Models\User;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;

class ForgotPasswordController extends Controller
{
    use Notify,SendsPasswordResetEmails;

    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */


    public function showLinkRequestForm()
    {
        $template = ContentDetails::whereHas('content', function ($query) {
            $query->whereIn('name', ['authentication']);
        })->get()->groupBy('content.name');

        return view(template() . 'auth.passwords.email', compact('template'));
    }

    public function submitForgetPassword(Request $request)
    {
        $request->validate([
            'email' => 'required|email|exists:users',
        ]);
        try {
            $token = Str::random(64);
            DB::table('password_resets')->insert([
                'email' => $request->email,
                'token' => $token,
                'created_at' => Carbon::now()
            ]);

            $userEmail = $request->email;
            $user = User::where('email', $userEmail)->first();

            $params = [
                'message' => '<a href="' . url('password/reset', $token) . '?email=' . $userEmail . '" target="_blank">Click To Reset Password</a>'
            ];

            $this->mail($user, 'PASSWORD_RESET', $params);

            return back()->with('success', 'We have e-mailed your password reset link!');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     x\8    0  Http/Controllers/Auth/VerificationController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;
use Illuminate\Http\Request;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }

    public function show(Request $request)
    {
        $control = (object) config('basic');
        if($control->email_verification == 1){
            return $request->user()->hasVerifiedEmail()
                ? redirect($this->redirectPath())
                : view('auth.verify');
        }else{
            return view('user.pages.dashboard');
        }

    }
}
PK     x\4b?  ?  )  Http/Controllers/Auth/LoginController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Helpers\UserSystemInfo;
use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\ContentDetails;
use App\Models\UserLogin;
use App\Providers\RouteServiceProvider;
use App\Services\Google\GoogleRecaptchaService;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->theme = template();
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm(Request $request)
    {
        $template = ContentDetails::whereHas('content', function ($query) {
            $query->whereIn('name', ['authentication']);
        })->get()->groupBy('content.name');
        return view($this->theme . 'auth/login', compact('template'));
    }

    protected function validateLogin(Request $request)
    {
        $basicControl = basicControl();
        $rules[$this->username()] = 'required';
        $rules ['password'] = 'required';

        // Recaptcha
        if ($basicControl->google_recaptcha && ($basicControl->google_reCaptcha_status_login)) {
            $recaptchaService = new GoogleRecaptchaService();
            $recaptchaService->responseRecaptcha($request['g-recaptcha-response']);
            $rules['g-recaptcha-response'] = 'sometimes|required';
        }

        // Manual Recaptcha
        if (($basicControl->manual_recaptcha == 1) && ($basicControl->reCaptcha_status_login == 1)) {
            $rules['captcha'] = ['required',
                Rule::when((!empty($request->captcha) && strcasecmp(session()->get('captcha'), $_POST['captcha']) != 0), ['confirmed']),
            ];
        }

        $message['captcha.confirmed'] = "The captcha does not match.";
        $message['g-recaptcha-response.required'] = 'The reCAPTCHA field is required.';

        $request->validate($rules, $message);
    }

    public function username()
    {
        $login = request()->input('username');
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        request()->merge([$field => $login]);
        return $field;
    }

    public function login(Request $request)
    {
        $basicControl = basicControl();
        $rules[$this->username()] = 'required';
        $rules ['password'] = 'required';
        if ($basicControl->manual_recaptcha == 1 && $basicControl->reCaptcha_status_login == 1) {
            $rules['captcha'] = ['required',
                Rule::when((!empty($request->captcha) && strcasecmp(session()->get('captcha'), $_POST['captcha']) != 0), ['confirmed']),
            ];
        }

        if ($basicControl->google_recaptcha == 1 && $basicControl->google_reCaptcha_status_login == 1) {
            $recaptchaService = new GoogleRecaptchaService();
            $recaptchaService->responseRecaptcha($request['g-recaptcha-response']);
            $rules['g-recaptcha-response'] = 'sometimes|required';
        }

        $message['captcha.confirmed'] = "The captcha does not match.";
        $validator = Validator::make($request->all(), $rules, $message);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        if ($this->guard()->validate($this->credentials($request))) {

            if (Auth::attempt([$this->username() => $request->username, 'password' => $request->password, 'status' => 1])) {
                return $this->sendLoginResponse($request);
            } else {
                $page_title = 'User Banned';
                return view('banned', compact('page_title'))->with('error', 'You are banned from this application. Please contact with system Administrator.');
            }
        }
        $this->incrementLoginAttempts($request);
        return $this->sendFailedLoginResponse($request);
    }


    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard('admin')->user())) {
            return $response;
        }

        return $request->wantsJson()
            ? new JsonResponse([], 204)
            : redirect()->intended($this->redirectPath());
    }

    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        $user->last_login = Carbon::now();
        $user->last_seen = Carbon::now();
        $user->two_fa_verify = ($user->two_fa == 1) ? 0 : 1;
        $user->save();

        $info = @json_decode(json_encode(getIpInfo()), true);
        $ul['user_id'] = $user->id;

        $ul['longitude'] = (!empty(@$info['long'])) ? implode(',', $info['long']) : null;
        $ul['latitude'] = (!empty(@$info['lat'])) ? implode(',', $info['lat']) : null;
        $ul['country_code'] = (!empty(@$info['code'])) ? implode(',', $info['code']) : null;
        $ul['location'] = (!empty(@$info['city'])) ? implode(',', $info['city']) . (" - " . @implode(',', @$info['area']) . "- ") . @implode(',', $info['country']) . (" - " . @implode(',', $info['code']) . " ") : null;
        $ul['country'] = (!empty(@$info['country'])) ? @implode(',', @$info['country']) : null;

        $ul['ip_address'] = UserSystemInfo::get_ip();
        $ul['browser'] = UserSystemInfo::get_browsers();
        $ul['os'] = UserSystemInfo::get_os();
        $ul['get_device'] = UserSystemInfo::get_device();

        UserLogin::create($ul);

    }
}
PK     x\D*  *  1  Http/Controllers/Auth/ResetPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\ContentDetails;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Http\Request;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::HOME;

    public function showResetForm(Request $request, $token = null)
    {
        $template = ContentDetails::whereHas('content', function ($query) {
            $query->whereIn('name', ['authentication']);
        })->get()->groupBy('content.name');

        return view(template() . 'auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email, 'template' => $template]
        );
    }
}
PK     x\	    $  Http/Requests/CardServiceRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CardServiceRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required|min:1|max:255',
            'image' => 'nullable|mimes:jpg,png,jpeg,webp',
            'price' => 'required|numeric|min:0',
            'discount' => 'numeric|min:0',
            'discount_type' => 'string|in:percentage,flat',
        ];
    }
}
PK     x\k\    #  Http/Requests/TopUpStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class TopUpStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        if ($this->method() == 'GET') {
            return [];
        }
        return [
            'category_id' => [
                'required',
                'numeric',
                Rule::exists('categories', 'id')->where(function ($query) {
                    $query->where('type', 'top_up');
                }),
            ],
            'name' => 'required|min:1',
            'region' => 'required|min:1',
        ];
    }
}
PK     x\(    &  Http/Requests/CurrencyStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CurrencyStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required|min:1|max:255',
            'code' => 'required|min:3|max:3',
            'symbol' => 'required',
            'rate' => 'required',
        ];
    }
}
PK     x\+~~  ~  '  Http/Requests/CategoryUpdateRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CategoryUpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required|min:1|max:255',
            'icon' => 'nullable|min:1|max:255',
        ];
    }
}
PK     x\X~  ~  &  Http/Requests/CategoryStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class CategoryStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required|min:1|max:255',
            'icon' => 'nullable|min:1|max:255',
        ];
    }

}
PK     x\j D  D  +  Http/Requests/BannerSettingStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BannerSettingStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'heading' => 'required',
            'title' => 'required',
            'button_name' => 'required',
            'button_link' => 'required',
            'image' => $this->routeIs('admin.banner.update') ? 'nullable|mimes:jpg,png,jpeg,webp' : 'required|mimes:jpg,png,jpeg,webp',
        ];
    }
}
PK     x\Ss-E  E  %  Http/Requests/TopUpServiceRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class TopUpServiceRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        //dd($this->request->all());
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'name' => 'required|min:1|max:255',
            'image' => 'nullable|mimes:jpg,png,jpeg,webp',
            'price' => 'required|numeric|min:0',
            'discount' => 'numeric|min:0',
            'discount_type' => 'string|in:percentage,flat',
        ];

    }
}
PK     x\%q    "  Http/Requests/GameStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class GameStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        if ($this->method() == 'GET') {
            return [];
        }
        return [
            'category_id' => [
                'required',
                'numeric',
                Rule::exists('categories', 'id')->where(function ($query) {
                    $query->where('type', 'game');
                }),
            ],
            'name' => 'required|min:1',
            'region' => 'required|min:1',
            'video_link' => 'nullable|url',
        ];
    }
}
PK     x\3c    "  Http/Requests/CardStoreRequest.phpnu [        <?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CardStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        if ($this->method() == 'GET') {
            return [];
        }
        return [
            'category_id' => [
                'required',
                'numeric',
                Rule::exists('categories', 'id')->where(function ($query) {
                    $query->where('type', 'card');
                }),
            ],
            'name' => 'required|min:1',
            'region' => 'required|min:1',
        ];

    }
}
PK     x\ 8    #  Http/Middleware/MaintenanceMode.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class MaintenanceMode
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (basicControl()->is_maintenance_mode) {
            return redirect(route('maintenance'));
        }

        return $next($request);
    }
}
PK     x\f    #  Http/Middleware/CheckUserStatus.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class CheckUserStatus
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = Auth::user();
        if ($user->github_id || $user->google_id || $user->facebook_id) {
            return $next($request);
        }

        if($user->status && $user->email_verification && $user->sms_verification && $user->two_fa_verify){
            return $next($request);
        }

        return redirect(route('user.check'));

    }

}
PK     x\@      Http/Middleware/Demo.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Demo
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $routeName = \Route::currentRouteName();
        $methods = ['POST','PUT','PATCH','DELETE'];
        if(env('IS_DEMO') == true && in_array(request()->method(), $methods) && $routeName != 'admin.logout'){
            return back()->with('error', 'This is DEMO version. You can just explore all the features but can\'t take any action.');
        }
        return $next($request);
    }
}
PK     x\	1@  @    Http/Middleware/Preview.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Preview
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if ($request->has('theme') && in_array(request()->theme, config('basic.themes'))) {
            session(['theme' =>  $request->theme]);
        }
        return $next($request);
    }
}
PK     x\I	  	  "  Http/Middleware/CheckStatusApi.phpnu [        <?php

namespace App\Http\Middleware;

use App\Traits\ApiValidation;
use App\Traits\Notify;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CheckStatusApi
{
    use Notify, ApiValidation;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $user = Auth::user();

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

        if ($user->sms_verification && $user->email_verification && $user->status && $user->two_fa_verify) {
            return $next($request);
        }

        if ($user->email_verification == 0) {
            if (!$user->sent_at || now()->diffInSeconds(Carbon::parse($user->sent_at)) >= 60) {
                $user->verify_code = code(6);
                $user->sent_at = now();
                $user->save();

                $this->verifyToMail($user, 'VERIFICATION_CODE', [
                    'code' => $user->verify_code
                ]);

                return response()->json($this->withErrors('Email Verification Required'));
            }
        }

        if ($user->sms_verification == 0) {
            if (!$user->sent_at || now()->diffInSeconds(Carbon::parse($user->sent_at)) >= 60) {
                $user->verify_code = code(6);
                $user->sent_at = now();
                $user->save();

                $this->verifyToSms($user, 'VERIFICATION_CODE', [
                    'code' => $user->verify_code
                ]);

                return response()->json($this->withErrors('Mobile Verification Required'));
            }
        }

        if ($user->status == 0) {
            return response()->json($this->withErrors('Your account has been suspended'), 403);
        }

        if ($user->two_fa_verify == 0) {
            return response()->json($this->withErrors('Two FA Verification Required'), 403);
        }

        // Ensure a valid response is always returned
        return $next($request);
    }

}
PK     x\~}  }    Http/Middleware/TrimStrings.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;

class TrimStrings extends Middleware
{
    /**
     * The names of the attributes that should not be trimmed.
     *
     * @var array<int, string>
     */
    protected $except = [
        'current_password',
        'password',
        'password_confirmation',
    ];
}
PK     x\Y    #  Http/Middleware/VerifyCsrfToken.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array<int, string>
     */
    protected $except = [
        '*save-token*',
        '*sort-payment-methods*',
        '*admin/upload/ck/image*',
        '*sort*',
        '*coupon/apply*',
        '*get/top-ups/service*',
        '*get/card/service*',
        '*payment*',
    ];
}
PK     x\{{n  n  4  Http/Middleware/PreventRequestsDuringMaintenance.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;

class PreventRequestsDuringMaintenance extends Middleware
{
    /**
     * The URIs that should be reachable while maintenance mode is enabled.
     *
     * @var array<int, string>
     */
    protected $except = [
        //
    ];
}
PK     x\    +  Http/Middleware/RedirectIfAuthenticated.phpnu [        <?php

namespace App\Http\Middleware;

use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;

class RedirectIfAuthenticated
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, string ...$guards): Response
    {
        $guards = empty($guards) ? [null] : $guards;

        foreach ($guards as $guard) {
            if (Auth::guard($guard)->check()) {
                if ($guard == 'admin') {
                    return redirect()->route('admin.dashboard');
                } else {
                    return redirect()->route('user.dashboard');
                }
            }
            return $next($request);
        }

        return $next($request);
    }
}
PK     x\Q#{  {    Http/Middleware/TrustHosts.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Http\Middleware\TrustHosts as Middleware;

class TrustHosts extends Middleware
{
    /**
     * Get the host patterns that should be trusted.
     *
     * @return array<int, string|null>
     */
    public function hosts(): array
    {
        return [
            $this->allSubdomainsOfApplicationUrl(),
        ];
    }
}
PK     x\g{R  R    Http/Middleware/CheckModule.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckModule
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $role)
    {
        if (basicControl()->{$role} == 0) {
            abort(403);
        }

        return $next($request);
    }
}
PK     x\bi'  '    Http/Middleware/Language.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use App\Models\Language as LanguageModel;
use Illuminate\Support\Facades\DB;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        session()->put('lang', $this->getCode());
        session()->put('rtl', $this->getDirection());
        app()->setLocale(session('lang', $this->getCode()));
        return $next($request);
    }

    public function getCode()
    {
        if (session()->has('lang')) {
            return session('lang');
        }
        try {
            DB::connection()->getPdo();

            $language = LanguageModel::where('status', 1)->where('default_status', 1)->first();
            if (!$language) {
                $language = LanguageModel::where('status', 1)->first();
            }
            return $language ? $language->short_name : 'en';
        } catch (\Exception $exception) {

        }
    }

    public function getDirection()
    {
        if (session()->has('rtl')) {
            return session('rtl');
        }
        try {
            DB::connection()->getPdo();

            $language = LanguageModel::where('status', 1)->where('default_status', 1)->first();
            if (!$language) {
                $language = LanguageModel::where('status', 1)->first();
            }
            return $language ? $language->rtl : 0;
        } catch (\Exception $exception) {

        }
    }
}
PK     x\j       Http/Middleware/TrustProxies.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array<int, string>|string|null
     */
    protected $proxies;

    /**
     * The headers that should be used to detect proxies.
     *
     * @var int
     */
    protected $headers =
        Request::HEADER_X_FORWARDED_FOR |
        Request::HEADER_X_FORWARDED_HOST |
        Request::HEADER_X_FORWARDED_PORT |
        Request::HEADER_X_FORWARDED_PROTO |
        Request::HEADER_X_FORWARDED_AWS_ELB;
}
PK     x\Q      Http/Middleware/apiKYC.phpnu [        <?php

namespace App\Http\Middleware;

use App\Models\Kyc as KYCModel;
use App\Models\UserKyc;
use App\Traits\ApiValidation;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class apiKYC
{
    use ApiValidation;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $kycTypes = KYCModel::where('status', 1)->pluck('id');
        if (count($kycTypes) > 0) {
            $userKyc = UserKyc::where('user_id', Auth::user()->id)->whereIn('kyc_id', $kycTypes)->get();
            $userKycIds = $userKyc->pluck('kyc_id')->toArray();
            $missingKycTypes = array_diff($kycTypes->toArray(), $userKycIds);

            if (!empty($missingKycTypes)) {
                return response()->json($this->withErrors('Please submit KYC information to access all the resource'));
            }
            $statuses = $userKyc->pluck('status');
            if (!in_array(1, $statuses->toArray())) {
                return response()->json($this->withErrors('Please submit KYC information to access all the resource'));
            }
        }
        return $next($request);
    }
}
PK     x\^sI    "  Http/Middleware/CheckModuleApi.phpnu [        <?php

namespace App\Http\Middleware;

use App\Traits\ApiValidation;
use Closure;
use Illuminate\Http\Request;

class CheckModuleApi
{
    use ApiValidation;

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next, $role)
    {
        if (basicControl()->{$role} == 0) {
            return response()->json($this->withErrors('Module currently unreachable'));
        }
        return $next($request);
    }
}
PK     x\=;a  a  "  Http/Middleware/ActivityByUser.phpnu [        <?php

namespace App\Http\Middleware;

use App\Models\Admin;
use App\Models\User;
use Carbon\Carbon;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class ActivityByUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (Auth::guard('web')->check()) {
            $expiresAt = Carbon::now()->addMinutes(2); // keep online for 1 min
            Cache::put('user-is-online-' . Auth::guard('web')->user()->id, true, $expiresAt);
            User::where('id', Auth::guard('web')->user()->id)->update(['last_seen' => (new \DateTime())->format("Y-m-d H:i:s")]);
        }
        if (Auth::guard('admin')->check()) {
            $expiresAt = Carbon::now()->addMinutes(2); // keep online for 1 min
            Cache::put('admin-is-online-' . Auth::guard('admin')->user()->id, true, $expiresAt);
            Admin::where('id', Auth::guard('admin')->user()->id)->update(['last_seen' => (new \DateTime())->format("Y-m-d H:i:s")]);
        }
        return $next($request);
    }
}




PK     x\Gf    %  Http/Middleware/ValidateSignature.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Routing\Middleware\ValidateSignature as Middleware;

class ValidateSignature extends Middleware
{
    /**
     * The names of the query string parameters that should be ignored.
     *
     * @var array<int, string>
     */
    protected $except = [
        // 'fbclid',
        // 'utm_campaign',
        // 'utm_content',
        // 'utm_medium',
        // 'utm_source',
        // 'utm_term',
    ];
}
PK     x\"q3  3  "  Http/Middleware/EncryptCookies.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class EncryptCookies extends Middleware
{
    /**
     * The names of the cookies that should not be encrypted.
     *
     * @var array<int, string>
     */
    protected $except = [
        //
    ];
}
PK     x\*?_  _    Http/Middleware/KYC.phpnu [        <?php

namespace App\Http\Middleware;

use App\Models\Kyc as KYCModel;
use App\Models\UserKyc;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;

class KYC
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $kycTypes = KYCModel::where('status', 1)->pluck('id');
        if(count($kycTypes) > 0){
            $userKyc = UserKyc::where('user_id', Auth::user()->id)->whereIn('kyc_id', $kycTypes)->get();
            $userKycIds = $userKyc->pluck('kyc_id')->toArray();
            $missingKycTypes = array_diff($kycTypes->toArray(), $userKycIds);

            if (!empty($missingKycTypes)) {
                return redirect()->route('user.kyc.settings')->with('error', 'Please submit KYC information to access all the resource');
            }
            $statuses = $userKyc->pluck('status');
            if (!in_array(1, $statuses->toArray())) {
                return redirect()->route('user.kyc.settings')->with('error', 'Your KYC is not approved yet');
            }
        }
        return $next($request);
    }



}
PK     x\q      '  Http/Middleware/ValidateRequestData.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Stevebauman\Purify\Facades\Purify;

class ValidateRequestData
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $preventFrom = ['email_template', 'email_description', 'guide', 'description'];
        foreach ($request->all() as $key => $req) {
            unset($request['filepond']);
            if (!$request->hasFile($key) && !in_array($key, $preventFrom)) {
                $request[$key] = isset($req) ? Purify::clean($req) : null;
            }
        }
        return $next($request);
    }
}
PK     x\K )  )     Http/Middleware/Authenticate.phpnu [        <?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     */
    protected function redirectTo(Request $request)
    {
        if (!$request->expectsJson()) {
            if (trim(request()->route()->getPrefix(), '/') == 'admin') {
                return route('admin.login');
            }
            return route('login');
        }
    }
}
PK     x\Gk    ,  Http/Middleware/AdminAuthorizeMiddleware.phpnu [        <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AdminAuthorizeMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next, $module): Response
    {
        $permissionLists = auth()->guard('admin')->user()->role->permission ?? null;
        if (!$permissionLists) {
            return $next($request);
        }
        if (in_array(title2snake($module),$permissionLists)) {
            return $next($request);
        }

        return redirect()->route('admin.403');
    }
}
PK     x\v&N  N    Http/Kernel.phpnu [        <?php

namespace App\Http;

use App\Http\Middleware\Demo;
use App\Http\Middleware\VerifyUser;
use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array<int, class-string|string>
     */
    protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\ValidateRequestData::class,
            \App\Http\Middleware\Language::class,
            \App\Http\Middleware\ActivityByUser::class,
            \App\Http\Middleware\Preview::class,

        ],

        'api' => [
            // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            \Illuminate\Routing\Middleware\ThrottleRequests::class . ':api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\ValidateRequestData::class,
        ],
    ];

    /**
     * The application's middleware aliases.
     *
     * Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
     *
     * @var array<string, class-string|string>
     */
    protected $middlewareAliases = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'demo' => Demo::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \App\Http\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'maintenanceMode' => \App\Http\Middleware\MaintenanceMode::class,
        'userCheck' => \App\Http\Middleware\CheckUserStatus::class,
        'checkAuthenticate' => \App\Http\Middleware\CheckApiAuthenticate::class,
        'permission' => \App\Http\Middleware\AdminAuthorizeMiddleware::class,
        'kyc' => \App\Http\Middleware\KYC::class,
        'CheckStatusApi' => \App\Http\Middleware\CheckStatusApi::class,
        'apiKYC' => \App\Http\Middleware\apiKYC::class,
        'ModuleApi' => \App\Http\Middleware\CheckModuleApi::class,
        'module' => \App\Http\Middleware\CheckModule::class,
    ];
}
PK     x\{fKV  V    Models/Payout.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Payout extends Model
{
    use HasFactory;
    protected $fillable = ['user_id', 'payout_method_id', 'payout_currency_code', 'amount', 'charge', 'net_amount', 'amount_in_base_currency',
    'charge_in_base_currency', 'net_amount_in_base_currency', 'response_id', 'last_error', 'information', 'meta_field', 'feedback', 'trx_id', 'status'];

    protected $table = 'payouts';

    protected $casts = [
        'information' => 'object',
        'meta_field' => 'object',
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function method()
    {
        return $this->belongsTo(PayoutMethod::class, 'payout_method_id');
    }

    public function getStatusClass()
    {
        return [
            '1' => 'text-pending',
            '2' => 'text-success',
            '3' => 'text-danger',
        ][$this->status] ?? 'text-success';
    }

    public function payoutMethod()
    {
        return $this->belongsTo(PayoutMethod::class, 'payout_method_id', 'id');
    }

    public function transactional()
    {
        return $this->morphOne(Transaction::class, 'transactional');
    }

    public function picture()
    {
        $image = $this->method->image;
        if (!$image) {
            $url = getFile($this->method->driver, $this->method->logo);
            return '<div class="avatar avatar-sm avatar-circle">
                        <img class="avatar-img" src="' . $url . '" alt="Image Description">
                     </div>';

        } else {
            $firstLetter = substr($this->method->name, 0, 1);
            return '<div class="avatar avatar-sm avatar-soft-primary avatar-circle">
                        <span class="avatar-initials">' . $firstLetter . '</span>
                     </div>';
        }
    }


    public static function boot(): void
    {
        parent::boot();
        static::saved(function () {
            Cache::forget('payoutRecord');
        });

        static::creating(function (Payout $payout) {
            if (empty($payout->trx_id)) {
                $payout->trx_id = self::generateOrderNumber();
            }
        });
    }
    public static function generateOrderNumber()
    {
        return DB::transaction(function () {
            $lastOrder = self::lockForUpdate()->orderBy('id', 'desc')->first();
            if ($lastOrder && isset($lastOrder->trx_id)) {
                $lastOrderNumber = (int)filter_var($lastOrder->trx_id, FILTER_SANITIZE_NUMBER_INT);
                $newOrderNumber = $lastOrderNumber + 1;
            } else {
                $newOrderNumber = strRandomNum(12);
            }

            while (self::where('trx_id', 'P'.$newOrderNumber)->exists()) {
                $newOrderNumber = (int)$newOrderNumber + 1;
            }
            return 'P' . $newOrderNumber;
        });
    }


}
PK     x\[JZ      Models/Kyc.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Kyc extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'slug', 'input_form', 'status'];

    public $casts = ['input_form' => 'object'];

    public function userKyc()
    {
        return $this->hasMany(UserKyc::class, 'kyc_id', 'id');
    }

}
PK     x\ }PZ
  
    Models/MaintenanceMode.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class MaintenanceMode extends Model
{
    use HasFactory;

    protected $fillable = ["heading", "description", "image", "image_driver"];
}
PK     x\:}      Models/SellPostOffer.phpnu [        <?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPostOffer extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $appends = ['dateParse'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function author()
    {
        return $this->belongsTo(User::class, 'author_id');
    }


    public function sellPost()
    {
        return $this->belongsTo(SellPost::class, 'sell_post_id');
    }

    public function lastMessage()
    {
        return $this->hasOne(SellPostChat::class, 'offer_id')->latest();
    }

    public function messages()
    {
        return $this->hasMany(SellPostChat::class, 'offer_id')->latest();
    }

    public function getDateParseAttribute()
    {
        return Carbon::parse($this->created_at)->diffForHumans();
    }
}
PK     x\      Models/OrderDetail.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OrderDetail extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $appends = ['image_path'];
    protected $casts = [
        'code' => 'array'
    ];

    public function getImagePathAttribute()
    {
        return getFile($this->image_driver, $this->image);
    }

    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function detailable()
    {
        return $this->morphTo();
    }
}
PK     x\	g  g    Models/CardService.phpnu [        <?php

namespace App\Models;

use App\Scopes\EnsureCardIdScope;
use App\Traits\Upload;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class CardService extends Model
{
    use HasFactory, Upload;

    protected $guarded = ['id'];
    protected $appends = ['image_path'];
    protected $casts = [
        'old_data' => 'object',
        'campaign_data' => 'object',
    ];

    protected static function booted()
    {
        static::saved(function ($model) {
            if (!isset($model->card_id)) {
                static::addGlobalScope(new EnsureCardIdScope);
                $model->refresh();
            }
            dispatch(new \App\Jobs\UpdateChildCountJob($model->card->category_id, 'card'));
        });
    }

    public function card()
    {
        return $this->belongsTo(Card::class, 'card_id');
    }

    public function codes()
    {
        return $this->morphMany(Code::class, 'codeable');
    }

    public function activeCodes()
    {
        return $this->morphMany(Code::class, 'codeable')->where('status', 1);
    }

    public function setImageAttribute($image)
    {
        if ($image) {
            $uploadedImage = $this->fileUpload($image, config('filelocation.cardService.path'), null, config('filelocation.cardService.size'), 'webp', 60);
            if ($uploadedImage) {
                $this->attributes['image'] = $uploadedImage['path'];
                $this->attributes['image_driver'] = $uploadedImage['driver'];
            }
        }
    }

    public function getImagePathAttribute()
    {
        return getFile($this->image_driver, $this->image);
    }

    public function imagePath()
    {
        return getFile($this->image_driver, $this->image);
    }

    public function getDiscount()
    {
        $discount = 0;
        if ($this->discount && $this->price) {
            if ($this->discount_type == 'percentage') {
                $discount = ($this->discount * $this->price) / 100;
            } elseif ($this->discount_type == 'flat') {
                $discount = $this->discount;
            }
        }
        return $discount;
    }
}
PK     x\T      Models/TopUp.phpnu [        <?php

namespace App\Models;

use App\Scopes\EnsureCategoryIdScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TopUp extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $casts = [
        'image' => 'object',
        'order_information' => 'object',
    ];

    protected $appends = ['preview_image', 'top_up_detail_route'];

    protected static function booted()
    {
        static::saving(function ($model) {
            if (isset($model->name)) {
                $model->slug = slug($model->name);
            }
        });

        static::saved(function ($model) {
            if (!isset($model->category_id)) {
                static::addGlobalScope(new EnsureCategoryIdScope);
                $model->refresh();
            }
            dispatch(new \App\Jobs\UpdateChildCountJob($model->category_id, 'top_up'));
        });
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function services()
    {
        return $this->hasMany(TopUpService::class, 'top_up_id');
    }

    public function activeServices()
    {
        return $this->hasMany(TopUpService::class, 'top_up_id')->where('status', 1)->orderBy('sort_by', 'ASC');
    }

    public function reviewByReviewer()
    {
        return $this->morphOne(Review::class, 'reviewable')->where('user_id', auth()->id());
    }

    public function getPreviewImageAttribute()
    {
        if (isset($this->image->preview_driver) && isset($this->image->preview)) {
            return getFile($this->image->preview_driver, $this->image->preview);
        }
    }

    public function getTopUpDetailRouteAttribute()
    {
        if (isset($this->slug)) {
            return route('topUp.details', $this->slug);
        }
    }
    public function serviceWithLowestPrice()
    {
        return $this->activeServices->sortBy('price')->first() ?? new TopUpService();
    }


}
PK     x\[      Models/PayoutMethod.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PayoutMethod extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'code', 'description', 'bank_name', 'banks', 'parameters', 'extra_parameters', 'inputForm', 'currency_lists',
        'supported_currency', 'payout_currencies', 'is_active', 'is_automatic', 'is_sandbox', 'environment', 'confirm_payout', 'is_auto_update',
        'currency_type', 'logo', 'driver'];

    protected $casts = [
        'bank_name' => 'object',
        'banks' => 'array',
        'parameters' => 'object',
        'extra_parameters' => 'object',
        'convert_rate' => 'object',
        'currency_lists' => 'object',
        'supported_currency' => 'object',
        'automatic_input_form' => 'object',
        'payout_currencies' => 'object',
        'inputForm' => 'object'
    ];
}
PK     x\}KA      Models/SellPost.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPost extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $table = 'sell_posts';
    protected $appends = ['imagePath'];
    protected $casts = [
        'image' => 'object',
        'credential' => 'object',
        'post_specification_form' => 'object'
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function category()
    {
        return $this->belongsTo(SellPostCategory::class, 'category_id', 'id');
    }

    public function activites()
    {
        return $this->hasMany(ActivityLog::class, 'sell_post_id');
    }

    public function getStatusMessageAttribute()
    {
        if ($this->status == 1) {
            return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Approved') . '
                  </span>';
        } elseif ($this->status == 0) {
            return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending') . '
                  </span>';
        } elseif ($this->status == 2) {
            return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Re Submission') . '
                  </span>';
        } elseif ($this->status == 3) {
            return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Hold') . '
                  </span>';
        } elseif ($this->status == 4) {
            return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Soft Rejected') . '
                  </span>';
        } elseif ($this->status == 5) {
            return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Hard Rejected') . '
                  </span>';
        }
    }


    public function getActivityTitleAttribute()
    {
        $oldActivity = $this->activites->count();
        if ($this->status == 0) {
            return "New Post Submission";
        } elseif (0 < $oldActivity && $this->status == 1) {
            return "Resubmission Trusted Approval";
        } elseif ($this->status == 1) {
            return "Trusted Approval";
        } elseif ($this->status == 2) {
            return "Resubmission";
        } elseif ($this->status == 3) {
            return "Post Hold";
        } elseif (0 < $oldActivity && $this->status == 4) {
            return "Resubmission Soft Rejected";
        } elseif ($this->status == 4) {
            return "Soft Rejected";
        } elseif ($this->status == 5) {
            return 'Hard Rejected';
        }

        return 'Unknown';
    }

    public function sellPostOffer()
    {
        return $this->hasMany(SellPostOffer::class, 'sell_post_id');
    }

    public function sellPostPayment()
    {
        return $this->hasOne(SellPostPayment::class, 'sell_post_id');
    }

    public function scopeStatus($query, $value)
    {
        return $query->where('status', $value);
    }
    public function getImagePathAttribute()
    {
        $imagePath = [];

        $images = is_array($this->image) ? $this->image : json_decode(json_encode($this->image), true);

        if (!empty($images) && is_array($images)) {
            foreach ($images as $key => $img) {
                $imagePath[$key] = getFile($this->image_driver, $img);
            }
        }

        return $imagePath;
    }

}
PK     x\bE  E    Models/BlogCategory.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BlogCategory extends Model
{
    use HasFactory;

    public $fillable = ['name', 'slug'];

    public function blogs()
    {
        return $this->hasMany(Blog::class, 'category_id');
    }
}
PK     x\[[ٗ      Models/UserKyc.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class UserKyc extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'kyc_id', 'kyc_type', 'kyc_info', 'status', 'reason'];

    protected $casts = [
        'kyc_info' => 'object',
    ];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function kyc()
    {
        return $this->belongsTo(Kyc::class, 'kyc_id', 'id');
    }

    protected static function boot()
    {
        parent::boot();
        static::saved(function () {
            Cache::forget('userKYCRecord');
        });
    }

}
PK     x\BXpJ  J    Models/UserLogin.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class UserLogin extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'longitude', 'latitude', 'country_code', 'location', 'country', 'ip_address', 'browser', 'os', 'get_device'];

}
PK     x\óU      Models/User.phpnu [        <?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Traits\Notify;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Database\Eloquent\SoftDeletes;


class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, SoftDeletes, Notify;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $guarded = ['id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    protected $appends = ['LastSeenActivity', 'imgPath', 'fullname'];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
        'password' => 'hashed',
    ];

    protected $dates = ['deleted_at'];

    protected static function boot()
    {
        parent::boot();
        static::saved(function () {
            Cache::forget('userRecord');
        });
    }

    public function notifypermission()
    {
        return $this->morphOne(NotificationSettings::class, 'notifyable');
    }
    public function getFullNameAttribute()
    {
        return $this->firstname . ' ' . $this->lastname;
    }
    public function getImgPathAttribute()
    {
        return getFile($this->image_driver, $this->image);
    }


    public function chatable()
    {
        return $this->morphOne(SellPostChat::class, 'chatable');
    }

    public function funds()
    {
        return $this->hasMany(Fund::class)->latest()->where('status', '!=', 0);
    }


    public function transaction()
    {
        return $this->hasOne(Transaction::class)->latest();
    }

    public function sellChats()
    {
        return $this->morphMany(SellPostChat::class, 'chatable');
    }
    public function getLastSeenActivityAttribute()
    {
        if (Cache::has('user-is-online-' . $this->id) == true) {
            return true;
        } else {
            return false;
        }
    }


    public function inAppNotification()
    {
        return $this->morphOne(InAppNotification::class, 'inAppNotificationable', 'in_app_notificationable_type', 'in_app_notificationable_id');
    }

    public function fireBaseToken()
    {
        return $this->morphMany(FireBaseToken::class, 'tokenable');
    }

    public function profilePicture()
    {
        $image = $this->image;
        if (!$image) {
            $active = $this->LastSeenActivity == false ? 'warning' : 'success';
            $firstLetter = substr($this->firstname, 0, 1);
            return '<div class="avatar avatar-sm avatar-soft-primary avatar-circle">
                        <span class="avatar-initials">' . $firstLetter . '</span>
                        <span class="avatar-status avatar-sm-status avatar-status-' . $active . '"></span>
                     </div>';

        } else {
            $url = getFile($this->image_driver, $this->image);
            $active = $this->LastSeenActivity == false ? 'warning' : 'success';
            return '<div class="avatar avatar-sm avatar-circle">
                        <img class="avatar-img" src="' . $url . '" alt="Image Description">
                        <span class="avatar-status avatar-sm-status avatar-status-' . $active . '"></span>
                     </div>';

        }
    }
    public function activities()
    {
        return $this->morphMany(ActivityLog::class, 'activityable');
    }
    public function sendPasswordResetNotification($token)
    {
        $this->mail($this, 'PASSWORD_RESET', $params = [
            'message' => '<a href="' . url('password/reset', $token) . '?email=' . $this->email . '" target="_blank">Click To Reset Password</a>'
        ], null, null, 'send');
    }

    public function notifySetting()
    {
        return $this->morphOne(NotificationSettings::class, 'notifyable');
    }


    public function topUp()
    {
        return $this->hasMany(TopUpSell::class, 'user_id')->latest();
    }
}
PK     x\6?  ?    Models/NotificationTemplate.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class NotificationTemplate extends Model
{
    use HasFactory;

    protected $fillable = [
        'language_id',
        'name',
        'subject',
        'template_key',
        'short_keys',
        'email',
        'sms',
        'in_app',
        'push',
        'status',
        'notify_for',
        'lang_code',
        'email_from'
    ];

    protected $casts = [
        'short_keys' => 'array',
        'status' => 'array',
    ];

}
PK     x\d7        Models/Currency.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Currency extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
}
PK     x\Fݨ(  (  "  Models/SupportTicketAttachment.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SupportTicketAttachment extends Model
{
    use HasFactory;

    protected $fillable = ['support_ticket_message_id', 'file', 'driver'];
    protected $appends = ['image'];

    public function supportMessage()
    {
        return $this->belongsTo(SupportTicketMessage::class, 'support_ticket_message_id');
    }

    public function getImageAttribute()
    {
        return getFile($this->driver, $this->file);
    }
}
PK     x\|b<m  m    Models/NotificationSettings.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class NotificationSettings extends Model
{
    use HasFactory;

    protected $fillable = ['id', 'notifyable_id', 'notifyable_type', 'template_email_key', 'template_sms_key', 'template_in_app_key', 'template_push_key'];

    public function notifyable()
    {
        return $this->morphTo();
    }

    protected $casts = [
        'template_email_key' => 'array',
        'template_sms_key' => 'array',
        'template_in_app_key' => 'array',
        'template_push_key' => 'array'
    ];
}
PK     x\!  !    Models/ManualSmsConfig.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ManualSmsConfig extends Model
{
    use HasFactory;

    protected $fillable = ['action_method', 'action_url', 'header_data', 'param_data', 'form_data'];

}
PK     x\4Qy  y    Models/Gateway.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Gateway extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'name',
        'sort_by',
        'image',
        'driver',
        'status',
        'parameters',
        'currencies',
        'description',
        'extra_parameters',
        'currency',
        'symbol',
        'is_sandbox',
        'environment',
        'min_amount',
        'max_amount',
        'percentage_charge',
        'fixed_charge',
        'convention_rate',
        'supported_currency',
        'receivable_currencies',
        'note'
    ];
    protected $casts = [
        'currency' => 'object',
        'supported_currency' => 'object',
        'receivable_currencies' => 'object',
        'parameters' => 'object',
        'currencies' => 'object',
        'extra_parameters' => 'object',
    ];

    public function scopeAutomatic()
    {
        return $this->where('id', '<', 1000);
    }

    public function scopeManual()
    {
        return $this->where('id', '>=', 1000);
    }

    public function countGatewayCurrency()
    {
        $currencyLists = $this->currencies->{0} ?? $this->currencies->{1};
        $count = 0;
        foreach ($currencyLists as $currency) {
            $count++;
        }
        return $count;
    }
}
PK     x\JPjX  X    Models/SmsControl.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SmsControl extends Model
{
    use HasFactory;

    protected $fillable = ['method_name', 'configuration_parameters', 'status'];

    protected $casts = [
        'configuration_parameters' => 'object',
    ];
}
PK     x\      Models/Coupon.phpnu [        <?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

class Coupon extends Model
{
    protected $guarded = ['id'];
    protected $casts = [
        'top_up_list' => 'array',
        'card_list' => 'array',
    ];

    protected $appends = ['check_status'];

    public function getCheckStatusAttribute()
    {
        if (!$this->status) {
            return 'In-Active';
        }

        if ($this->start_date < Carbon::now() && $this->end_date > Carbon::now()) {
            return 'Running';
        }

        if ($this->start_date < Carbon::now() && !$this->end_date) {
            return 'Running';
        }

        if ($this->start_date > Carbon::now()) {
            return 'Awaiting-Running';
        }

        return 'Expired';
    }
}
PK     x\< }      Models/Blog.phpnu [        <?php

namespace App\Models;

use App\Traits\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Blog extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    protected $casts = ['meta_keywords' => 'array'];

    public function details()
    {
        return $this->hasOne(BlogDetails::class, 'blog_id');
    }

    public function category()
    {
        return $this->belongsTo(BlogCategory::class);
    }

}
PK     x\W8>      Models/Content.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Content extends Model
{
    use HasFactory;

    public $fillable = ['name', 'type', 'media'];

    public $casts = ['media' => "object"];

    public function contentDetails()
    {
        return $this->hasMany(ContentDetails::class, 'content_id', 'id');
    }

}
PK     x\J!        Models/Subscriber.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Subscriber extends Model
{
    protected $guarded = ['id'];
    protected $table = 'subscribers';
}
PK     x\              Models/index.phpnu [        PK     x\U      Models/SupportTicket.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;

class SupportTicket extends Model
{
    use HasFactory;

    protected $fillable = ['user_id', 'ticket', 'subject', 'status', 'last_reply'];

    protected $dates = ['last_reply'];

    public function getUsernameAttribute()
    {
        return $this->name;
    }

    protected static function boot()
    {
        parent::boot();
        static::saved(function () {
            Cache::forget('ticketRecord');
        });
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function messages(){
        return $this->hasMany(SupportTicketMessage::class)->latest();
    }

    public function lastReply(){
        return $this->hasOne(SupportTicketMessage::class)->latest();
    }
    public function  getLastMessageAttribute(){
        return Str::limit($this->lastReply->message,40);
    }

}
PK     x\߯b        Models/Campaign.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Campaign extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
}
PK     x\r  r    Models/Page.phpnu [        <?php

namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Page extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    protected $casts = ['meta_keywords' => 'array'];


    public function details()
    {
        return $this->hasOne(PageDetail::class, 'page_id', 'id');
    }

    protected function metaKeywords(): Attribute
    {
        return Attribute::make(
            get: fn(string $value) => explode(", ", $value),
        );
    }

    public function getLanguageEditClass($id, $languageId)
    {
        return DB::table('page_details')->where(['page_id' => $id, 'language_id' => $languageId])->exists() ? 'bi-check2' : 'bi-pencil';
    }

    public function getMetaRobots()
    {
        return explode(",", $this->meta_robots);
    }
}
PK     x\~P.      Models/Transaction.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Transaction extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function transactional()
    {
        return $this->morphTo();
    }

    public static function boot(): void
    {
        parent::boot();
        static::creating(function (Transaction $transaction) {
            if (empty($transaction->trx_id)) {
                $transaction->trx_id = self::generateOrderNumber();
            }
        });
    }

    public static function generateOrderNumber()
    {
        return DB::transaction(function () {
            $lastOrder = self::lockForUpdate()->orderBy('id', 'desc')->first();
            if ($lastOrder && isset($lastOrder->trx_id)) {
                $lastOrderNumber = (int)filter_var($lastOrder->trx_id, FILTER_SANITIZE_NUMBER_INT);
                $newOrderNumber = $lastOrderNumber + 1;
            } else {
                $newOrderNumber = strRandomNum(12);
            }

            while (self::where('trx_id', 'T' . $newOrderNumber)->exists()) {
                $newOrderNumber = (int)$newOrderNumber + 1;
            }
            return 'T' . $newOrderNumber;
        });
    }

}
PK     x\Dj  j  !  Models/SellPostCategoryDetail.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPostCategoryDetail extends Model
{
    use HasFactory;
    protected $guarded = ['id'];


    public function sellPostCategory()
    {
        return $this->belongsTo(SellPostCategory::class, 'sell_post_category_id');
    }
}
PK     x\|      Models/SellPostChat.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPostChat extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    public function chatable()
    {
        return $this->morphTo();
    }



    protected $appends = ['formatted_date'];


    public function getFormattedDateAttribute(){
        return $this->created_at->format('M d, Y h:i A');
    }

    public function sellPost()
    {
        return $this->belongsTo(SellPost::class,'sell_post_id');
    }
    public function sellPostOffer()
    {
        return $this->belongsTo(SellPostOffer::class,'offer_id');
    }

}
PK     x\
"[w  w    Models/Role.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    use HasFactory;


    protected $guarded = ['id'];
    protected $casts = [
        'permission' => 'array'
    ];

    public function roleUsers()
    {
        return $this->hasMany(Admin::class, 'role_id');
    }
}
PK     x\J      Models/SellPostPayment.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPostPayment extends Model
{
    use HasFactory;
    protected $guarded = ['id'];

    public function fundable()
    {
        return $this->morphMany(Fund::class, 'fundable');
    }

    // payment By
    public function user()
    {
        return $this->belongsTo(User::class,'user_id','id');
    }

    public function sellPost()
    {
        return $this->belongsTo(SellPost::class, 'sell_post_id');
    }

    public function sellPostUser()
    {
        return $this->belongsToT(SellPost::class, 'sell_post_id');
    }

}
PK     x\Jt      Models/TopUpService.phpnu [        <?php

namespace App\Models;

use App\Scopes\EnsureTopUpIdScope;
use App\Traits\Upload;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class TopUpService extends Model
{
    use HasFactory, Upload;

    protected $guarded = ['id'];
    protected $appends = ['image_path'];
    protected $casts = [
        'old_data' => 'object',
        'campaign_data' => 'object',
    ];

    protected static function booted()
    {
        static::saved(function ($model) {
            if (!isset($model->top_up_id)) {
                static::addGlobalScope(new EnsureTopUpIdScope);
                $model->refresh();
            }
            dispatch(new \App\Jobs\UpdateChildCountJob($model->topUp->category_id, 'top_up'));
        });
    }

    public function topUp()
    {
        return $this->belongsTo(TopUp::class, 'top_up_id');
    }

    public function getImagePathAttribute()
    {
        return getFile($this->image_driver, $this->image);
    }


    public function imagePath()
    {
        return getFile($this->image_driver, $this->image);
    }

    public function setImageAttribute($image)
    {
        if ($image) {
            $uploadedImage = $this->fileUpload($image, config('filelocation.topUpService.path'), null, config('filelocation.topUpService.size'), 'webp', 60);
            if ($uploadedImage) {
                $this->attributes['image'] = $uploadedImage['path'];
                $this->attributes['image_driver'] = $uploadedImage['driver'];
            }
        }
    }

    public function getDiscount()
    {
        $discount = 0;
        if ($this->discount && $this->price) {
            if ($this->discount_type == 'percentage') {
                $discount = ($this->discount * $this->price) / 100;
            } elseif ($this->discount_type == 'flat') {
                $discount = $this->discount;
            }
        }
        return round($discount, 2);
    }

    public function orderDetails()
    {
        return $this->morphMany(OrderDetail::class, 'detailable');
    }
}
PK     x\
W  W    Models/Language.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Language extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'short_name',
        'flag',
        'flag_driver',
        'status',
        'rtl',
        'default_status',
    ];

    public function setNameAttribute($value)
    {
        $this->attributes['name'] = ucwords($value);
    }

    public function setShortNameAttribute($value)
    {
        $this->attributes['short_name'] = strtolower($value);
    }

    public function getStatusClass()
    {
        return [
            '0' => 'danger',
            '1' => 'success',
        ][$this->status] ?? 'danger';
    }
    public function notificationTemplates()
    {
        return $this->hasMany(NotificationTemplate::class,'language_id');
    }

    public function pageDetails()
    {
        return $this->hasMany(PageDetail::class,'language_id');
    }

    public function contentDetails()
    {
        return $this->hasMany(ContentDetails::class,'language_id');
    }

}
PK     x\LTv  v    Models/SupportTicketMessage.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SupportTicketMessage extends Model
{
    use HasFactory;

    protected $fillable = ['support_ticket_id', 'admin_id', 'message'];

    public function ticket(){
        return $this->belongsTo(SupportTicket::class, 'support_ticket_id', 'id');
    }

    public function admin(){
        return $this->belongsTo(Admin::class, 'admin_id', 'id');
    }

    public function attachments()
    {
        return $this->hasMany(SupportTicketAttachment::class,'support_ticket_message_id','id');
    }



}
PK     x\/      Models/ManageMenu.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ManageMenu extends Model
{
    use HasFactory;

    protected $fillable = ['menu_section', 'menu_items'];
    protected $casts = ['menu_items' => 'array'];

    protected static function boot()
    {
        parent::boot();
        static::saved(function () {
            \Cache::forget('headerMenu');
            \Cache::forget('footerMenu');
        });
    }
}
PK     x\p!      Models/Order.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class Order extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $casts = [
        'info' => 'object'
    ];

    public function scopeOwn($query)
    {
        return $query->where('user_id', auth()->id());
    }

    public function scopePayment($query)
    {
        return $query->where('payment_status', 1);
    }

    public function scopeType($query, $type)
    {
        return $query->where('order_for', $type);
    }

    public function orderDetails()
    {
        return $this->hasMany(OrderDetail::class, 'order_id');
    }

    public function user()
    {
        return $this->belongsTo(User::class,'user_id');
    }

    public function gateway()
    {
        return $this->belongsTo(Gateway::class,'payment_method_id');
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class,'coupon_id');
    }

    public static function boot(): void
    {
        parent::boot();
        static::creating(function (Order $order) {
            if (empty($order->utr)) {
                $order->utr = self::generateOrderNumber();
            }
        });
    }

    public static function generateOrderNumber()
    {
        return DB::transaction(function () {
            $lastOrder = self::lockForUpdate()->orderBy('id', 'desc')->first();
            if ($lastOrder && isset($lastOrder->trx_id)) {
                $lastOrderNumber = (int)filter_var($lastOrder->trx_id, FILTER_SANITIZE_NUMBER_INT);
                $newOrderNumber = $lastOrderNumber + 1;
            } else {
                $newOrderNumber = strRandomNum(12);
            }

            while (self::where('utr', 'O' . $newOrderNumber)->exists()) {
                $newOrderNumber = (int)$newOrderNumber + 1;
            }
            return 'O' . $newOrderNumber;
        });
    }
}
PK     x\L~        Models/RazorpayContact.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RazorpayContact extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
}
PK     x\G\  \    Models/Category.phpnu [        <?php

namespace App\Models;

use App\Traits\Upload;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Category extends Model
{
    use HasFactory, SoftDeletes, Upload;

    protected $guarded = ['id'];

    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }

    public function scopeType($query, $type)
    {
        return $query->where('type', $type);
    }

    public function scopeSort($query)
    {
        return $query->orderBy('sort_by', 'ASC');
    }

}
PK     x\i      Models/Code.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Code extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    public function scopeServiceWise($query, $model, $id)
    {
        return $query->where(['codeable_type' => $model, 'codeable_id' => $id]);
    }

    public function codeable()
    {
        return $this->morphTo();
    }

}
PK     x\Gr      Models/Deposit.phpnu [        <?php

namespace App\Models;


use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class Deposit extends Model
{
    use HasFactory, Prunable;

    protected $guarded = ['id'];

    protected $casts = [
        'information' => 'object'
    ];

    public function transactional()
    {
        return $this->morphOne(Transaction::class, 'transactional');
    }

    public function depositable()
    {
        return $this->morphTo();
    }


    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function gateway()
    {
        return $this->belongsTo(Gateway::class, 'payment_method_id', 'id');
    }

    public function picture()
    {
        $image = optional($this->gateway)->image;
        if (!$image) {
            $firstLetter = substr(optional($this->gateway)->name, 0, 1);
            return '<div class="avatar avatar-sm avatar-soft-primary avatar-circle">
                        <span class="avatar-initials">' . $firstLetter . '</span>
                     </div>';

        } else {
            $url = getFile(optional($this->gateway)->driver, optional($this->gateway)->image);
            return '<div class="avatar avatar-sm avatar-circle">
                        <img class="avatar-img" src="' . $url . '" alt="Image Description">
                     </div>';

        }
    }
    public static function boot(): void
    {
        parent::boot();
        static::saved(function () {
            Cache::forget('paymentRecord');
        });

        static::creating(function (Deposit $deposit) {
            if (empty($deposit->trx_id)) {
                $deposit->trx_id = self::generateOrderNumber();
            }
        });
    }

    public static function generateOrderNumber()
    {
        return DB::transaction(function () {
            $lastOrder = self::lockForUpdate()->orderBy('id', 'desc')->first();
            if ($lastOrder && isset($lastOrder->trx_id)) {
                $lastOrderNumber = (int)filter_var($lastOrder->trx_id, FILTER_SANITIZE_NUMBER_INT);
                $newOrderNumber = $lastOrderNumber + 1;
            } else {
                $newOrderNumber = strRandomNum(12);
            }

            while (self::where('trx_id', 'D' . $newOrderNumber)->exists()) {
                $newOrderNumber = (int)$newOrderNumber + 1;
            }
            return 'D' . $newOrderNumber;
        });
    }

    public function getStatusClass()
    {
        return [
                '0' => 'text-dark',
                '1' => 'text-success',
                '2' => 'text-dark',
                '3' => 'text-danger',
            ][$this->status] ?? 'text-danger';
    }

    public function prunable(): Builder
    {
        return static::where('created_at', '<=', now()->subDays(2));
    }

}
PK     x\5J      Models/Review.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Review extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function reviewable()
    {
        return $this->morphTo();
    }
}
PK     x\3      Models/ContentDetails.phpnu [        <?php

namespace App\Models;

use App\Traits\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ContentDetails extends Model
{
    use HasFactory, Translatable;

    public $fillable = ['content_id', 'language_id', 'description'];

    public $casts = ['description' => "object"];

    public function content()
    {
        return $this->belongsTo(Content::class, 'content_id', 'id');
    }

}
PK     x\o      Models/InAppNotification.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class InAppNotification extends Model
{
    use HasFactory;

    protected $fillable = ['in_app_notificationable_id', 'in_app_notificationable_type', 'description'];

    protected $casts = [
        'description' => 'object'
    ];

    protected $appends = ['formatted_date'];

    public function getFormattedDateAttribute(){
        return $this->created_at->format('F d, Y h:i A');
    }

    public function inAppNotificationable()
    {
        return $this->morphTo(__FUNCTION__, 'in_app_notificationable_type', 'in_app_notificationable_id');
    }
}
PK     x\$Y)  )    Models/ActivityLog.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ActivityLog extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    public function activityable()
    {
        return $this->morphTo();
    }
}
PK     x\sh
  
    Models/Admin.phpnu [        <?php

namespace App\Models;

use App\Traits\Notify;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Cache;
use Laravel\Sanctum\HasApiTokens;

class Admin extends Authenticatable
{
    use HasFactory, Notifiable, HasApiTokens, Notify;

    protected $guarded = ['id'];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
        'verification_token'
    ];

    protected $appends = ['imgPath', 'LastSeenActivity'];

    public function fireBaseToken()
    {
        return $this->morphMany(FireBaseToken::class, 'tokenable');
    }

    public function inAppNotification()
    {
        return $this->morphOne(InAppNotification::class, 'inAppNotificationable', 'in_app_notificationable_type', 'in_app_notificationable_id');
    }

    public function sendPasswordResetNotification($token)
    {
        $this->mail($this, 'PASSWORD_RESET', $params = [
            'message' => '<a href="' . url('admin/password/reset', $token) . '?email=' . $this->email . '" target="_blank">Click To Reset Password</a>'
        ]);
    }

    public function profilePicture()
    {
        $disk = $this->image_driver;
        $image = $this->image ?? 'unknown';

        try {
            if ($disk == 'local') {
                $localImage = asset('/assets/upload') . '/' . $image;
                return \Illuminate\Support\Facades\Storage::disk($disk)->exists($image) ? $localImage : asset(config('location.default'));
            } else {
                return \Illuminate\Support\Facades\Storage::disk($disk)->exists($image) ? \Illuminate\Support\Facades\Storage::disk($disk)->url($image) : asset(config('filelocation.default'));
            }
        } catch (\Exception $e) {
            return asset(config('location.default'));
        }
    }
    public function chatable()
    {
        return $this->morphOne(SellPostChat::class, 'chatable');
    }
    public function activities()
    {
        return $this->morphMany(ActivityLog::class, 'activityable');
    }
    public function getImgPathAttribute()
    {
        return getFile($this->image_driver, $this->image);
    }
    public function getLastSeenActivityAttribute()
    {
        if (Cache::has('admin-is-online-' . $this->id)) {
            return true;
        } else {
            return false;
        }
    }

    public function role()
    {
        return $this->belongsTo(Role::class, 'role_id');
    }

}
PK     x\NS-`  `    Models/BlogDetails.phpnu [        <?php

namespace App\Models;

use App\Traits\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class BlogDetails extends Model
{
    use HasFactory, Translatable;

    protected $guarded = ['id'];

    public function blog(){
        return $this->belongsTo(Blog::class, 'blog_id');
    }

}
PK     x\,s
@  @    Models/FileStorage.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FileStorage extends Model
{
    use HasFactory;

    protected $fillable = ['code', 'name', 'logo', 'driver', 'status', 'parameters'];

    protected $casts = ['parameters' => 'array'];
}
PK     x\.	  	    Models/Card.phpnu [        <?php

namespace App\Models;

use App\Scopes\EnsureCategoryIdScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Card extends Model
{
    use HasFactory, SoftDeletes;

    protected $guarded = ['id'];
    protected $casts = [
        'image' => 'object',
    ];
    protected $appends = ['preview_image', 'card_detail_route'];

    protected static function booted()
    {
        static::saving(function ($model) {
            if (isset($model->name)) {
                $model->slug = slug($model->name);
            }
        });

        static::saved(function ($model) {
            if (!isset($model->category_id)) {
                static::addGlobalScope(new EnsureCategoryIdScope);
                $model->refresh();
            }
            dispatch(new \App\Jobs\UpdateChildCountJob($model->category_id, 'card'));
        });
    }

    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id');
    }

    public function services()
    {
        return $this->hasMany(CardService::class, 'card_id');
    }

    public function activeServices()
    {
        return $this->hasMany(CardService::class, 'card_id')->where('status', 1)->orderBy('sort_by', 'ASC');
    }


    public function activeCodeCount()
    {
        return $this->activeServices()
            ->withCount(['codes as active_codes_count' => function ($query) {
                $query->where('status', 1);
            }])
            ->get()
            ->sum('active_codes_count');
    }

    public function serviceWithLowestPrice()
    {
        $lowPriceData = \Cache::get('lowPriceData_' . $this->id);
        if (!$lowPriceData) {
            $lowPriceData = $this->activeServices->sortBy('price')->first() ?? new CardService();
            \Cache::put('lowPriceData_' . $this->id, $lowPriceData);
        }
        return $lowPriceData;
    }

    public function reviewByReviewer()
    {
        return $this->morphOne(Review::class, 'reviewable')->where('user_id', auth()->id());
    }

    public function getPreviewImageAttribute()
    {
        if (isset($this->image->preview_driver) && isset($this->image->preview)) {
            return getFile($this->image->preview_driver, $this->image->preview);
        }
    }

    public function getCardDetailRouteAttribute()
    {
        if (isset($this->slug)) {
            return route('card.details', $this->slug);
        }
    }
}
PK     x\2ln  n    Models/PageDetail.phpnu [        <?php

namespace App\Models;

use App\Traits\Translatable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class PageDetail extends Model
{
    use HasFactory, Translatable;

    protected $fillable = ['page_id', 'language_id', 'name', 'content', 'sections'];

    protected $casts = ['sections' => 'array'];


    public function page()
    {
        return $this->belongsTo(Page::class, 'page_id');
    }

    public function language()
    {
        return $this->belongsTo(Language::class, 'language_id', 'id');
    }
}
PK     x\$R
  
    Models/SellPostCategory.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class SellPostCategory extends Model
{
    use HasFactory;

    protected $guarded = ['id'];
    protected $casts=[
        'form_field' => 'object',
        'post_specification_form' => 'object'
    ];


    public function language()
    {
        return $this->hasMany(Language::class, 'language_id', 'id');
    }

    public function details(){
        return $this->hasOne(SellPostCategoryDetail::class);
    }


    public function getStatusMessageAttribute()
    {
        if ($this->status == 0) {
            return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In-Active') . '
                  </span>';
        }
        return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';
    }

    public function post()
    {
        return $this->hasMany(SellPost::class,'category_id');
    }
    public function activePost()
    {
        return $this->hasMany(SellPost::class,'category_id')->where('payment_status','!=','1')->where('status',1);
    }
}
PK     x\E|  |    Models/FireBaseToken.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class FireBaseToken extends Model
{
    use HasFactory;

    protected $fillable = ['tokenable_id', 'tokenable_type', 'token'];

    public function tokenable()
    {
        return $this->morphTo(__FUNCTION__, 'tokenable_type', 'tokenable_id');
    }
}
PK     x\-,[  [    Models/BasicControl.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;

class BasicControl extends Model
{
    use HasFactory;

    protected $guarded = ['id'];

    protected function metaKeywords(): Attribute
    {
        return Attribute::make(
            get: fn(string $value) => explode(", ", $value),
        );
    }

    protected static function boot()
    {
        parent::boot();
        static::saved(function () {
            \Cache::forget('ConfigureSetting');
        });
    }
}
PK     x\`        Models/UserTracking.phpnu [        <?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class UserTracking extends Model
{
    protected $guarded = ['id'];

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}
PK     x\@F\k  k    Exports/TopUpServiceExport.phpnu [        <?php

namespace App\Exports;

use App\Models\TopUpService;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class TopUpServiceExport implements FromCollection, WithHeadings
{
    private $search;

    public function __construct($request)
    {
        $this->search = $request;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $currency = basicControl()->base_currency;
        $dateTimeFormat = basicControl()->date_time_format;

        return TopUpService::where('top_up_id', $this->search['topUp'])
            ->orderBy('sort_by', 'asc')
            ->get()
            ->map(function ($query) use ($currency, $dateTimeFormat) {
                $discount = $query->getDiscount();
                $discountType = $query->discount_type == 'flat' ? $currency : '%';

                return [
                    'Service Name' => $query->name,
                    'Price' => formatAmount($query->price - $discount) . ' ' . $currency,
                    'Discount' => $query->discount . ' ' . $discountType,
                    'Discount Amount' => formatAmount($discount) . ' ' . $currency,
                    'Status' => $query->status == 1 ? 'Active' : 'In-active',
                    'Created At' => dateTime($query->created_at, $dateTimeFormat),
                ];
            });
    }

    public function headings(): array
    {
        return [
            'Service Name',
            'Price',
            'Discount',
            'Discount Amount',
            'Status',
            'Created At',
        ];
    }

}
PK     x\Wok  k    Exports/CodeExport.phpnu [        <?php

namespace App\Exports;

use App\Models\Code;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class CodeExport implements FromCollection, WithHeadings
{
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $dateTimeFormat = basicControl()->date_time_format;

        return Code::where('codeable_type', $this->data['codeable_type'])->where('codeable_id', $this->data['codeable_id'])
            ->orderBy('id', 'desc')
            ->get()
            ->map(function ($query) use ($dateTimeFormat) {
                return [
                    'Code' => $query->passcode,
                    'Status' => $query->status == 1 ? 'Active' : 'In-active',
                    'Created At' => dateTime($query->created_at, $dateTimeFormat),
                ];
            });
    }

    public function headings(): array
    {
        return [
            'Code',
            'Status',
            'Created At',
        ];
    }
}
PK     x\<g  g    Exports/CardServiceExport.phpnu [        <?php

namespace App\Exports;

use App\Models\CardService;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;

class CardServiceExport implements FromCollection, WithHeadings
{
    private $search;

    public function __construct($request)
    {
        $this->search = $request;
    }

    /**
     * @return \Illuminate\Support\Collection
     */
    public function collection()
    {
        $currency = basicControl()->base_currency;
        $dateTimeFormat = basicControl()->date_time_format;

        return CardService::where('card_id', $this->search['card_id'])
            ->orderBy('sort_by', 'asc')
            ->get()
            ->map(function ($query) use ($currency, $dateTimeFormat) {
                $discount = $query->getDiscount();
                $discountType = $query->discount_type == 'flat' ? $currency : '%';

                return [
                    'Service Name' => $query->name,
                    'Price' => formatAmount($query->price - $discount) . ' ' . $currency,
                    'Discount' => $query->discount . ' ' . $discountType,
                    'Discount Amount' => formatAmount($discount) . ' ' . $currency,
                    'Status' => $query->status == 1 ? 'Active' : 'In-active',
                    'Created At' => dateTime($query->created_at, $dateTimeFormat),
                ];
            });
    }

    public function headings(): array
    {
        return [
            'Service Name',
            'Price',
            'Discount',
            'Discount Amount',
            'Status',
            'Created At',
        ];
    }
}
PK     x\z|V  V    Jobs/UpdateChildCountJob.phpnu [        <?php

namespace App\Jobs;

use App\Models\Card;
use App\Models\Category;
use App\Models\Game;
use App\Models\TopUp;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UpdateChildCountJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $categoryId;
    public $type;

    /**
     * Create a new job instance.
     */
    public function __construct($categoryId, $type)
    {
        $this->categoryId = $categoryId;
        $this->type = $type;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $activeChildren = 0;
        switch ($this->type) {
            case 'card':
                $activeChildren = Card::where('category_id', $this->categoryId)
                    ->where('status', 1)->whereHas('activeServices')->count();
                break;

            case 'top_up':
                $activeChildren = TopUp::where('category_id', $this->categoryId)
                    ->where('status', 1)->whereHas('activeServices')->count();
                break;
        }

        Category::where('id', $this->categoryId)->update([
            'active_children' => $activeChildren,
        ]);
    }
}
PK     x\n̩    "  Jobs/UserNotificationTempletes.phpnu [        <?php

namespace App\Jobs;

use App\Models\NotificationSettings;
use App\Models\NotificationTemplate;
use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UserNotificationTempletes implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     */
    private $userID;
    public function __construct($userID)
    {
        $this->userID = $userID;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $template_keys = NotificationTemplate::where('notify_for', 0)
            ->where(function ($query) {
                $query->whereNotNull('email')
                    ->orWhereNotNull('push')
                    ->orWhereNotNull('sms')
                    ->orWhereNotNull('in_app');
            })
            ->pluck('template_key');

        $notifyFor = new NotificationSettings();
        $notifyFor->notifyable_id = $this->userID;
        $notifyFor->notifyable_type = User::class;
        $notifyFor->template_email_key = $template_keys;
        $notifyFor->template_sms_key = $template_keys;
        $notifyFor->template_push_key = $template_keys;
        $notifyFor->template_in_app_key = $template_keys;
        $notifyFor->save();
    }
}
PK     x\K  K    Jobs/UserTrackingJob.phpnu [        <?php

namespace App\Jobs;

use App\Helpers\UserSystemInfo;
use App\Models\UserTracking;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Stevebauman\Location\Facades\Location;

class UserTrackingJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $userId;
    public $ip;
    public $remark;

    /**
     * Create a new job instance.
     */
    public function __construct($userId, $ip, $remark)
    {
        $this->userId = $userId;
        $this->ip = $ip;
        $this->remark = $remark;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $currentUser = Location::get($this->ip);

        $userTracking = new UserTracking();

        $userTracking->user_id = $this->userId;
        $userTracking->ip = $this->ip;
        $userTracking->country_name = $currentUser->countryName;
        $userTracking->country_code = $currentUser->countryCode;
        $userTracking->region_name = $currentUser->regionName;
        $userTracking->city_name = $currentUser->cityName;
        $userTracking->latitude = $currentUser->latitude;
        $userTracking->longitude = $currentUser->longitude;
        $userTracking->timezone = $currentUser->timezone;
        $userTracking->device = UserSystemInfo::get_device();
        $userTracking->remark = $this->remark;

        $userTracking->save();
    }
}
PK     x\       Jobs/CodeSendBuyer.phpnu [        <?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class CodeSendBuyer implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public $order;

    /**
     * Create a new job instance.
     */
    public function __construct($order)
    {
        $this->order = $order;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $order = $this->order;
        $orderStatus = 1;
        foreach ($order->orderDetails as $detail) {
            $service = $detail->detailable;
            if (!$service) {
                continue;
            }

            $codeLists = $service->codes()->where('status', 1)->take($detail->qty)->get(['id', 'status', 'passcode']);
            $sendCodeList = $codeLists->pluck('passcode');
            $stock_short = max(0, $detail->qty - count($sendCodeList));

            $detail->card_codes = $sendCodeList;
            $detail->stock_short = $stock_short;
            $detail->status = ($stock_short == 0) ? 1 : 3;
            $detail->save();

            if ($stock_short) {
                $orderStatus = 3;
            }

            $codeLists->each(function ($code) {
                $code->delete();
            });

            $this->addedSellList($service->card()->select(['id', 'sell_count'])->first());
        }

        $order->status = $orderStatus;
        $order->save();
    }

    public function addedSellList($card): void
    {
        if ($card) {
            $card->sell_count += 1;
            $card->save();
        }
    }
}
PK     x\`
  `
    Jobs/UserAllRecordDeleteJob.phpnu [        <?php

namespace App\Jobs;

use App\Models\SellPost;
use App\Models\SupportTicket;
use App\Traits\Upload;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UserAllRecordDeleteJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels, Upload;

    public $userID;

    /**
     * Create a new job instance.
     */
    public function __construct($userID)
    {
        $this->userID = $userID;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        DB::table('deposits')->where('user_id', $this->userID)->delete();
        DB::table('orders')->where('user_id', $this->userID)->delete();
        DB::table('order_details')->where('user_id', $this->userID)->delete();
        DB::table('reviews')->where('user_id', $this->userID)->delete();
        DB::table('transactions')->where('user_id', $this->userID)->delete();
        DB::table('user_logins')->where('user_id', $this->userID)->delete();
        DB::table('orders')->where('user_id', $this->userID)->delete();
        DB::table('order_details')->where('user_id', $this->userID)->delete();
        DB::table('roles')->where('user_id', $this->userID)->delete();
        DB::table('sell_post_payments')->where('user_id', $this->userID)->delete();
        DB::table('user_trackings')->where('user_id', $this->userID)->delete();

        SellPost::where('user_id', $this->userID)->get()->map(function ($item) {
            $item->image->map(function ($img) use ($item){
                $this->fileDelete($item->image_driver, $img);
                $img->delete();
            });
            $item->delete();
        });
        DB::table('sell_posts')->where('user_id', $this->userID)->delete();


        SupportTicket::where('user_id', $this->userID)->get()->map(function ($item) {
            $item->messages()->get()->map(function ($message) {
                if (count($message->attachments) > 0) {
                    foreach ($message->attachments as $img) {
                        $this->fileDelete($img->driver, $img->file);
                        $img->delete();
                    }
                }
            });
            $item->messages()->delete();
            $item->delete();
        });


        DB::table('in_app_notifications')->where('in_app_notificationable_id', $this->userID)->where('in_app_notificationable_type','App\Models\User')->delete();
    }
}
PK     x\Vd!  !  !  Jobs/UpdateReviewAndRatingJob.phpnu [        <?php

namespace App\Jobs;

use App\Models\Review;
use App\Models\TopUp;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class UpdateReviewAndRatingJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $rating;
    private $model;
    private $item;

    /**
     * Create a new job instance.
     */
    public function __construct($rating , $model, $item)
    {
        $this->rating = $rating;
        $this->model = $model;
        $this->item = $item;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {

        $reviewData = Review::where('reviewable_id', $this->item)
            ->where('reviewable_type', $this->model)
            ->selectRaw('COUNT(*) as total, AVG(rating) as avg_rating')
            ->first();

        $totalReviews = $reviewData->total ?? 0;
        $avgRating = $reviewData->avg_rating ?? 0;
        $topup = TopUp::find($this->item);
        if ($topup) {
            $topup->total_review = $totalReviews;
            $topup->avg_rating = $avgRating;
            $topup->save();
        }
    }
}
PK     x\-a[  [  !  Services/Payout/paystack/Card.phpnu [        <?php

namespace App\Services\Payout\paystack;

use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Transaction;
use Facades\App\Services\BasicCurl;

class Card
{
	public static function getBank($currencyCode)
	{
		$method = PayoutMethod::where('code', 'paystack')->first();
		$url = 'https://api.paystack.co/bank/?currency=' . strtoupper($currencyCode);


		$SEC_KEY = optional($method->parameters)->Secret_key;
		$headers = [
			'Content-Type: application/json',
			'Authorization: Bearer ' . $SEC_KEY
		];


		$response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
		$result = json_decode($response);

		if (!isset($result->status)) {
			return [
				'status' => 'error',
				'data' => 'Something went wrong try again'
			];
		}

		if ($result->status == 'true') {
			return [
				'status' => 'success',
				'data' => $result->data
			];
		} else {
			return [
				'status' => 'error',
				'data' => $result->message
			];
		}
	}

	public static function payouts($payout)
	{
		$method = PayoutMethod::where('code', 'paystack')->first();
		$api = 'https://api.paystack.co/';
		$SEC_KEY = optional($method->parameters)->Secret_key;
		$headers = [
			'Content-Type: application/json',
			'Authorization: Bearer ' . $SEC_KEY
		];

		$card = new Card();
		$res = $card->createRecipient($api, $headers, $payout);
		if ($res['status'] == 'error') {
			return [
				'status' => 'error',
				'data' => $res['data']
			];
		}

		$recipient_code = $res['data'];
		$url = $api . 'transfer';
		$info = json_decode($payout->withdraw_information);
		$amount = (int)$info->amount->fieldValue;

		$postParam = [
			"source" => 'balance',
			"amount" => $amount,
			"recipient" => $recipient_code,
		];
		$response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
		$result = json_decode($response);

		if ($result->status == false) {
			return [
				'status' => 'error',
				'data' => $result->message
			];
		} elseif ($result->status == true) {
			return [
				'status' => 'success',
				'response_id' => $result->data->id
			];
		}

	}

	public static function createRecipient($api, $headers, $payout)
	{
		$url = $api . 'transferrecipient';
		$info = $payout->information;

		$postParam = [
			"type" => $info->type->field_value,
			"name" => $info->name->field_value,
			"account_number" => $info->account_number->field_value,
			"bank_code" => $info->bank_code->field_value,
			"currency" => $payout->payout_currency_code,
		];

		$response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
		$result = json_decode($response);

		if ($result->status == false) {
			return [
				'status' => 'error',
				'data' => $result->message
			];
		} elseif ($result->status == true) {
			return [
				'status' => 'success',
				'data' => $result->data->recipient_code
			];
		}
	}

    public function webhook($apiResponse)
    {
        if ($apiResponse) {
            if ($apiResponse->data) {
                $payout = Payout::where('response_id', $apiResponse->data->id)->first();
                if ($payout) {
                    if ($apiResponse->event == 'transfer.success') {
                        $payout->status = 2;
                        $payout->save();
                    } elseif ($apiResponse->event == 'transfer.failed') {
                        $payout->status = 6;
                        $payout->last_error = $apiResponse->data->complete_message;
                        $payout->save();
                    }
                }
            }
        }
    }
}
PK     x\I.  .  %  Services/Payout/perfectmoney/Card.phpnu [        <?php

namespace App\Services\Payout\perfectmoney;

use App\Models\PayoutMethod;
use Facades\App\Services\BasicCurl;

class Card
{
	public static function payouts($payout)
	{
		$method = PayoutMethod::where('code', 'perfectmoney')->first();
		$AccountID = optional($method->parameters)->Account_ID;
		$PassPhrase = optional($method->parameters)->Passphrase;
		$Payer_Account = optional($method->parameters)->Payer_Account;

		$info = $payout->information;
		$amount = $info->amount->field_value;

		$params = array('AccountID' => $AccountID,
			'PassPhrase' => '45P7GN1T8TlRfMRAPCqLArVHz',
			'Payer_Account' => $PassPhrase, // Admin ID - FROM WALLET
			'Payee_Account' => $Payer_Account, // User Id- TO WALLET
			'Amount' => $amount, // AMOUNT AFTER CALCULATION, in USD
			'PAY_IN' => 1, // Keep This
			'PAYMENT_ID' => 'abir 551211', // TRX NUM
		);
		$query = http_build_query($params);
		$url = 'https://perfectmoney.is/acct/confirm.asp?' . $query;
		$f = fopen($url, 'rb');

		if ($f === false) {
			echo 'error openning url';
			exit();
		}

		$out = array();
		$out = "";
		while (!feof($f)) $out .= fgets($f);
		fclose($f);

		if (!preg_match_all("/<input name='(.*)' type='hidden' value='(.*)'>/", $out, $result, PREG_SET_ORDER)) {
			echo 'Ivalid output';
			exit;

			$ar = "";

			foreach ($result as $item) {
				$ar .= "$item[1]:$item[2],";
			}
		}

		if (isset($result[0]) && $result[0][1] == 'ERROR') {
			return [
				'status' => 'error',
				'data' => $result[0][2]
			];
		} else {
			return [
				'status' => 'success',
				'response_id' => null
			];
		}
	}
}
PK     x\      Services/Payout/paypal/Card.phpnu [        <?php

namespace App\Services\Payout\paypal;

use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\RazorpayContact;
use App\Models\Transaction;
use Facades\App\Services\BasicCurl;

class Card
{
    public static function payouts($payout)
    {
        $method = PayoutMethod::where('code', 'paypal')->first();
        $info = json_decode($payout->withdraw_information);

        if ($method->environment == 'live') {
            $api = 'https://api-m.paypal.com/v1/';
        } else {
            $api = 'https://api-m.sandbox.paypal.com/v1/';
        }

        $CLIENT_ID = optional($method->parameters)->cleint_id;
        $KEY_SECRET = optional($method->parameters)->secret;

        $url = $api . 'payments/payouts';
        $recipient_type = $info->recipient_type->fieldValue;
        $value = $info->amount->fieldValue;
        $receiver = $info->receiver->fieldValue;

        $headers = [
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode("{$CLIENT_ID}:{$KEY_SECRET}")
        ];

        $postParam = [
            "sender_batch_header" => [
                "sender_batch_id" => substr(md5(mt_rand()), 0, 10),
                "email_subject" => "You have a payout!",
                "email_message" => "You have received a payout! Thanks for using our service!",
            ],
            "items" => [
                [
                    "recipient_type" => $recipient_type,
                    "amount" => [
                        "value" => $value,
                        "currency" => $payout->currency_code
                    ],
                    "receiver" => $receiver,
                ]
            ]
        ];

        $response = BasicCurl::payoutCurlPostRequestWithHeaders($url, $headers, $postParam);
        $result = json_decode($response);

        if (isset($result->batch_header)) {
            return [
                'status' => 'success',
                'response_id' => $result->batch_header->payout_batch_id
            ];
        } else {
            return [
                'status' => 'error',
                'data' => $result->details[0]->issue
            ];
        }
    }

    public function webhook($apiResponse)
    {
        if ($apiResponse) {
            if ($apiResponse->batch_header) {
                $payout = Payout::where('response_id', $apiResponse->batch_header->payout_batch_id)->first();
                if ($payout) {
                    if ($apiResponse->event_type == 'PAYMENT.PAYOUTSBATCH.SUCCESS' || $apiResponse->event_type == 'PAYMENT.PAYOUTS-ITEM.SUCCEEDED' || $apiResponse->event_type == 'PAYMENT.PAYOUTSBATCH.PROCESSING') {
                        if ($apiResponse->event_type != 'PAYMENT.PAYOUTSBATCH.PROCESSING') {
                            $payout->status = 2;
                            $payout->save();
                        }
                    } else {
                        $payout->status = 6;
                        $payout->last_error = $apiResponse->summary;
                        $payout->save();
                    }
                }
            }
        }
    }
}
PK     x\s       Services/Payout/binance/Card.phpnu [        <?php

namespace App\Services\Payout\binance;

use App\Models\PayoutMethod;
use Carbon\Carbon;
use Facades\App\Services\BasicCurl;
use Illuminate\Support\Facades\Http;

class Card
{
	public static function payouts($payout)
	{
		$method = PayoutMethod::where('code', 'binance')->first();
		$info = $payout->information;

		if ($method->environment == 'live') {
			$api = 'https://api.binance.com/sapi/v1/';
		} else {
			$api = 'https://testnet.binance.com/sapi/v1/';
		}

		$API_Key = optional($method->parameters)->API_Key;
		$KEY_Secret = optional($method->parameters)->KEY_Secret;

		$microtime = round(microtime(true) * 1000);
		$withoutF = preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', $microtime);

		$coin = $payout->payout_currency_code;
		$network = $info->network->field_value;
		$address = $info->address->field_value;
		$amount = (int)$info->amount->field_value;
		$recvWindow = 60000;

		$params = [
			'coin' => $coin,
			'network' => $network,
			'address' => $address,
			'amount' => $amount,
			'recvWindow' => $recvWindow,
			'timestamp' => $withoutF
		];

		$card = new Card();
		$query = $card->buildQuery($params);

		$signature = hash_hmac('sha256', $query, $KEY_Secret);

		$url = $api . "capital/withdraw/apply?coin=$coin&network=$network&address=$address&amount=$amount&recvWindow=$recvWindow&timestamp=$withoutF&signature=$signature";

		$response = BasicCurl::payoutBinanceCurlRequestWithHeaders($url, $API_Key, 'POST');
		$result = json_decode($response);
		if (!isset($result->msg)) {
			return [
				'status' => 'error',
				'data' => 'Something went wrong'
			];
		}
		if (isset($result->msg)) {
			return [
				'status' => 'error',
				'data' => $result->msg
			];
		}
		if (isset($result->id)) {
			return [
				'status' => 'success',
				'response_id' => $result->id
			];
		}

	}

	public static function getStatus()
	{
		$method = PayoutMethod::where('code', 'binance')->first();

		if ($method->environment == 'live') {
			$api = 'https://api.binance.com/sapi/v1/';
		} else {
			$api = 'https://testnet.binance.com/sapi/v1/';
		}

		$API_Key = optional($method->parameters)->API_Key;
		$KEY_Secret = optional($method->parameters)->KEY_Secret;

		$microtime = round(microtime(true) * 1000);
		$withoutF = preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', $microtime);
		$startTime = preg_replace('/(0)\.(\d+) (\d+)/', '$3$1$2', Carbon::now()->subDays(90)->getPreciseTimestamp(3));

		$params = [
			'startTime' => $startTime,
			'timestamp' => $withoutF,
		];

		$card = new Card();
		$query = $card->buildQuery($params);

		$signature = hash_hmac('sha256', $query, $KEY_Secret);

		$endTime = Carbon::now();
		$url = $api . "capital/withdraw/history?startTime=$startTime&timestamp=$withoutF&signature=$signature";

		$response = BasicCurl::payoutBinanceCurlRequestWithHeaders($url, $API_Key, 'GET');
		$result = json_decode($response);

		if (isset($result)) {
			return $result;
		}

	}

	function buildQuery(array $params)
	{
		$query_array = array();
		foreach ($params as $key => $value) {
			if (is_array($value)) {
				$query_array = array_merge($query_array, array_map(function ($v) use ($key) {
					return urlencode($key) . '=' . urlencode($v);
				}, $value));
			} else {
				$query_array[] = urlencode($key) . '=' . urlencode($value);
			}
		}
		return implode('&', $query_array);
	}
}
PK     x\.  .  $  Services/Payout/flutterwave/Card.phpnu [        <?php

namespace App\Services\Payout\flutterwave;

use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Transaction;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Card
{
    public static function getBank($countryCode)
    {
        $method = PayoutMethod::where('code', 'flutterwave')->first();
        $url = 'https://api.flutterwave.com/v3/banks/' . strtoupper($countryCode);
        $SEC_KEY = optional($method->parameters)->Secret_Key;
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $SEC_KEY
        ];

        $response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
        $result = json_decode($response);

        if (!isset($result->status)) {
            return [
                'status' => 'error',
                'data' => 'Something went wrong try again'
            ];
        }
        if ($result->status == 'error') {
            return [
                'status' => 'error',
                'data' => $result->message
            ];
        } elseif ($result->status == 'success') {
            return [
                'status' => 'success',
                'data' => $result->data
            ];
        }
    }

    public static function payouts($payout)
    {
        $method = PayoutMethod::where('code', 'flutterwave')->first();
        $url = 'https://api.flutterwave.com/v3/transfers';
        $SEC_KEY = optional($method->parameters)->Secret_Key;
        $headers = [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $SEC_KEY
        ];

        $postParam['currency'] = $payout->payout_currency_code;
        foreach ($payout->information as $key => $info) {
            $postParam[$key] = $info->field_value;
        }

        if ($payout->meta_field) {
            foreach ($payout->meta_field as $key => $info) {
                $postParam['meta'][$key] = $info->field_value;
            }
        }

        $postParam['amount'] = (int)$postParam['amount'];
        $postParam['callback_url'] = route('payoutIpn', $payout->PayoutMethod->code);

        $response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
        $result = json_decode($response);

        if (isset($result->status) && $result->status == 'error') {
            return [
                'status' => 'error',
                'data' => $result->message
            ];
        } elseif (isset($result->status) && $result->status == 'success') {
            return [
                'status' => 'success',
                'response_id' => $result->data->id
            ];
        }
    }

    public function webhook($apiResponse)
    {
        if ($apiResponse) {
            if ($apiResponse->event == 'transfer.completed') {
                if ($apiResponse->data) {
                    $payout = Payout::where('response_id', $apiResponse->data->id)->first();
                    if ($payout) {
                        if ($apiResponse->data->status == 'SUCCESSFUL') {
                            $payout->status = 2;
                            $payout->save();
                        }
                        if ($apiResponse->data->status == 'FAILED') {
                            $payout->status = 6;
                            $payout->last_error = $apiResponse->data->complete_message;
                            $payout->save();
                        }
                    }
                }
            }
        }
    }
}
PK     x\O̎    !  Services/Payout/razorpay/Card.phpnu [        <?php

namespace App\Services\Payout\razorpay;

use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\RazorpayContact;
use App\Models\Transaction;
use Facades\App\Services\BasicCurl;

class Card
{
    public static function payouts($payout)
    {
        $method = PayoutMethod::where('code', 'razorpay')->first();
        $api = 'https://api.razorpay.com/v1/';
        $KEY_ID = optional($method->parameters)->Key_Id;
        $KEY_SECRET = optional($method->parameters)->Key_Secret;
        $accountNumber = optional($method->parameters)->account_number;

        $card = new Card();
        $res = $card->createContact($api, $KEY_ID, $KEY_SECRET, $payout);
        if ($res['status'] == 'error') {
            return [
                'status' => 'error',
                'data' => $res['data']
            ];
        }

        $contact_id = $res['data'];
        $res = $card->createFund($api, $KEY_ID, $KEY_SECRET, $payout, $contact_id);
        if ($res['status'] == 'error') {
            return [
                'status' => 'error',
                'data' => $res['data']
            ];
        }

        $info = json_decode($payout->withdraw_information);
        $fund_account_id = $res['data'];
        $currencyCode = $payout->currency_code;
        $amount = (int)$info->amount->fieldValue;

        $url = $api . 'payouts';

        $postParam = [
            "account_number" => $accountNumber,
            "fund_account_id" => $fund_account_id,
            "amount" => $amount,
            "currency" => $currencyCode,
            "mode" => "IMPS",
            "purpose" => "payout",
        ];

        $response = BasicCurl::razorpayCurlPostRequestWithHeaders($url, $postParam, $KEY_ID, $KEY_SECRET);
        $result = json_decode($response);

        if (isset($result->error)) {
            return [
                'status' => 'error',
                'data' => $result->error->description
            ];
        } else {
            return [
                'status' => 'success',
                'response_id' => $result->id,
            ];
        }
    }

    public static function createContact($api, $KEY_ID, $KEY_SECRET, $payout)
    {

        $info = $payout->information;
        $name = $info->name->field_value;
        $email = $info->email->field_value;
        $contact = RazorpayContact::where('name', $name)->where('email', $email)->first();
        if ($contact) {
            return $contact->contact_id;
        }

        $url = $api . 'contacts';

        $postParam = [
            "name" => "Gaurav Kumar",
            "email" => "gaurav.kumar@example.com",
        ];

        $response = BasicCurl::razorpayCurlPostRequestWithHeaders($url, $postParam, $KEY_ID, $KEY_SECRET);
        $result = json_decode($response);

        if (isset($result->error)) {
            return [
                'status' => 'error',
                'data' => $result->error->description
            ];
        } else {
            return [
                'status' => 'success',
                'data' => $result->id
            ];
        }
    }

    public static function createFund($api, $KEY_ID, $KEY_SECRET, $payout, $contact_id)
    {
        $info = $payout->information;

        $url = $api . 'fund_accounts';
        $postParam = [
            "contact_id" => $contact_id,
            "account_type" => "bank_account",
            "bank_account" => [
                "name" => $info->name->field_value,
                "ifsc" => $info->ifsc->field_value,
                "account_number" => $info->account_number->field_value,
            ]
        ];

        $response = BasicCurl::razorpayCurlPostRequestWithHeaders($url, $postParam, $KEY_ID, $KEY_SECRET);
        $result = json_decode($response);

        if (isset($result->error)) {
            return [
                'status' => 'error',
                'data' => $result->error->description
            ];
        } else {
            return [
                'status' => 'success',
                'data' => $result->id
            ];
        }
    }

    public static function webhook($apiResponse)
    {
        if ($apiResponse) {
            if ($apiResponse->payload) {
                if ($apiResponse->payload->payout) {
                    if ($apiResponse->payload->payout->entity) {
                        $payout = Payout::where('response_id', $apiResponse->payload->payout->entity->id)->first();
                        if ($payout) {
                            if ($apiResponse->event == 'payout.processed' || $apiResponse->event == 'payout.updated') {
                                if ($payout->status != 2) {
                                    $payout->status = 2;
                                    $payout->save();
                                }
                            } elseif ($apiResponse->event == 'payout.rejected' || $apiResponse->event == 'payout.failed') {
                                $payout->status = 6;
                                $payout->last_error = $apiResponse->payload->payout->entity->status_details->description ?? '';
                                $payout->save();
                                updateWallet($payout->user_id, $payout->currency_id, $payout->transfer_amount, 1);
                            }
                        }
                    }
                }
            }
        }
        return true;
    }
}
PK     x\z%z:  :  !  Services/Payout/coinbase/Card.phpnu [        <?php

namespace App\Services\Payout\coinbase;

use App\Models\PayoutMethod;
use Facades\App\Services\BasicCurl;
use Illuminate\Support\Facades\Http;

class Card
{
	public static function payouts($payout)
	{
		$card = new Card();
		$method = PayoutMethod::where('code', 'coinbase')->first();
		$SEC_KEY = optional($method->parameters)->API_Secret;
		$API_Key = optional($method->parameters)->API_Key;
		$Api_Passphrase = optional($method->parameters)->Api_Passphrase;
		$info = $payout->information;
		$uri = "https://api-public.sandbox.exchange.coinbase.com/withdrawals/crypto";
		$time = time();

		$body = [
			'amount' => $info->amount->field_value,
			'currency' => $payout->currency_code,
			'crypto_address' => $info->crypto_address->field_value,
		];
		$sign = base64_encode(hash_hmac("sha256", $time . 'POST' . '/withdrawals/crypto' . json_encode($body), base64_decode($SEC_KEY), true));
		$response = Http::withHeaders($card->getHeaders($sign, $time, $API_Key, $Api_Passphrase))->post($uri, $body);
		$result = json_decode($response->body());

		if (isset($result->message)) {
			return [
				'status' => 'error',
				'data' => $result->message
			];
		} else {
			return [
				'status' => 'success',
			];
		}
	}

	protected function getHeaders($sign, $time, $API_Key, $Api_Passphrase)
	{
		return [
			'Accept' => 'application/json',
			'Content-Type' => 'application/json',
			'cb-access-key' => $API_Key,
			'cb-access-passphrase' => $Api_Passphrase,
			'cb-access-sign' => $sign,
			'cb-access-timestamp' => $time,
		];
	}
}
PK     x\I    %  Services/Gateway/cinetpay/Payment.phpnu [        <?php

namespace App\Services\Gateway\cinetpay;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;
use CinetPay\CinetPay;

class Payment
{
    public static function prepareData($order, $gateway)
    {
        $send['view'] = 'cinetpay';
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $order = null, $trx = null, $type = null)
    {


         $id_transaction = $order->transaction;

        if (!empty($id_transaction)) {
//            try {
                $apiKey = $gateway->parameters->apiKey; //Veuillez entrer votre apiKey
                $site_id = $gateway->parameters->site_id; //Veuillez entrer votre siteId

                $cp = new CinetPay($site_id, $apiKey);

                dd($cp);
                // Reprise exacte des bonnes données chez CinetPay
                $cp->setTransId($id_transaction)->getPayStatus();


                $paymentData = [
                    "cpm_site_id" => $cp->_cpm_site_id,
                    "signature" => $cp->_signature,
                    "cpm_amount" => $cp->_cpm_amount,
                    "cpm_trans_id" => $cp->_cpm_trans_id,
                    "cpm_custom" => $cp->_cpm_custom,
                    "cpm_currency" => $cp->_cpm_currency,
                    "cpm_payid" => $cp->_cpm_payid,
                    "cpm_payment_date" => $cp->_cpm_payment_date,
                    "cpm_payment_time" => $cp->_cpm_payment_time,
                    "cpm_error_message" => $cp->_cpm_error_message,
                    "payment_method" => $cp->_payment_method,
                    "cpm_phone_prefixe" => $cp->_cpm_phone_prefixe,
                    "cel_phone_num" => $cp->_cel_phone_num,
                    "cpm_ipn_ack" => $cp->_cpm_ipn_ack,
                    "created_at" => $cp->_created_at,
                    "updated_at" => $cp->_updated_at,
                    "cpm_result" => $cp->_cpm_result,
                    "cpm_trans_status" => $cp->_cpm_trans_status,
                    "cpm_designation" => $cp->_cpm_designation,
                    "buyer_name" => $cp->_buyer_name,
                ];
                // Recuperation de la ligne de la transaction dans votre base de données

                // Verification de l'etat du traitement de la commande

                // Si le paiement est bon alors ne traitez plus cette transaction : die();

                // On verifie que le montant payé chez CinetPay correspond à notre montant en base de données pour cette transaction

                // On verifie que le paiement est valide

                if ($cp->isValidPayment()) {
                    BasicService::preparePaymentUpgradation($order);

                    $data['status'] = 'success';
                    $data['msg'] = 'Transaction was successful.';
                    $data['redirect'] = route('success');
                } else {
                    $data['status'] = 'error';
                    $data['msg'] = 'it seems some issue in server to server communication. Kindly connect with administrator';
                    $data['redirect'] = route('failed');
                }
//            } catch ( \Exception $e) {
//
//                $data['status'] = 'error';
//                $data['msg'] = 'it seems some issue in server to server communication. Kindly connect with administrator';
//                $data['redirect'] = route('failed');
//            }
        } else {
            // redirection vers la page d'accueil
            die();
        }
        return $data;
    }
}
PK     x\2U3(  (  -  Services/Gateway/coinbasecommerce/Payment.phpnu [        <?php

namespace App\Services\Gateway\coinbasecommerce;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$apiKey = $gateway->parameters->api_key ?? '';

		$postParam = [
			'name' => optional($deposit->user)->name ?? $basic->site_title,
			'description' => "Pay to $basic->site_title",
			'local_price' => [
				'amount' => round($deposit->payable_amount, 2),
				'currency' => $deposit->payment_method_currency
			],
			'metadata' => [
				'trx' => $deposit->trx_id
			],
			'pricing_type' => "fixed_price",
			'redirect_url' => route('ipn', [$gateway->code, $deposit->trx_id]),
			'cancel_url' => twoStepPrevious($deposit)
		];

		$url = 'https://api.commerce.coinbase.com/charges';
		$headers = [
			'Content-Type:application/json',
			'X-CC-Api-Key: ' . "$apiKey",
			'X-CC-Version: 2018-03-22'];
		$response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
		$response = json_decode($response);

		if (@$response->error == '') {
			$send['redirect'] = true;
			$send['redirect_url'] = $response->data->hosted_url;
		} else {
			$send['error'] = true;
			$send['message'] = 'Some Problem Occurred. Try Again';
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$sentSign = $request->header('X-Cc-Webhook-Signature');
		$sig = hash_hmac('sha256', $request, $gateway->parameters->secret);
		if ($sentSign == $sig) {
			if ($request->event->type == 'charge:confirmed' && $deposit->status == 0) {
				BasicService::preparePaymentUpgradation($deposit);

				$data['status'] = 'success';
				$data['msg'] = 'Transaction was successful.';
				$data['redirect'] = route('success');
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'Invalid response.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Invalid response.';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\bO    #  Services/Gateway/khalti/Payment.phpnu [        <?php

namespace App\Services\Gateway\khalti;


use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$send['publicKey'] = $gateway->parameters->public_key ?? '';
		$send['productIdentity'] = $deposit->trx_id;
		$send['eventOnSuccess'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$send['amount'] = round($deposit->payable_amount);
		$send['view'] =  'khalti';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$token = $request->token;
		$args = http_build_query(array(
			'token' => $token,
			'amount' => round($deposit->payable_amount) * 100
		));

		if ($gateway->environment == 'test') {
			$url = "https://a.khalti.com/api/v2/payment/verify/";
		} else {
			$url = "https://khalti.com/api/v2/payment/verify/";
		}

		# Make the call using API.
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$secret_key = $gateway->parameters->secret_key ?? '';

		$headers = ["Authorization: Key $secret_key"];
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		// Response
		$response = curl_exec($ch);
		$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);

		$res = json_decode($response);

		if (isset($res->error_key) && $res->error_key == 'validation_error') {
			$data['status'] = 'error';
			$data['msg'] = 'Validation Error: ' . @$res->amount[0] . "<br>" . $res->token[0];
			$data['redirect'] = route('failed');
			return $data;
		}
		$forder = Deposit::where("trx_id", $res->product_identity)->orderBy('id', 'desc')->first();
		if ($forder) {
			BasicService::preparePaymentUpgradation($forder);
		}
	}
}
PK     x\D$    #  Services/Gateway/skrill/Payment.phpnu [        <?php

namespace App\Services\Gateway\skrill;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicService;

class Payment
{
	/*
	 * Skrill Gateway
	 */
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$val['pay_to_email'] = trim($gateway->parameters->pay_to_email);
		$val['transaction_id'] = "$deposit->trx_id";
		$val['return_url'] = route('success');
		$val['return_url_text'] = "Return $basic->site_title";
		$val['cancel_url'] = route('user.fund.index');
		$val['status_url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$val['language'] = 'EN';
		$val['amount'] = round($deposit->payable_amount, 2);
		$val['currency'] = "$deposit->payment_method_currency";
		$val['detail1_description'] = "$basic->site_title";
		$val['detail1_text'] = "Pay To $basic->site_title";
		$val['logo_url'] = getFile(config('location.logo.path') . 'logo.png');
		$send['val'] = $val;
		$send['view'] = 'redirect';
		$send['method'] = 'post';
		$send['url'] = 'https://www.moneybookers.com/app/payment.pl';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$concatFields = $request->merchant_id
			. $request->transaction_id
			. strtoupper(md5(trim($gateway->parameters->secret_key)))
			. $request->mb_amount
			. $request->mb_currency
			. $request->status;

		if (strtoupper(md5($concatFields)) == $request->md5sig && $request->status == 2 && $request->pay_to_email == trim($gateway->parameters->pay_to_email) && $deposit->status = '0') {
			BasicService::preparePaymentUpgradation($deposit);
		}
	}
}
PK     x\`    )  Services/Gateway/authorizenet/Payment.phpnu [        <?php

namespace App\Services\Gateway\authorizenet;

use Facades\App\Services\BasicService;
use net\authorize\api\constants\ANetEnvironment;
use net\authorize\api\contract\v1\CreateTransactionRequest;
use net\authorize\api\contract\v1\CreditCardType;
use net\authorize\api\contract\v1\MerchantAuthenticationType;
use net\authorize\api\contract\v1\PaymentType;
use net\authorize\api\contract\v1\TransactionRequestType;
use net\authorize\api\controller\CreateTransactionController;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$send['view'] =  'card';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		// Common setup for API credentials
		$merchantAuthentication = new MerchantAuthenticationType();
		$merchantAuthentication->setName($gateway->parameters->login_id);
		$merchantAuthentication->setTransactionKey($gateway->parameters->current_transaction_key);
		$refId = $deposit->trx_id;

		// Create the payment data for a credit card
		$creditCard = new CreditCardType();
		$creditCard->setCardNumber($request->card_number);
		$expiry = $request->expiry_year . '-' . $request->expiry_month;
		$creditCard->setExpirationDate($expiry);

		$paymentOne = new PaymentType();
		$paymentOne->setCreditCard($creditCard);

		// Create a transaction
		$transactionRequestType = new TransactionRequestType();
		$transactionRequestType->setTransactionType("authCaptureTransaction");
		$transactionRequestType->setAmount($deposit->payable_amount);
		$transactionRequestType->setPayment($paymentOne);

		$transactionRequest = new CreateTransactionRequest();
		$transactionRequest->setMerchantAuthentication($merchantAuthentication);
		$transactionRequest->setRefId($refId);
		$transactionRequest->setTransactionRequest($transactionRequestType);

		$controller = new CreateTransactionController($transactionRequest);
		$env = $gateway->environment == 'live' && $deposit->mode == 0 ? ANetEnvironment::PRODUCTION : ANetEnvironment::SANDBOX;
		$response = $controller->executeWithApiResponse($env);
		if ($response != null) {
			$tresponse = $response->getTransactionResponse();
			if (($tresponse != null) && ($tresponse->getResponseCode() == "1")) {
				BasicService::preparePaymentUpgradation($deposit);

				$data['status'] = 'success';
				$data['msg'] = 'Transaction was successful.';
				$data['redirect'] = route('success');
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'Invalid response.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Charge Credit Card Null response returned';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
    public static function mobileIpn($request, $gateway, $order = null)
    {
        // Common setup for API credentials
        $merchantAuthentication = new MerchantAuthenticationType();
        $merchantAuthentication->setName($gateway->parameters->login_id);
        $merchantAuthentication->setTransactionKey($gateway->parameters->current_transaction_key);
        $refId = $order->transaction;

        // Create the payment data for a credit card
        $creditCard = new CreditCardType();
        $creditCard->setCardNumber($request->card_number);
        $expiry = $request->expiry_year . '-' . $request->expiry_month;
        $creditCard->setExpirationDate($expiry);

        $paymentOne = new PaymentType();
        $paymentOne->setCreditCard($creditCard);

        // Create a transaction
        $transactionRequestType = new TransactionRequestType();
        $transactionRequestType->setTransactionType("authCaptureTransaction");
        $transactionRequestType->setAmount($order->final_amount);
        $transactionRequestType->setPayment($paymentOne);

        $transactionRequest = new CreateTransactionRequest();
        $transactionRequest->setMerchantAuthentication($merchantAuthentication);
        $transactionRequest->setRefId($refId);
        $transactionRequest->setTransactionRequest($transactionRequestType);

        $controller = new CreateTransactionController($transactionRequest);

        $response = $controller->executeWithApiResponse(ANetEnvironment::SANDBOX);

        if ($response != null) {
            $tresponse = $response->getTransactionResponse();
            if (($tresponse != null) && ($tresponse->getResponseCode() == "1")) {
                BasicService::preparePaymentUpgradation($order);
                return 'success';
            } else {
                return 'failed';
            }
        } else {
            return 'failed';
        }
    }
}
PK     x\Ng.    "  Services/Gateway/paytm/Payment.phpnu [        <?php

namespace App\Services\Gateway\paytm;

use App\Models\Deposit;
use App\Models\Fund;
use Facades\App\Services\BasicService;
use Facades\App\Services\BasicCurl;


class Payment
{
    public static function prepareData($order, $gateway)
    {

        $val['MID'] = trim($gateway->parameters->MID);
        $val['WEBSITE'] = trim($gateway->parameters->WEBSITE);
        $val['CHANNEL_ID'] = trim($gateway->parameters->CHANNEL_ID);
        $val['INDUSTRY_TYPE_ID'] = trim($gateway->parameters->INDUSTRY_TYPE_ID);
        $val['ORDER_ID'] = $order->trx_id;
        $val['TXN_AMOUNT'] = round($order->payable_amount, 2);
        $val['CUST_ID'] = $order->user_id;
        $val['CALLBACK_URL'] = route('ipn', [$gateway->code, $order->trx_id]);
        $val['CHECKSUMHASH'] = (new PayTM())->getChecksumFromArray($val, trim($gateway->parameters->merchant_key));
        $send['val'] = $val;
        $send['view'] = 'redirect';
        $send['method'] = 'post';

        $send['url'] = trim($gateway->parameters->process_transaction_url);
        return json_encode($send);

    }

    public static function ipn($request, $gateway, $order = null, $trx = null, $type = null)
    {
        define('PAYTM_ENVIRONMENT', trim($gateway->parameters->environment_url));
        define('PAYTM_MID', trim($gateway->parameters->MID));
        define('PAYTM_MERCHANT_KEY', trim($gateway->parameters->merchant_key));
        define('PAYTM_WEBSITE', trim($gateway->parameters->WEBSITE));

        $order = Deposit::with('gateway')
            ->whereHas('gateway', function ($query) {
                $query->where('code', 'paytm');
            })
            ->where('trx_id', $request->ORDERID)
            ->orderBy('id', 'desc')
            ->first();

//        dd($request->all());
        /* initialize an array */
        $paytmParams = array();

        /* body parameters */
        $paytmParams["body"] = array(
            "mid" => PAYTM_MID,
            /* Enter your order id which needs to be check status for */
            "orderId" => $request->ORDERID,
        );

        $checksum = PaytmChecksum::generateSignature(json_encode($paytmParams["body"], JSON_UNESCAPED_SLASHES), PAYTM_MERCHANT_KEY);

        /* head parameters */
        $paytmParams["head"] = array(
            "signature" => $checksum
        );

        /* prepare JSON string for request */
        $post_data = json_encode($paytmParams, JSON_UNESCAPED_SLASHES);

        $url = PAYTM_ENVIRONMENT . "/v3/order/status";

        $getcURLResponse = self::getcURLRequest($url, $paytmParams);


        if ($getcURLResponse && isset($getcURLResponse['body']['resultInfo']['resultStatus'])) {
            if ($getcURLResponse['body']['resultInfo']['resultStatus'] == 'TXN_SUCCESS' && $getcURLResponse['body']['txnAmount'] == round($order->payable_amount, 2)) {
                BasicService::preparePaymentUpgradation($order);

                $data['status'] = 'success';
                $data['msg'] = 'Transaction was successful.';
                $data['redirect'] = route('success');
            } else {
                $data['status'] = 'error';
                $data['msg'] = 'it seems some issue in server to server communication. Kindly connect with administrator';
                $data['redirect'] = route('failed');
            }
        } else {
            $data['status'] = 'error';
            $data['msg'] = $request->RESPMSG;
            $data['redirect'] = route('failed');
        }
        return $data;
    }

    public function getcURLRequest($url, $postData = array(), $headers = array("Content-Type: application/json"))
    {
        $post_data_string = json_encode($postData, JSON_UNESCAPED_SLASHES);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
        $response = curl_exec($ch);
        return json_decode($response, true);
    }


}
PK     x\6n    (  Services/Gateway/paytm/PaytmChecksum.phpnu [        <?php

namespace App\Services\Gateway\paytm;

class PaytmChecksum{

    private static $iv = "@@@@&&&&####$$$$";

    static public function encrypt($input, $key) {
        $key = html_entity_decode($key);

        if(function_exists('openssl_encrypt')){
            $data = openssl_encrypt ( $input , "AES-128-CBC" , $key, 0, self::$iv );
        } else {
            $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
            $input = self::pkcs5Pad($input, $size);
            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
            mcrypt_generic_init($td, $key, self::$iv);
            $data = mcrypt_generic($td, $input);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);
            $data = base64_encode($data);
        }
        return $data;
    }

    static public function decrypt($encrypted, $key) {
        $key = html_entity_decode($key);

        if(function_exists('openssl_decrypt')){
            $data = openssl_decrypt ( $encrypted , "AES-128-CBC" , $key, 0, self::$iv );
        } else {
            $encrypted = base64_decode($encrypted);
            $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
            mcrypt_generic_init($td, $key, self::$iv);
            $data = mdecrypt_generic($td, $encrypted);
            mcrypt_generic_deinit($td);
            mcrypt_module_close($td);
            $data = self::pkcs5Unpad($data);
            $data = rtrim($data);
        }
        return $data;
    }

    static public function generateSignature($params, $key) {
        if(!is_array($params) && !is_string($params)){
            throw new Exception("string or array expected, ".gettype($params)." given");
        }
        if(is_array($params)){
            $params = self::getStringByParams($params);
        }
        return self::generateSignatureByString($params, $key);
    }

    static public function verifySignature($params, $key, $checksum){
        if(!is_array($params) && !is_string($params)){
            throw new Exception("string or array expected, ".gettype($params)." given");
        }
        if(is_array($params)){
            $params = self::getStringByParams($params);
        }
        return self::verifySignatureByString($params, $key, $checksum);
    }

    static private function generateSignatureByString($params, $key){
        $salt = self::generateRandomString(4);
        return self::calculateChecksum($params, $key, $salt);
    }

    static private function verifySignatureByString($params, $key, $checksum){
        $paytm_hash = self::decrypt($checksum, $key);
        $salt = substr($paytm_hash, -4);
        return $paytm_hash == self::calculateHash($params, $salt) ? true : false;
    }

    static private function generateRandomString($length) {
        $random = "";
        srand((double) microtime() * 1000000);

        $data = "9876543210ZYXWVUTSRQPONMLKJIHGFEDCBAabcdefghijklmnopqrstuvwxyz!@#$&_";

        for ($i = 0; $i < $length; $i++) {
            $random .= substr($data, (rand() % (strlen($data))), 1);
        }

        return $random;
    }

    static private function getStringByParams($params) {
        ksort($params);
        $params = array_map(function ($value){
            return ($value == null) ? "" : $value;
        }, $params);
        return implode("|", $params);
    }

    static private function calculateHash($params, $salt){
        $finalString = $params . "|" . $salt;
        $hash = hash("sha256", $finalString);
        return $hash . $salt;
    }

    static private function calculateChecksum($params, $key, $salt){
        $hashString = self::calculateHash($params, $salt);
        return self::encrypt($hashString, $key);
    }

    static private function pkcs5Pad($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }

    static private function pkcs5Unpad($text) {
        $pad = ord($text{strlen($text) - 1});
        if ($pad > strlen($text))
            return false;
        return substr($text, 0, -1 * $pad);
    }
}
PK     x\       Services/Gateway/paytm/PayTM.phpnu [        <?php

namespace App\Services\Gateway\paytm;

class PayTM{
    /*
     *  For PayTM
     */

    public function encrypt_e($input, $ky)
    {
        $key   = html_entity_decode($ky);
        $iv = "@@@@&&&&####$$$$";
        $data = openssl_encrypt($input, "AES-128-CBC", $key, 0, $iv);
        return $data;
    }

    public function decrypt_e($crypt, $ky)
    {
        $key   = html_entity_decode($ky);
        $iv = "@@@@&&&&####$$$$";
        $data = openssl_decrypt($crypt, "AES-128-CBC", $key, 0, $iv);
        return $data;
    }

    public function pkcs5_pad_e($text, $blocksize)
    {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    public function pkcs5_unpad_e($text)
    {
        return $text;
        /*
        $pad = ord($text{
        strlen($text) - 1});
        if ($pad > strlen($text))
            return false;
        return substr($text, 0, -1 * $pad);
        */
    }

    public function generateSalt_e($length)
    {
        $random = "";
        srand((float) microtime() * 1000000);

        $data = "AbcDE123IJKLMN67QRSTUVWXYZ";
        $data .= "aBCdefghijklmn123opq45rs67tuv89wxyz";
        $data .= "0FGH45OP89";

        for ($i = 0; $i < $length; $i++) {
            $random .= substr($data, (rand() % (strlen($data))), 1);
        }

        return $random;
    }

    public function checkString_e($value)
    {
        $myvalue = ltrim($value);
        $myvalue = rtrim($myvalue);
        if ($myvalue == 'null')
            $myvalue = '';
        return $myvalue;
    }


    public function getChecksumFromArray($arrayList, $key, $sort = 1)
    {
        if ($sort != 0) {
            ksort($arrayList);
        }
        $str         = $this->getArray2Str($arrayList);
        $salt        = $this->generateSalt_e(4);
        $finalString = $str . "|" . $salt;
        $hash        = hash("sha256", $finalString);
        $hashString  = $hash . $salt;
        $checksum    = $this->encrypt_e($hashString, $key);
        return $checksum;
    }

    public function verifychecksum_e($arrayList, $key, $checksumvalue)
    {
        $arrayList = $this->removeCheckSumParam($arrayList);
        ksort($arrayList);
        $str        = $this->getArray2StrForVerify($arrayList);
        $paytm_hash = $this->decrypt_e($checksumvalue, $key);
        $salt       = substr($paytm_hash, -4);

        $finalString = $str . "|" . $salt;

        $website_hash = hash("sha256", $finalString);
        $website_hash .= $salt;

        $validFlag = "FALSE";
        if ($website_hash == $paytm_hash) {
            $validFlag = "TRUE";
        } else {
            $validFlag = "FALSE";
        }
        return $validFlag;
    }





    public function getArray2Str($arrayList)
    {
        $findme   = 'REFUND';
        $findmepipe = '|';
        $paramStr = "";
        $flag = 1;
        foreach ($arrayList as $key => $value) {
            $pos = strpos($value, $findme);
            $pospipe = strpos($value, $findmepipe);
            if ($pos !== false || $pospipe !== false) {
                continue;
            }

            if ($flag) {
                $paramStr .= $this->checkString_e($value);
                $flag = 0;
            } else {
                $paramStr .= "|" . $this->checkString_e($value);
            }
        }
        return $paramStr;
    }


    public function getArray2StrForVerify($arrayList)
    {
        $paramStr = "";
        $flag = 1;
        foreach ($arrayList as $key => $value) {
            if ($flag) {
                $paramStr .= $this->checkString_e($value);
                $flag = 0;
            } else {
                $paramStr .= "|" . $this->checkString_e($value);
            }
        }
        return $paramStr;
    }

    public function redirect2PG($paramList, $key)
    {
        $hashString = $this->getchecksumFromArray($paramList);
        $checksum   = $this->encrypt_e($hashString, $key);
    }

    public function removeCheckSumParam($arrayList)
    {
        if (isset($arrayList["CHECKSUMHASH"])) {
            unset($arrayList["CHECKSUMHASH"]);
        }
        return $arrayList;
    }

    public function getTxnStatus($requestParamList)
    {
        return $this->callAPI(PAYTM_STATUS_QUERY_URL, $requestParamList);
    }

    public function initiateTxnRefund($requestParamList)
    {
        $CHECKSUM                     = $this->getChecksumFromArray($requestParamList, PAYTM_MERCHANT_KEY, 0);
        $requestParamList["CHECKSUM"] = $CHECKSUM;
        return $this->callAPI(PAYTM_REFUND_URL, $requestParamList);
    }

    public function callAPI($apiURL, $requestParamList)
    {
        $jsonResponse      = "";
        $responseParamList = array();
        $JsonData          = json_encode($requestParamList);
        $postData          = 'JsonData=' . urlencode($JsonData);
        $ch                = curl_init($apiURL);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($postData)
        ));
        $jsonResponse      = curl_exec($ch);
        $responseParamList = json_decode($jsonResponse, true);
        return $responseParamList;
    }

    public function sanitizedParam($param)
    {
        $pattern[0]     = "%,%";
        $pattern[1]     = "%#%";
        $pattern[2]     = "%\(%";
        $pattern[3]     = "%\)%";
        $pattern[4]     = "%\{%";
        $pattern[5]     = "%\}%";
        $pattern[6]     = "%<%";
        $pattern[7]     = "%>%";
        $pattern[8]     = "%`%";
        $pattern[9]     = "%!%";
        $pattern[10]    = "%\\$%";
        $pattern[11]    = "%\%%";
        $pattern[12]    = "%\^%";
        $pattern[13]    = "%=%";
        $pattern[14]    = "%\+%";
        $pattern[15]    = "%\|%";
        $pattern[16]    = "%\\\%";
        $pattern[17]    = "%:%";
        $pattern[18]    = "%'%";
        $pattern[19]    = "%\"%";
        $pattern[20]    = "%;%";
        $pattern[21]    = "%~%";
        $pattern[22]    = "%\[%";
        $pattern[23]    = "%\]%";
        $pattern[24]    = "%\*%";
        $pattern[25]    = "%&%";
        $sanitizedParam = preg_replace($pattern, "", $param);
        return $sanitizedParam;
    }

    public function callNewAPI($apiURL, $requestParamList)
    {
        $jsonResponse = "";
        $responseParamList = array();
        $JsonData = json_encode($requestParamList);
        $postData = 'JsonData=' . urlencode($JsonData);
        $ch = curl_init($apiURL);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt(
            $ch,
            CURLOPT_HTTPHEADER,
            array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($postData)
            )
        );
        $jsonResponse = curl_exec($ch);
        $responseParamList = json_decode($jsonResponse, true);
        return $responseParamList;
    }
}
PK     x\GHt#  #  %  Services/Gateway/voguepay/Payment.phpnu [        <?php

namespace App\Services\Gateway\voguepay;


use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$send['v_merchant_id'] = $gateway->parameters->merchant_id ?? '';
		$send['notify_url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$send['cur'] = $deposit->payment_method_currency;
		$send['merchant_ref'] = $deposit->trx_id;
		$send['memo'] = "Pay to {$basic->site_title}";
		$send['custom'] = $deposit->trx_id;
		$send['customer_name'] = optional($deposit->user)->name ?? $basic->site_title;
		$send['customer_address'] = optional($deposit->user)->profile->address ?? '';
		$send['customer_email'] = optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? basicControl()->sender_email;
		$send['Buy'] = round($deposit->payable_amount, 2);
		$send['view'] = 'voguepay';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$trx = $request->transaction_id;
		$url = "https://voguepay.com/?v_transaction_id={$type}&type=json";
		$response = BasicCurl::curlGetRequest($url);
		$response = json_decode($response);
		$merchantId = $gateway->parameters->merchant_id ?? '';
		if ($response->status == "Approved" && $response->merchant_id == $merchantId && $response->total == round($deposit->payable_amount, 2) && $response->cur_iso == $deposit->payment_method_currency) {
			BasicService::preparePaymentUpgradation($deposit);
			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\EԯI  I  %  Services/Gateway/cashonex/Payment.phpnu [        <?php

namespace App\Services\Gateway\cashonex;

use Facades\App\Services\BasicCurl;


class Payment
{
    public static function prepareData($order, $gateway)
    {

        $basic = basicControl();
        $val['name'] = optional($order->user)->username ?? $basic->site_title;
        $val['amount'] = round($order->payable_amount ,2);
        $val['currency'] = $order->gateway_currency;
        $send['val'] = $val;
        $send['view'] = 'cashonex';
        $send['method'] = 'post';
        $send['url'] = route('ipn', [$gateway->code, $order->transaction]);
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $order = null, $trx = null, $type = null)
    {
        $idempotency_key = $gateway->parameters->idempotency_key;
        $salt = $gateway->parameters->salt;
        $request->validate( [
            'name' => 'required',
            'cardNumber' => 'required',
            'cardExpiry' => 'required',
            'cardCVC' => 'required'
        ],[
            'cardCVC.required' => "The card CVC field is required."
        ]);



        $card_number = $request->cardNumber;
        $exp = $request->cardExpiry;
        $cvc = $request->cardCVC;

        $exp = $pieces = explode("/", $_POST['cardExpiry']);
        $expiry_year = trim($exp[1]);
        $expiry_month = trim($exp[0]);
        $amount = round($order->final_amount ,2);
        $headers = [
            'Content-Type: application/json',
            "Idempotency-Key: $idempotency_key",
        ];

        $postParam = [
            "salt" => $salt,
            "first_name" => optional($order->user)->firstname,
            "last_name" => optional($order->user)->lastname,
            "email" => optional($order->user)->email??'email@gmail.com',
            "phone" => optional($order->user)->phone??'9999999999',
            "address" => optional($order->user)->address??'123, address',
            "city" => optional($order->user)->city??'City',
            "state" => optional($order->user)->city??'State',
            "country" => optional($order->user)->country??'GB',
            "zip_code" => optional($order->user)->zip_code??'90210',
            "amount" => $amount,
            "currency" => $order->gateway_currency,
            "pay_by" => "VISA",
            "card_name" => $request->name,
            "card_number" => $card_number,
            "cvv_code" => $cvc,
            "expiry_year" => $expiry_year,
            "expiry_month" => $expiry_month,
            "orderid" => $order->transaction,
            "clientip" => request()->ip(),
            "redirect_url" => route('success'),
            "webhook_url" => route('paymentCashonex')
        ];

        $url = "https://cashonex.com/api/rest/payment";
        $result = BasicCurl::curlPostRequestWithHeadersJson($url, $headers, $postParam);
        $response = json_decode($result);
        if (isset($response->success) && $response->success == true) {
            $order->btc_wallet = @$response->data->paymentId;
            $order->update();
            $data['status'] = 'success';
            $data['msg'] = ' Payment Proceed.';
            $data['redirect'] = $response->data->redirectUrl;
        } else {
            $data['status'] = 'error';
            $data['msg'] = 'Unsuccessful transaction.';
            $data['redirect'] = route('failed');
        }

        return $data;

    }
}
PK     x\Ng  g  %  Services/Gateway/paystack/Payment.phpnu [        <?php

namespace App\Services\Gateway\paystack;


use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;
use Illuminate\Support\Facades\Auth;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$send['key'] = $gateway->parameters->public_key ?? '';
		$send['email'] = optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? basicControl()->sender_email;
		$send['amount'] = round($deposit->payable_amount, 2) * 100;
		$send['currency'] = $deposit->payment_method_currency;
		$send['ref'] = $deposit->trx_id;
		$send['view'] = 'paystack';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$secret_key = $gateway->parameters->secret_key ?? '';
		$url = 'https://api.paystack.co/transaction/verify/' . $trx;
		$headers = [
			"Authorization: Bearer {$secret_key}"
		];
		$response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
		$response = json_decode($response, true);
		if ($response) {
			if ($response['data']) {
				if ($response['data']['status'] == 'success') {
					$deposit = Deposit::with('user')->where('trx_id', $trx)->first();

					$depositAmount = round($deposit->payable_amount, 2) * 100;
					if (round($response['data']['amount'], 2) == $depositAmount && $response['data']['currency'] == $deposit->payment_method_currency) {
						BasicService::preparePaymentUpgradation($deposit);
						$data['status'] = 'success';
						$data['msg'] = 'Transaction was successful.';
						$data['redirect'] = route('success');
					} else {
						$data['status'] = 'error';
						$data['msg'] = 'invalid amount.';
						$data['redirect'] = route('failed');
					}
				} else {
					$data['status'] = 'error';
					$data['msg'] = $response['data']['gateway_response'];
					$data['redirect'] = route('failed');
				}
			} else {
				$data['status'] = 'error';
				$data['msg'] = $response['message'];
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\o
  
  $  Services/Gateway/swagger/Payment.phpnu [        <?php

namespace App\Services\Gateway\swagger;

use App\Models\Deposit;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
    public static function prepareData($deposit, $gateway)
    {
        $val['account'] = $gateway->parameters->MAGUA_PAY_ACCOUNT;
        $val['order_id'] = $deposit->trx_id;
        $val['amount'] = (int)round($deposit->payable_amount);
        $val['currency'] = $deposit->payment_method_id;
        $val['recurrent'] = false;
        $val['purpose'] = "Online Payment";
        $val['customer_first_name'] = "John";
        $val['customer_last_name'] = optional($deposit->user)->lastname ?? "Doe";
        $val['customer_address'] = optional($deposit->user)->address ?? "10 Downing Street";
        $val['customer_city'] = optional($deposit->user)->city ?? "London";
        $val['customer_zip_code'] = optional($deposit->user)->zip_code ?? "121165";
        $val['customer_country'] = "GB";
        $val['customer_phone'] = optional($deposit->user)->phone ?? "+79000000000";
        $val['customer_email'] = $deposit->email ?? "johndoe@mail.com";

        $val['customer_ip_address'] = request()->ip();
        $val['merchant_site'] = url('/');

        $val['success_url'] = route('success');
        $val['fail_url'] = route('failed');
        $val['callback_url'] = route('ipn', $gateway->code);
        $val['status_url'] = route('ipn', $gateway->code);

        if ($gateway->environment == 'test' || $deposit->mode == 1) {
            $url = "https://merchantapi.magua-pay.com/initPayment";
        } else {
            $url = "https://api-gateway.magua-pay.com/initPayment";
        }
        $header = array();
        $header[] = 'Content-Type: application/json';
        $header[] = 'Authorization: Basic ' . base64_encode($gateway->parameters->MerchantKey . ":" . $gateway->parameters->Secret);

        $response = BasicCurl::curlPostRequestWithHeaders($url, $header, $val);

        $response = json_decode($response);

        if (isset($response->form_url)) {
            $send['redirect'] = true;
            $send['redirect_url'] = $response->form_url;
        } else {
            $send['error'] = true;
            $send['message'] = "Invalid Request";
        }
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $order = Deposit::where('trx_id', $request->orderId)->orderBy('id', 'DESC')->first();
        if ($order) {
            if ($request->status == 2 && $request->currency == $order->gateway_currency && ($request->amount == (int)round($order->payable_amount)) && $order->status == 0) {
                BasicService::preparePaymentUpgradation($order);
            }
        }
    }
}
PK     x\    )  Services/Gateway/perfectmoney/Payment.phpnu [        <?php

namespace App\Services\Gateway\perfectmoney;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicService;
use Illuminate\Support\Facades\Auth;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$val['PAYEE_ACCOUNT'] = trim($gateway->parameters->payee_account);
		$val['PAYEE_NAME'] = optional($deposit->user)->name ?? $basic->site_title;
		$val['PAYMENT_ID'] = $deposit->trx_id;
		$val['PAYMENT_AMOUNT'] = round($deposit->payable_amount, 2);
		$val['PAYMENT_UNITS'] = $deposit->payment_method_currency;
		$val['STATUS_URL'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$val['PAYMENT_URL'] = route('success');
		$val['PAYMENT_URL_METHOD'] = 'POST';
		$val['NOPAYMENT_URL'] = route('failed');
		$val['NOPAYMENT_URL_METHOD'] = 'POST';
		$val['SUGGESTED_MEMO'] = optional($deposit->user)->name ?? $basic->site_title;
		$val['BAGGAGE_FIELDS'] = 'IDENT';
		$send['val'] = $val;
		$send['view'] = 'redirect';
		$send['method'] = 'post';
		$send['url'] = 'https://perfectmoney.is/api/step1.asp';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$passphrase = strtoupper(md5(trim($gateway->parameters->passphrase)));
		define('ALTERNATE_PHRASE_HASH', $passphrase);
		define('PATH_TO_LOG', '/assets/upload/');
		$string =
			$request->PAYMENT_ID . ':' . $request->PAYEE_ACCOUNT . ':' .
			$request->PAYMENT_AMOUNT . ':' . $request->PAYMENT_UNITS . ':' .
			$request->PAYMENT_BATCH_NUM . ':' .
			$request->PAYER_ACCOUNT . ':' . ALTERNATE_PHRASE_HASH . ':' .
			$request->TIMESTAMPGMT;

		$hash = strtoupper(md5($string));
		$hash2 = $request->V2_HASH;

		if ($hash == $hash2) {
			$amount = $request->PAYMENT_AMOUNT;
			$unit = $request->PAYMENT_UNITS;
			if ($request->PAYEE_ACCOUNT == trim($gateway->parameters->payee_account) && $unit == $deposit->payment_method_currency && $amount == $deposit->payable_amount && $deposit->status == 0) {
				BasicService::preparePaymentUpgradation($deposit);
			}
		}
	}
}
PK     x\/  /  (  Services/Gateway/twocheckout/Payment.phpnu [        <?php

namespace App\Services\Gateway\twocheckout;

use App\Models\Deposit;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$send['val'] = [
			'sid' => $gateway->parameters->merchant_code,
			'mode' => '2CO',
			'li_0_type' => 'product',
			'li_0_name' => "Pay to $basic->site_title",
			'li_0_product_id' => "{$deposit->trx_id}",
			'li_0_price' => round($deposit->payable_amount, 2),
			'li_0_quantity' => "1",
			'li_0_tangible' => "N",
			'currency_code' => $deposit->payment_method_currency,
			'demo' => "Y",
		];
		$send['view'] = 'redirect';
		$send['method'] = 'post';
		$send['url'] = 'https://www.2checkout.com/checkout/purchase';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$hashSecretWord = $gateway->parameters->secret_key;
		$hashSid = $gateway->parameters->merchant_code;
		$deposit = Deposit::where('trx_id', $request->li_0_product_id)->first();
		$hashTotal = round($deposit->payable_amount, 2);
		$hashOrder = $request->order_number;
		$StringToHash = strtoupper(md5($hashSecretWord . $hashSid . $hashOrder . $hashTotal));

		if ($StringToHash != $request->key) {
			BasicService::preparePaymentUpgradation($deposit);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unsuccessful';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\Yo	  o	  $  Services/Gateway/monnify/Payment.phpnu [        <?php

namespace App\Services\Gateway\monnify;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$send['api_key'] = $gateway->parameters->api_key ?? '';
		$send['contract_code'] = $gateway->parameters->contract_code ?? '';
		$send['amount'] = round($deposit->payable_amount, 2);
		$send['currency'] = $deposit->payment_method_currency;
		$send['customer_name'] = optional($deposit->user)->name ?? $basic->site_title;
		$send['customer_email'] = optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? $basic->sender_email;
		$send['customer_phone'] = optional($deposit->user)->phone ?? '';
		$send['ref'] = $deposit->trx_id;
		$send['description'] = "Pay to {$basic->site_title}";
		$send['view'] = 'monnify';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$apiKey = $gateway->parameters->api_key ?? '';
		$secretKey = $gateway->parameters->secret_key ?? '';
		if ($gateway->environment == 'test') {
			$url = "https://sandbox.monnify.com/api/v1/merchant/transactions/query?paymentReference={$trx}";
		} else {
			$url = "https://app.monnify.com/api/v1/merchant/transactions/query?paymentReference={$trx}";
		}
		$headers = [
			"Authorization: Basic " . base64_encode($apiKey . ':' . $secretKey)
		];
		$response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
		$response = json_decode($response);
		if ($response->requestSuccessful && $response->responseMessage == "success") {
			if ($response->responseBody->amount == round($deposit->payable_amount, 2) && $response->responseBody->currencyCode == $deposit->payment_method_currency && $deposit->status == 0) {
				BasicService::preparePaymentUpgradation($deposit);

				$data['status'] = 'success';
				$data['msg'] = 'Transaction was successful.';
				$data['redirect'] = route('success');
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'invalid amount.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unable to Process.';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\I
  I
  '  Services/Gateway/blockchain/Payment.phpnu [        <?php

namespace App\Services\Gateway\blockchain;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
    public static function prepareData($deposit, $gateway)
    {

        $apiKey = $gateway->parameters->api_key ?? '';
        $xpubCode = $gateway->parameters->xpub_code ?? '';

        $btcPriceUrl = "https://blockchain.info/ticker";
        $btcPriceResponse = BasicCurl::curlGetRequest($btcPriceUrl);
        $btcPriceResponse = json_decode($btcPriceResponse);
        $btcRate = $btcPriceResponse->USD->last;

        $usd = round($deposit->payable_amount, 2);
        $btcamount = $usd / $btcRate;
        $btc = round($btcamount, 8);
        if ($deposit->btc_amount == 0 || $deposit->btc_wallet == "") {
            $secret = $deposit->trx_id;
            $callback_url = route('ipn', [$gateway->code, $deposit->trx_id]) . "?invoice_id=" . $deposit->trx_id . "&secret=" . $secret;
            $url = "https://api.blockchain.info/v2/receive?key={$apiKey}&callback=" . urlencode($callback_url) . "&xpub={$xpubCode}";
            $response = BasicCurl::curlGetRequest($url);
            $response = json_decode($response);
            if (@$response->address == '') {
                $send['error'] = true;
                $send['message'] = 'BLOCKCHAIN API HAVING ISSUE. PLEASE TRY LATER. ' . $response->message ?? null;
            } else {
                $deposit['btc_wallet'] = $response->address;
                $deposit['btc_amount'] = $btc;
                $deposit->update();
            }
        }

        $send['amount'] = $deposit->btc_amount;
        $send['sendto'] = $deposit->btc_wallet;
        $send['img'] = BasicService::cryptoQR($deposit->btc_wallet, $deposit->btc_amount);
        $send['currency'] = $deposit->payment_method_currency ?? 'BTC';
        $send['view'] = 'crypto';
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $btc = $request->value / 100000000;
        if ($deposit->btc_amount == $btc && $request->address == $deposit->btc_wallet && $request->secret == $deposit->trx_id && $request->confirmations > 2 && $deposit->status == 0) {
            BasicService::preparePaymentUpgradation($deposit);

            $data['status'] = 'success';
            $data['msg'] = 'Transaction was successful.';
            $data['redirect'] = route('success');
        } else {
            $data['status'] = 'error';
            $data['msg'] = 'Invalid response.';
            $data['redirect'] = route('failed');
        }
        return $data;
    }
}
PK     x\T♡    %  Services/Gateway/shkeeper/Payment.phpnu [        <?php

namespace App\Services\Gateway\shkeeper;

use App\Models\Deposit;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
    public static function prepareData($deposit, $gateway)
    {
        $apiKey = $gateway->parameters->api_key ?? '';
        $hostedUrl = $gateway->parameters->hosted_url ?? '';
        $url = rtrim($hostedUrl, '/') . "/api/v1/{$deposit->payment_crypto_currency}/payment_request";

        $postParams = [
            "external_id" => $deposit->trx_id,
            "fiat" => "USD",
            "amount" => round($deposit->payable_amount, 2),
            "callback_url" => route('ipn', [$gateway->code, $deposit->trx_id])
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParams));

        $headers = array();
        $headers[] = 'X-Shkeeper-Api-Key: ' . $apiKey;
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

        $res = json_decode($result);

        if ($res && $res->status == 'success') {
            $deposit->btc_amount = $res->amount;
            $deposit->btc_wallet = $res->wallet;
            $deposit->save();
        }

        $send['amount'] = $deposit->btc_amount;
        $send['sendto'] = $deposit->btc_wallet;
        $send['img'] = BasicService::cryptoQR($deposit->btc_wallet, $deposit->btc_amount, $deposit->payment_crypto_currency);
        $send['currency'] = $deposit->payment_crypto_currency ?? 'BTC';
        $send['view'] = 'crypto';
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $apiKey = $gateway->parameters->api_key ?? '';
        $hostedUrl = $gateway->parameters->hosted_url ?? '';
        $url = rtrim($hostedUrl, '/') . "/api/v1/invoices/{$deposit->trx_id}";

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');


        $headers = array();
        $headers[] = 'X-Shkeeper-Api-Key: ' . $apiKey;
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);

        $res = json_decode($result);

        if ($res && $res->status == 'success' && ($res->invoices[0]->status == 'PAID' || $res->invoices[0]->status == 'OVERPAID')) {
            BasicService::preparePaymentUpgradation($deposit);

            $data['status'] = 'success';
            $data['msg'] = 'Transaction was successful.';
            $data['redirect'] = route('success');
        } else {
            $data['status'] = 'error';
            $data['msg'] = 'Invalid response.';
            $data['redirect'] = route('failed');
        }
        return $data;
    }
}
PK     x\#    #  Services/Gateway/paypal/Payment.phpnu [        <?php

namespace App\Services\Gateway\paypal;


use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$send['cleint_id'] = $gateway->parameters->cleint_id ?? '';
		$send['description'] = "Payment To {$basic->site_title} Account";
		$send['custom_id'] = $deposit->trx_id;
		$send['amount'] = round($deposit->payable_amount, 2);
		$send['currency'] = $deposit->payment_method_currency;
		$send['view'] = 'paypal';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		if ($gateway->environment == 'live') {
			$url = "https://api-m.paypal.com/v2/checkout/orders/{$type}";
		} else {
			$url = "https://api-m.sandbox.paypal.com/v2/checkout/orders/{$type}";
		}

		$client_id = $gateway->parameters->cleint_id ?? '';
		$secret = $gateway->parameters->secret ?? '';
		$headers = [
			'Content-Type:application/json',
			'Authorization:Basic ' . base64_encode("{$client_id}:{$secret}")
		];
		$response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
		$paymentData = json_decode($response, true);
		if (isset($paymentData['status']) && $paymentData['status'] == 'COMPLETED') {
			if ($paymentData['purchase_units'][0]['amount']['currency_code'] == $deposit->payment_method_currency && $paymentData['purchase_units'][0]['amount']['value'] == round($deposit->payable_amount, 2)) {
				BasicService::preparePaymentUpgradation($deposit);
				$data['status'] = 'success';
				$data['msg'] = 'Transaction was successful.';
				$data['redirect'] = route('success');
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'invalid amount.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\kN
  
  *  Services/Gateway/peachpayments/Payment.phpnu [        <?php

namespace App\Services\Gateway\peachpayments;

use Facades\App\Services\BasicService;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$Entity_ID = trim($gateway->parameters->Entity_ID);
		$amount = trim(round($deposit->payable_amount));
		$currency = trim(strtoupper($deposit->payment_method_currency));
		if ($gateway->environment == 'test') {
			$url = "https://test.oppwa.com/v1/checkouts";
		} else {
			$url = "https://oppwa.com/v1/checkouts";
		}
		$data = "entityId=$Entity_ID" .
			"&amount=$amount" .
			"&currency=$currency" .
			"&paymentType=DB";

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $gateway->parameters->Authorization_Bearer)); // client
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true in production
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$responseData = curl_exec($ch);
		if (curl_errno($ch)) {
			return curl_error($ch);
		}
		curl_close($ch);

		$result = json_decode($responseData);

		$deposit->btc_wallet = $result->id;
		$deposit->save();
		$send['view'] = 'peachpayments';

		$send['checkoutId'] = $result->id;
		$send['environment'] = $gateway->environment;
		//$send['mode'] = $deposit->mode;

		$send['url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{

		$id = $request->id;
		if ($gateway->environment == 'test') {
			$url = "https://test.oppwa.com/v1/checkouts";
		} else {
			$url = "https://oppwa.com/v1/checkouts";
		}
		$url .= "?entityId=" . $gateway->parameters->Entity_ID;

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization:Bearer ' . $gateway->parameters->Authorization_Bearer));
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);// this should be set to true in production
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$responseData = curl_exec($ch);
		if (curl_errno($ch)) {
			return curl_error($ch);
		}
		curl_close($ch);
		$response = json_decode($responseData);
		//$deposit->response = $response;
		//$deposit->save();

		if (@$response->result->code == '000.100.110') {
			BasicService::preparePaymentUpgradation($deposit);
			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = @$response->result->description;
			$data['redirect'] = route('failed');
		}
		return $data;

	}
}
PK     x\X    &  Services/Gateway/instamojo/Payment.phpnu [        <?php

namespace App\Services\Gateway\instamojo;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$api_key = trim($gateway->parameters->api_key);
		$auth_token = trim($gateway->parameters->auth_token);
		$url = 'https://instamojo.com/api/1.1/payment-requests/';
		$headers = [
			"X-Api-Key:$api_key",
			"X-Auth-Token:$auth_token"
		];


		$postParam = [
			'purpose' => 'Payment to ' . $basic->site_title ?? 'Bug Finder',
			'amount' => round($deposit->payable_amount, 2),
			'buyer_name' => optional($deposit->user)->name ?? $basic->site_title,
			'redirect_url' => route('success'),
			'webhook' => route('ipn', [$gateway->code, $deposit->trx_id]),
			'email' => optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? $basic->sender_email,
			'send_email' => true,
			'allow_repeated_payments' => false
		];

		$response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);

		$response = json_decode($response);

		if ($response->success) {
			$send['redirect'] = true;
			$send['redirect_url'] = $response->payment_requests[0]->longurl;
		} else {
			$send['error'] = true;
			$send['message'] = "Invalid Request";
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$salt = trim($gateway->parameters->salt);
		$imData = $request;
		$macSent = $imData['mac'];
		unset($imData['mac']);
		ksort($imData, SORT_STRING | SORT_FLAG_CASE);
		$mac = hash_hmac("sha1", implode("|", $imData), $salt);

		if ($macSent == $mac && $imData['status'] == "Credit" && $deposit->status == '0') {
			BasicService::preparePaymentUpgradation($deposit);
		}
	}
}
PK     x\r  r  "  Services/Gateway/bkash/Payment.phpnu [        <?php

namespace App\Services\Gateway\bkash;

use App\Traits\Bkash;
use Facades\App\Services\BasicService;
use Exception;

class Payment
{
    use Bkash;

    public static function prepareData($deposit, $gateway)
    {
        throw_if(empty($gateway->parameters->app_key ?? "") || empty($gateway->parameters->app_secret ?? ""), "Unable to process with bKash.");

        $_this = new self();
        $token = $_this->getToken($gateway);
        $uri = $_this->getBaseURL($gateway->environment) . "/create";
        $data = array(
            'mode' => '0011',
            'payerReference' => ' ',
            'callbackURL' => route('ipn', ['code' => 'bkash', 'trx' => $deposit->trx_id]),
            'amount' => round($deposit->payable_amount, 2),
            'currency' => 'BDT',
            'intent' => 'sale',
            'merchantInvoiceNumber' => $deposit->trx_id
        );

        $response = $_this->sentHttpRequestToBkash($token, $gateway->parameters->app_key, $uri, $data);

        if ($response->status() == 200) {
            $bkashResponse = json_decode($response->body());
            throw_if(!isset($bkashResponse->bkashURL, $bkashResponse->paymentID), 'Something went wrong while trying pay with bKash. Please contact with author.');

            $deposit->update([
                'payment_id' => $bkashResponse->paymentID
            ]);

            $send['redirect'] = true;
            $send['redirect_url'] = $bkashResponse->bkashURL;
            return json_encode($send);
        }
        throw new Exception("Something went wrong while trying to pay with your bKash.");
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $_this = new self();
        if (isset($request->status) && $request->status == 'failure') {
            return $_this->updateAndMessage($deposit, 'Failed','Payment Failed due to unknown reason.');
        }

        if (isset($request->status) && $request->status == 'cancel') {
            return $_this->updateAndMessage($deposit, 'Cancelled','Payment cancelled.');
        }
        $executePaymentResponse = $_this->executePayment($request->paymentID, $gateway);

        if (isset($executePaymentResponse->statusCode) && $executePaymentResponse->statusCode != '0000') {
            return $_this->updateAndMessage($deposit, 'Failed',$executePaymentResponse->statusMessage);
        }

        if (isset($executePaymentResponse->message)) {
            $query = $_this->queryPayment($request->paymentID, $gateway);

            if ($query->trxID) {
                BasicService::preparePaymentUpgradation($deposit, $query->trxID, 'bKash Gateway');
                $data['status'] = 'success';
                $data['msg'] = 'Transaction was successful.';
                $data['redirect'] = route('success');
                return $data;
            }
            return $_this->updateAndMessage($deposit, 'Failed', $query->statusMessage);
        }
        BasicService::preparePaymentUpgradation($deposit, $executePaymentResponse->trxID, 'bKash Gateway');

        $data['status'] = 'success';
        $data['msg'] = 'Transaction was successful.';
        $data['redirect'] = route('success');
        return $data;
    }



    public static function refund($deposit, $trxNo, $gateway, $amount)
    {
        $_this = new self();
        throw_if(empty($gateway->parameters->app_key ?? "") || empty($gateway->parameters->app_secret ?? ""), "Unable to process with bKash.");
        $token = $_this->getToken($gateway);

        $uri = $_this->getBaseURL($gateway->environment) . "/payment/refund";
        $data = array(
            'paymentID' => $deposit->payment_id,
            'amount' => $amount,
            'trxID' => $trxNo,
            'sku' => 'sku',
            'reason' => "Requested for refund."
        );
        $response = $_this->sentHttpRequestToBkash($token, $gateway->parameters->app_key, $uri, $data);

        if ($response->status() == 200) {
            $bkashResponse = json_decode($response->body());

            if (!isset($bkashResponse->refundTrxID))
                return [
                    'status' => 'error',
                    'msg' => $bkashResponse->statusMessage ?? 'Something went wrong while trying refund.'
                ];

            return [
                'status' => 'success',
                'msg' => 'refund was successful.',
                'trx_id' => $bkashResponse->refundTrxID
            ];
        }
        throw new Exception("Something went wrong while trying to verify your payment with bKash.");
    }

}
PK     x\>     $  Services/Gateway/binance/Payment.phpnu [        <?php

namespace App\Services\Gateway\binance;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$url = "https://bpay.binanceapi.com/binancepay/openapi/v2/order";
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$nonce = '';
		for ($i = 1; $i <= 32; $i++) {
			$pos = mt_rand(0, strlen($chars) - 1);
			$char = $chars[$pos];
			$nonce .= $char;
		}
//		$merchantTradeNo = mt_rand(982538, 9825382937292);
		$merchantTradeNo = $deposit->trx_id;

		$ch = curl_init();
		$timestamp = round(microtime(true) * 1000);
		// Request body
		$request = array(
			"env" => array(
				"terminalType" => "WEB"
			),
			"merchantTradeNo" => $merchantTradeNo,
			"orderAmount" => round($deposit->payable_amount, 2),
			"currency" => $deposit->payment_method_currency,
			"goods" => array(
				"goodsType" => "01",
				"goodsCategory" => "D000",
				"referenceGoodsId" => "7876763A3B",
				"goodsName" => basicControl()->site_title." Payment",
				"goodsDetail" => "Payment to ".basicControl()->site_title
			),
			'returnUrl' => route('ipn', [$gateway->code, $merchantTradeNo]),
			'webhookUrl' => route('ipn', [$gateway->code, $merchantTradeNo]),
//			'returnUrl' => "https://bugfinder.net/contact",
//			'webhookUrl' => 'https://bugfinder.net/api/paymentTrack',
			'cancelUrl' => twoStepPrevious($deposit),
		);

		$json_request = json_encode($request);
		$payload = $timestamp . "\n" . $nonce . "\n" . $json_request . "\n";
		$binance_pay_key = $gateway->parameters->mercent_api_key;
		$binance_pay_secret = $gateway->parameters->mercent_secret;
		$signature = strtoupper(hash_hmac('SHA512', $payload, $binance_pay_secret));


		$headers = array();
		$headers[] = "Content-Type: application/json";
		$headers[] = "BinancePay-Timestamp: $timestamp";
		$headers[] = "BinancePay-Nonce: $nonce";
		$headers[] = "BinancePay-Certificate-SN: $binance_pay_key";
		$headers[] = "BinancePay-Signature: $signature";

		$response = BasicCurl::binanceCurlOrderRequest($url, $headers, $json_request);
		$result = json_decode($response);


		if ($result->status !== "FAIL") {
			if ($result->data) {
				$send['redirect'] = true;
				$send['redirect_url'] = $result->data->checkoutUrl;
			} else {
				$send['error'] = true;
				$send['message'] = 'Unexpected Error! Please Try Again';
			}
		} else {
			$send['error'] = true;
			$send['message'] = 'Unexpected Error! Please Try Again';
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$url = "https://bpay.binanceapi.com/binancepay/openapi/v2/order/query";
		$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$nonce = '';
		for ($i = 1; $i <= 32; $i++) {
			$pos = mt_rand(0, strlen($chars) - 1);
			$char = $chars[$pos];
			$nonce .= $char;
		}
		$ch = curl_init();
		$timestamp = round(microtime(true) * 1000);
		$request = array(
			"merchantTradeNo" => $trx,
		);

		$json_request = json_encode($request);
		$payload = $timestamp . "\n" . $nonce . "\n" . $json_request . "\n";
		$binance_pay_key = $gateway->parameters->mercent_api_key;
		$binance_pay_secret = $gateway->parameters->mercent_secret;
		$signature = strtoupper(hash_hmac('SHA512', $payload, $binance_pay_secret));

		$headers = array();
		$headers[] = "Content-Type: application/json";
		$headers[] = "BinancePay-Timestamp: $timestamp";
		$headers[] = "BinancePay-Nonce: $nonce";
		$headers[] = "BinancePay-Certificate-SN: $binance_pay_key";
		$headers[] = "BinancePay-Signature: $signature";

		$response = BasicCurl::binanceCurlOrderRequest($url, $headers, $json_request);
		$result = json_decode($response);


		if (isset($result)) {
			if ($result->status == 'SUCCESS') {
				if (isset($result->data)) {
					if ($result->data->status = 'PAID') {
						BasicService::preparePaymentUpgradation($deposit);
						$data['status'] = 'success';
						$data['msg'] = 'Transaction was successful.';
						$data['redirect'] = route('success');
					}
				}
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'unexpected error!';
				$data['redirect'] = route('failed');
			}
		}
		return $data;
	}
}
PK     x\yL
  
  "  Services/Gateway/mypay/Payment.phpnu [        <?php

namespace App\Services\Gateway\mypay;


use App\Models\Deposit;
use App\Models\Fund;
use Facades\App\Services\BasicService;
use Facades\App\Services\BasicCurl;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$API_KEY = $gateway->parameters->api_key ?? '';
		$UserName = $gateway->parameters->merchant_username ?? '';
		$Password = $gateway->parameters->merchant_api_password ?? '';
		$MerchantId = $gateway->parameters->merchant_id ?? '';

		if ($gateway->environment == 'test') {
			$url = "https://testapi.mypay.com.np/api/use-mypay-payments";
		} else {
			$url = "https://smartdigitalnepal.com/api/use-mypay-payments";
		}

		$headers = [
			'Content-Type: application/json',
			"API_KEY: $API_KEY",
		];

		$postParam = [
			"Amount" => round($deposit->payable_amount),
			"OrderId" => $deposit->trx_id,
			"UserName" => "$UserName",
			"Password" => "$Password",
			"MerchantId" => "$MerchantId"
		];

		$result = BasicCurl::curlPostRequestWithHeadersJson($url, $headers, $postParam);
		$response = json_decode($result);


		if (@$response->status == false) {
			$send['error'] = true;
			$send['message'] = 'PLEASE TRY LATER. ' . @$response->Message;
		} else {
			$deposit['referenceno'] = $response->MerchantTransactionId;
			$deposit->update();

			$send['redirect'] = true;
			$send['redirect_url'] = $response->RedirectURL;
		}

		return json_encode($send);

	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
//        {"merchant_username":"gaming.center","merchant_api_password":"RVJT5WIY43J9285","merchant_id":"MER25851801","api_key":"9JRZYZ+oxl2A+ZuoXfgQZiPdiMehRfbDuAQK86nopPb041KGJp+TTQO/pUMEMPDh"}

		$API_KEY = $gateway->parameters->api_key ?? '';
		$UserName = $gateway->parameters->merchant_username ?? '';
		$Password = $gateway->parameters->merchant_api_password ?? '';
		$MerchantId = $gateway->parameters->merchant_id ?? '';

		$orderData = Deposit::with('gateway')
			->whereHas('gateway', function ($query) {
				$query->where('code', 'mypay');
			})
			->where('status', 0)
			->whereNotNull('referenceno')
			->latest()
			->get();

		if ($gateway->environment == 'test') {
			$url = "https://testapi.mypay.com.np/api/use-mypay-payments-status";
		} else {
			$url = "https://smartdigitalnepal.com/api/use-mypay-payments-status";
		}
		$headers = [
			'Content-Type: application/json',
			"API_KEY: $API_KEY",
		];

		foreach ($orderData as $data) {
			$postParam['MerchantTransactionId'] = $data->referenceno;
			$result = BasicCurl::curlPostRequestWithHeadersJson($url, $headers, $postParam);
			$response = json_decode($result);
			if (isset($response) && $response->Status == 1) {
				BasicService::preparePaymentUpgradation($data);
			}
		}

	}
}
PK     x\9	  	  +  Services/Gateway/cashonexHosted/Payment.phpnu [        <?php

namespace App\Services\Gateway\cashonexHosted;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;
use Illuminate\Support\Facades\Http;



class Payment
{
    public static function prepareData($deposit, $gateway)
    {

        $idempotency_key = $gateway->parameters->idempotency_key??'727649-0h76ac-467573-fxoxli-141433-c5ugg1';
        $salt = $gateway->parameters->salt??'67a8d2c1548c1ddb616bdc27e31fbd5e385f7872204043df7219498f08e4dcda';

        $headers = [
            'Content-Type: application/json',
            "Idempotency-Key: $idempotency_key",
        ];

        $postParam = [
            "salt" => $salt,
            "last_name" => optional($deposit->user)->lastname,
            "first_name" => optional($deposit->user)->firstname,
            "email" => optional($deposit->user)->email??'email@gmail.com',
            "phone" => optional($deposit->user)->phone??'9999999999',
            "address" => optional($deposit->user)->address??'123, address',
            "city" => optional($deposit->user)->city??'City',
            "state" => optional($deposit->user)->city??'State',
            "country" => optional($deposit->user)->country??'GB',
            "zip_code" => optional($deposit->user)->zip_code??'90210',
            "amount" => round($deposit->payable_amount ,2),
            "currency" => $deposit->payment_method_currency,
            "orderid" => $deposit->trx_id,
            "clientip" => request()->ip(),
            "redirect_url" => route('success'),
            "webhook_url" => route('ipn', [$gateway->code, $deposit->trx_id])
        ];

        $url = "https://cashonex.com/api/rest/payment";
        $result = BasicCurl::curlPostRequestWithHeadersJson($url, $headers, $postParam);
        $response = json_decode($result);


        if (isset($response->success) && $response->success == true) {
            $deposit->btc_wallet = @$response->data->paymentId;
            $deposit->update();

            $send['redirect'] = true;
            $send['redirect_url'] = $response->data->redirectUrl;
        } else {
            $send['error'] = true;
            $send['message'] = 'Unexpected Error!';
        }
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        if ($request['transaction_status'] == 'APPROVED' && $request['amount'] == round($deposit->final_amount ,2)) {
            BasicService::preparePaymentUpgradation($deposit);
        }

    }
}
PK     x\_YA  A  %  Services/Gateway/midtrans/Payment.phpnu [        <?php

namespace App\Services\Gateway\midtrans;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;
use Midtrans\Config;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
//		Config::$serverKey = $gateway->parameters->server_key ?? '';
//		Config::$isProduction = $gateway->environment == 'live';
//		Config::$isSanitized = true;
//		Config::$is3ds = true;
//		Config::$overrideNotifUrl = route('ipn', 'midtrans');

        \Midtrans\Config::$serverKey = $gateway->parameters->server_key ?? '';
        \Midtrans\Config::$isProduction = false;
        \Midtrans\Config::$isSanitized = true;
        \Midtrans\Config::$is3ds = true;
        \Midtrans\Config::$overrideNotifUrl = route('ipn', 'midtrans');

		$params = array(
			'transaction_details' => array(
				'order_id' => $deposit->trx_id,
				'gross_amount' => round($deposit->payable_amount, 2) * 100,
			),
			'customer_details' => array(
				'first_name' => optional($deposit->user)->firstname ?? 'John',
				'last_name' => optional($deposit->user)->lastname ?? 'Doe',
				'email' => optional($deposit->user)->email ?? 'example@gmail.com',
			),
		);

		$send['environment'] = $gateway->environment == 'live' ? 'live' : 'test';
		$send['client_key'] = $gateway->parameters->client_key ?? '';
		$send['token'] = \Midtrans\Snap::getSnapToken($params);

        $send['view'] = 'midtrans';

		return json_encode($send);
	}

	/**
	 * @param $request
	 * @param $gateway
	 * @param null $order
	 * @param null $trx
	 * @param null $type
	 * @return mixed
	 */
	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		if ($gateway->environment == 'live') {
			$url = "https://api.midtrans.com/v2/{$deposit->trx_id}/status";
		} else {
			$url = "https://api.sandbox.midtrans.com/v2/{$deposit->trx_id}/status";
		}
		$serverKey = $gateway->parameters->server_key ?? '';
		$headers = [
			'Content-Type:application/json',
			'Authorization:Basic ' . base64_encode("{$serverKey}:")
		];
		$response = BasicCurl::curlGetRequestWithHeaders($url, $headers);
		$paymentData = json_decode($response, true);
		if (isset($paymentData['transaction_status']) && ($paymentData['transaction_status'] == 'capture' || $paymentData['transaction_status'] == 'settlement')) {
			if ($paymentData['currency'] == $deposit->payment_method_currency && $paymentData['gross_amount'] == round($deposit->payable_amount, 2) * 100) {
				BasicService::preparePaymentUpgradation($deposit);

				$data['status'] = 'success';
				$data['msg'] = 'Transaction was successful.';
				$data['redirect'] = route('success');
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'invalid amount.';
				$data['redirect'] = route('failed');
			}
		} elseif (isset($paymentData['transaction_status']) && $paymentData['transaction_status'] == 'pending') {
			$data['status'] = 'error';
			$data['msg'] = 'Your payment is on pending.';
			$data['redirect'] = route('user.dashboard');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\9?  ?  %  Services/Gateway/cashmaal/Payment.phpnu [        <?php

namespace App\Services\Gateway\cashmaal;

use App\Models\Deposit;
use Facades\App\Services\BasicService;

class Payment
{
    public static function prepareData($deposit, $gateway)
    {
        $val['pay_method'] = " ";
        $val['amount'] = round($deposit->payable_amount, 2);
        $val['currency'] = $deposit->payment_method_currency;
        $val['succes_url'] = route('success');
        $val['cancel_url'] = twoStepPrevious($deposit);
        $val['client_email'] = $deposit->email ?? 'example@gmail.com';
        $val['web_id'] = $gateway->parameters->web_id;
        $val['order_id'] = $deposit->trx_id;
        $val['addi_info'] = "Payment";
        $send['url'] = 'https://www.cashmaal.com/Pay/';
        $send['method'] = 'post';
        $send['view'] = 'redirect';
        $send['val'] = $val;

        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $deposit = Deposit::where('trx_id', $request->order_id)->orderBy('id', 'desc')->first();
        if ($deposit) {
            if ($request->currency == $deposit->payment_method_currency && ($request->Amount == round($deposit->payable_amount, 2)) && $deposit->status == 0) {
                BasicService::preparePaymentUpgradation($deposit);
            }
        }
    }
}
PK     x\	  	  &  Services/Gateway/payumoney/Payment.phpnu [        <?php

namespace App\Services\Gateway\payumoney;

use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
		$hashVarsSeq = explode('|', $hashSequence);
		$hash_string = '';
		$send['val'] = [
			'key' => $gateway->parameters->merchant_key ?? '',
			'txnid' => $deposit->trx_id,
			'amount' => round($deposit->payable_amount, 2),
			'firstname' => optional($deposit->user)->name ?? $basic->site_title,
			'email' => optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? $basic->sender_email,
			'productinfo' => "Pay to $basic->site_title",
			'surl' => route('ipn', [$gateway->code, $deposit->trx_id]),
			'furl' => route('failed'),
			'service_provider' => $basic->site_title ?? $basic->site_title,
		];
		foreach ($hashVarsSeq as $hash_var) {
			$hash_string .= $send['val'][$hash_var] ?? '';
			$hash_string .= '|';
		}
		$hash_string .= $gateway->parameters->salt ?? '';

		$send['val']['hash'] = strtolower(hash('sha512', $hash_string));
		$send['view'] = 'redirect';
		$send['method'] = 'post';
		$send['url'] = 'https://test.payu.in/_payment';

		if ($gateway->environment == 'live') {
			$send['url'] = 'https://secure.payu.in/_payment';
		} else {
			$send['url'] = 'https://test.payu.in/_payment';
		}

		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		if (isset($request->status) && $request->status == 'success') {
			if (($gateway->parameters->merchant_key ?? '') == $request->key) {
				if ($deposit->trx_id == $request->txnid) {
					if (round($deposit->payable_amount, 2) <= $request->amount) {
						BasicService::preparePaymentUpgradation($deposit);

						$data['status'] = 'success';
						$data['msg'] = 'Transaction was successful.';
						$data['redirect'] = route('success');
					} else {
						$data['status'] = 'error';
						$data['msg'] = 'invalid amount.';
						$data['redirect'] = route('failed');
					}
				} else {
					$data['status'] = 'error';
					$data['msg'] = 'invalid trx id.';
					$data['redirect'] = route('failed');
				}
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'deposit into wrong account.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error.';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\9pu  u  )  Services/Gateway/coinpayments/Payment.phpnu [        <?php

namespace App\Services\Gateway\coinpayments;

use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();

		$isCrypto = (checkTo($gateway->currencies, $deposit->payment_method_currency) == 1) ? true : false;

		if ($isCrypto == false) {
			$val['merchant'] = $gateway->parameters->merchant_id ?? '';
			$val['item_name'] = $basic->site_title;
			$val['currency'] = $deposit->payment_method_currency;
			$val['currency_code'] = $deposit->payment_method_currency;
			$val['amountf'] = round($deposit->payable_amount, 2);
			$val['ipn_url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
			$val['custom'] = $deposit->trx_id;
			$val['amount'] = round($deposit->payable_amount, 2);
			$val['return'] = route('ipn', [$gateway->code, $deposit->trx_id]);
			$val['cancel_return'] = twoStepPrevious($deposit);
			$val['notify_url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
			$val['success_url'] = route('success');
			$val['cancel_url'] = twoStepPrevious($deposit);
			$val['cmd'] = '_pay_simple';
			$val['want_shipping'] = 0;
			$send['val'] = $val;
			$send['view'] = 'redirect';
			$send['method'] = 'post';
			$send['url'] = 'https://www.coinpayments.net/index.php';

		} else {

			if ($deposit->btc_wallet == 0 || $deposit->btc_wallet == "") {
				$cps = new CoinPaymentHosted();
				$cps->Setup($gateway->parameters->private_key, $gateway->parameters->public_key);
				$callbackUrl = route($gateway->extra_parameters->callback, $gateway->code);


				$req = array(
					'amount' => round($deposit->payable_amount, 2),
					'currency1' => 'USD',
					'currency2' => $deposit->payment_method_currency,
					'custom' => $deposit->trx_id,
					'ipn_url' => $callbackUrl,
					'buyer_email' => $deposit->email ?? 'hello@example.com'
				);
				$result = $cps->CreateTransaction($req);

				if ($result['error'] == 'ok') {
					$btc = sprintf('%.08f', $result['result']['amount']);
					$wallet = $result['result']['address'];
					$deposit['btc_wallet'] = $wallet;
					$deposit['btc_amount'] = $btc;
					$deposit->update();


					$send['amount'] = $deposit->btc_amount;
					$send['sendto'] = $deposit->btc_wallet;

					$send['img'] = BasicService::cryptoQR($deposit->btc_wallet, $deposit->btc_amount);
					$send['currency'] = $deposit->payment_method_currency ?? 'BTC';
					$send['view'] = 'crypto';

				} else {
					$send['error'] = true;
					$send['message'] = $result['error'];
				}
			}
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{

		$isCrypto = (checkTo($gateway->currencies, $deposit->payment_method_currency) == 1) ? true : false;

		$amount1 = floatval($request->amount1) ?? 0;
		$amount2 = floatval($request->amount2) ?? 0;
		$status = $request->status;
		if ($status >= 100 || $status == 2) {

			if ($deposit->payment_method_currency == $request->currency1 && round($deposit->payable_amount, 2) <= $amount1 && $gateway->parameters->merchant_id == $request->merchant && $deposit->status == '0') {
				BasicService::preparePaymentUpgradation($deposit);
			} elseif ($deposit->payment_method_currency == $request->currency2 && round($deposit->payable_amount, 2) <= $amount2 && $gateway->parameters->merchant_id == $request->merchant && $deposit->status == '0') {
				BasicService::preparePaymentUpgradation($deposit);
			} else {
				$data['status'] = 'error';
				$data['msg'] = 'Invalid amount.';
				$data['redirect'] = route('failed');
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Invalid response.';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\Uj    3  Services/Gateway/coinpayments/CoinPaymentHosted.phpnu [        <?php
namespace App\Services\Gateway\coinpayments;



class CoinPaymentHosted {
    private $private_key = '';
    private $public_key = '';
    private $ch = null;

    public function Setup($private_key, $public_key) {
        $this->private_key = $private_key;
        $this->public_key = $public_key;
        $this->ch = null;
    }

    /**
     * Gets the current CoinPayments.net exchange rate. Output includes both crypto and fiat currencies.
     * @param short If short == TRUE (the default), the output won't include the currency names and confirms needed to save bandwidth.
     */
    public function GetRates($short = TRUE) {
        $short = $short ? 1:0;
        return $this->api_call('rates', array('short' => $short));
    }

    /**
     * Gets your current coin balances (only includes coins with a balance unless all = TRUE).<br />
     * @param all If all = TRUE then it will return all coins, even those with a 0 balance.
     */
    public function GetBalances($all = FALSE) {
        return $this->api_call('balances', array('all' => $all ? 1:0));
    }

    /**
     * Creates a basic transaction with minimal parameters.<br />
     * See CreateTransaction for more advanced features.
     * @param amount The amount of the transaction (floating point to 8 decimals).
     * @param currency1 The source currency (ie. USD), this is used to calculate the exchange rate for you.
     * @param currency2 The cryptocurrency of the transaction. currency1 and currency2 can be the same if you don't want any exchange rate conversion.
     * @param address Optionally set the payout address of the transaction. If address is empty then it will follow your payout settings for that coin.
     * @param ipn_url Optionally set an IPN handler to receive notices about this transaction. If ipn_url is empty then it will use the default IPN URL in your account.
     * @param buyer_email Optionally (recommended) set the buyer's email so they can automatically claim refunds if there is an issue with their payment.
     */
    public function CreateTransactionSimple($amount, $currency1, $currency2, $address='', $ipn_url='', $buyer_email='') {
        $req = array(
            'amount' => $amount,
            'currency1' => $currency1,
            'currency2' => $currency2,
            'address' => $address,
            'ipn_url' => $ipn_url,
            'buyer_email' => $buyer_email,
        );
        return $this->api_call('create_transaction', $req);
    }

    public function CreateTransaction($req) {
        // See https://www.coinpayments.net/apidoc-create-transaction for parameters
        return $this->api_call('create_transaction', $req);
    }

    public function ViewTransaction($req) {
        // See https://www.coinpayments.net/apidoc-create-transaction for parameters
        return $this->api_call('get_tx_info', $req);
    }

    /**
     * Creates an address for receiving payments into your CoinPayments Wallet.<br />
     * @param currency The cryptocurrency to create a receiving address for.
     * @param ipn_url Optionally set an IPN handler to receive notices about this transaction. If ipn_url is empty then it will use the default IPN URL in your account.
     */
    public function GetCallbackAddress($currency, $ipn_url = '') {
        $req = array(
            'currency' => $currency,
            'ipn_url' => $ipn_url,
        );
        return $this->api_call('get_callback_address', $req);
    }

    /**
     * Creates a withdrawal from your account to a specified address.<br />
     * @param amount The amount of the transaction (floating point to 8 decimals).
     * @param currency The cryptocurrency to withdraw.
     * @param address The address to send the coins to.
     * @param auto_confirm If auto_confirm is TRUE, then the withdrawal will be performed without an email confirmation.
     * @param ipn_url Optionally set an IPN handler to receive notices about this transaction. If ipn_url is empty then it will use the default IPN URL in your account.
     */
    public function CreateWithdrawal($amount, $currency, $address, $auto_confirm = FALSE, $ipn_url = '') {
        $req = array(
            'amount' => $amount,
            'currency' => $currency,
            'address' => $address,
            'auto_confirm' => $auto_confirm ? 1:0,
            'ipn_url' => $ipn_url,
        );
        return $this->api_call('create_withdrawal', $req);
    }

    /**
     * Creates a transfer from your account to a specified merchant.<br />
     * @param amount The amount of the transaction (floating point to 8 decimals).
     * @param currency The cryptocurrency to withdraw.
     * @param merchant The merchant ID to send the coins to.
     * @param auto_confirm If auto_confirm is TRUE, then the transfer will be performed without an email confirmation.
     */
    public function CreateTransfer($amount, $currency, $merchant, $auto_confirm = FALSE) {
        $req = array(
            'amount' => $amount,
            'currency' => $currency,
            'merchant' => $merchant,
            'auto_confirm' => $auto_confirm ? 1:0,
        );
        return $this->api_call('create_transfer', $req);
    }

    /**
     * Creates a transfer from your account to a specified $PayByName tag.<br />
     * @param amount The amount of the transaction (floating point to 8 decimals).
     * @param currency The cryptocurrency to withdraw.
     * @param pbntag The $PayByName tag to send funds to.
     * @param auto_confirm If auto_confirm is TRUE, then the transfer will be performed without an email confirmation.
     */
    public function SendToPayByName($amount, $currency, $pbntag, $auto_confirm = FALSE) {
        $req = array(
            'amount' => $amount,
            'currency' => $currency,
            'pbntag' => $pbntag,
            'auto_confirm' => $auto_confirm ? 1:0,
        );
        return $this->api_call('create_transfer', $req);
    }

    private function is_setup() {
        return (!empty($this->private_key) && !empty($this->public_key));
    }

    private function api_call($cmd, $req = array()) {
        if (!$this->is_setup()) {
            return array('error' => 'You have not called the Setup function with your private and public keys!');
        }

        // Set the API command and required fields
        $req['version'] = 1;
        $req['cmd'] = $cmd;
        $req['key'] = $this->public_key;
        $req['format'] = 'json'; //supported values are json and xml

        // Generate the query string
        $post_data = http_build_query($req, '', '&');

        // Calculate the HMAC signature on the POST data
        $hmac = hash_hmac('sha512', $post_data, $this->private_key);

        // Create cURL handle and initialize (if needed)
        if ($this->ch === null) {
            $this->ch = curl_init('https://www.coinpayments.net/api.php');
            curl_setopt($this->ch, CURLOPT_FAILONERROR, TRUE);
            curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
        }
        curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('HMAC: '.$hmac));
        curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_data);

        $data = curl_exec($this->ch);
        if ($data !== FALSE) {
            if (PHP_INT_SIZE < 8 && version_compare(PHP_VERSION, '5.4.0') >= 0) {
                // We are on 32-bit PHP, so use the bigint as string option. If you are using any API calls with Satoshis it is highly NOT recommended to use 32-bit PHP
                $dec = json_decode($data, TRUE, 512, JSON_BIGINT_AS_STRING);
            } else {
                $dec = json_decode($data, TRUE);
            }
            if ($dec !== NULL && count($dec)) {
                return $dec;
            } else {
                // If you are using PHP 5.5.0 or higher you can use json_last_error_msg() for a better error message
                return array('error' => 'Unable to parse JSON result ('.json_last_error().')');
            }
        } else {
            return array('error' => 'cURL error: '.curl_error($this->ch));
        }
    }
};

PK     x\Ճ    #  Services/Gateway/imepay/Payment.phpnu [        <?php

namespace App\Services\Gateway\imepay;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Deposit;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicService;
use Facades\App\Services\BasicCurl;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$MerchantModule = optional($gateway->parameters)->MerchantModule;
		$MerchantCode = optional($gateway->parameters)->MerchantCode;
		$username = optional($gateway->parameters)->username;
		$password = optional($gateway->parameters)->password;


		$url = "https://stg.imepay.com.np:7979/api/Web/GetToken";

		$postParam = array(
			"MerchantCode" => $MerchantCode,
			"Amount" => round($deposit->payable_amount, 2),
			"RefId" => $deposit->trx_id);

		$headers = array(
			'Content-Type: application/json',
			'Module: ' . base64_encode("{$MerchantModule}"),
			'Authorization: Basic ' . base64_encode("{$username}:{$password}")
			//'Module: R0FNSU5HQ0VO',
			//'Authorization: Basic Z2FtaW5nY2VudGVyOmltZUAxMjM0'
		);


		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_ENCODING, '');
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		curl_setopt($ch, CURLOPT_TIMEOUT, 0);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParam));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		$result = curl_exec($ch);
		curl_close($ch);

		$checkResponse = json_decode($result);

		if ($checkResponse && isset($checkResponse->Message)) {
			$send['error'] = true;
			$send['message'] = "Error:" . @$checkResponse->Message;
			return json_encode($send);
		}

		$deposit->btc_wallet = @$checkResponse->TokenId;
		$deposit->save();

		$val['TokenId'] = $checkResponse->TokenId; //'IHzGMwNqGT24KHsD';
		$val['MerchantCode'] = optional($gateway->parameters)->MerchantCode;
		$val['RefId'] = $deposit->trx_id;
		$val['TranAmount'] = round($deposit->payable_amount, 2);
		$val['Method'] = 'GET';
		$val['RespUrl'] = route('ipn', [$gateway->code, $deposit->trx_id]);


		$CancelUrl = route('user.payment.request');
		$val['CancelUrl'] = $CancelUrl;
		$send['val'] = $val;
		$send['view'] = 'redirect';
		$send['method'] = 'post';
		$send['url'] = 'https://stg.imepay.com.np:7979/WebCheckout/Checkout';
		return json_encode($send);

	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{

		$imePayRes = $request->data;
		$res = base64_decode($imePayRes);
		$resArr = explode('|', $res);

		$order = Deposit::where('trx_id', $resArr[4])->orderBy('id', 'DESC')->with(['gateway'])->first();
		if ($order && $resArr[0] == 0 && $resArr[5] == round($order->payable_amount, 2) && $resArr[6] == $order->btc_wallet) {
			BasicService::preparePaymentUpgradation($order);
			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Invalid response.';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\LkR  R  (  Services/Gateway/flutterwave/Payment.phpnu [        <?php

namespace App\Services\Gateway\flutterwave;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;


class Payment
{
    public static function prepareData($deposit, $gateway)
    {
        $send['API_publicKey'] = $gateway->parameters->public_key ?? '';
        $send['customer_email'] = optional($deposit->user)->email ?? 'example@gmail.com';
        $send['customer_phone'] = optional($deposit->receiver)->phone ?? '';
        $send['amount'] = round($deposit->payable_amount, 2);
        $send['currency'] = $deposit->payment_method_currency;
        $send['txref'] = $deposit->trx_id;
        $send['view'] = 'flutterwave';
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        if ($type == 'error') {
            $data['status'] = 'error';
            $data['msg'] = 'transaction Failed.';
            $data['redirect'] = route('failed');
        } else {

            $url = 'https://api.ravepay.co/flwv3-pug/getpaidx/api/v2/verify';
            $headers = ['Content-Type:application/json'];
            $postParam = array(
                "SECKEY" => $gateway->parameters->secret_key ?? '',
                "txref" => $deposit->trx_id
            );

            $response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
            $response = json_decode($response);
            if ($response->data->status == "successful" && $response->data->chargecode == "00" && round($deposit->payable_amount, 2) == $response->data->amount && $deposit->payment_method_currency == $response->data->currency && $deposit->status == 0) {
                BasicService::preparePaymentUpgradation($deposit);

                $data['status'] = 'success';
                $data['msg'] = 'Transaction was successful.';
                $data['redirect'] = route('success');
            } else {
                $data['status'] = 'error';
                $data['msg'] = 'unable to Process.';
                $data['redirect'] = route('failed');
            }
        }
        return $data;
    }
}
PK     x\.5
  5
  &  Services/Gateway/freekassa/Payment.phpnu [        <?php

namespace App\Services\Gateway\freekassa;

use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$merchant_id = trim($gateway->parameters->merchant_id);
		$order_amount = round($deposit->payable_amount, 2);
//        $order_amount = number_format($order->final_amount, 2, '.', "");
		$secret_word = trim($gateway->parameters->secret_word);
		$currency = strtoupper($deposit->payment_method_currency);
		$order_id = $deposit->trx_id;
		$sign = md5($merchant_id . ':' . $order_amount . ':' . $secret_word . ':' . $currency . ':' . $order_id);

		$val['m'] = $merchant_id;
		$val['oa'] = $order_amount;
		$val['o'] = $order_id;
		$val['s'] = $sign;
		$val['currency'] = $currency;
		$val['i'] = '1';
		$val['phone'] = optional($deposit->user)->mobile ?? '415 123 1234';
		$val['em'] = optional($deposit->user)->email ?? 'example@gmail.com';
		$val['lang'] = 'en';
		$send['val'] = $val;
		$send['view'] = 'redirect';
		$send['method'] = 'get';
		$send['url'] = 'https://pay.freekassa.ru/';
		return json_encode($send);
	}


	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{

		$ipnrequest = @file_get_contents('php://input');
//        file_put_contents(time().'_freekassa.txt', $ipnrequest);

		if (!in_array(self::getIP(), array('168.119.157.136', '168.119.60.227', '138.201.88.124', '178.154.197.79'))) {
			$data['status'] = 'error';
			$data['msg'] = 'Hacking attempt!';
			$data['redirect'] = route('failed');
			return $data;
		};

		$merchant_id = trim($gateway->parameters->merchant_id);
		$merchant_secret = trim($gateway->parameters->secret_word2);
		$sign = md5($merchant_id . ':' . $_REQUEST['AMOUNT'] . ':' . $merchant_secret . ':' . $_REQUEST['MERCHANT_ORDER_ID']);


		if ($sign != $_REQUEST['SIGN']) {
			$data['status'] = 'error';
			$data['msg'] = 'wrong sign';
			$data['redirect'] = route('failed');
			return $data;
		}

		if ($_REQUEST['AMOUNT'] == round($deposit->payable_amount, 2) && $request->MERCHANT_ORDER_ID == $deposit->trx_id && $deposit->status == 0) {
			BasicService::preparePaymentUpgradation($deposit);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
			return $data;
		} else {

			$data['status'] = 'error';
			$data['msg'] = 'transaction was unsuccessful';
			$data['redirect'] = route('failed');
			return $data;
		}
	}


	//helper function
	public function getIP()
	{
		if (isset($_SERVER['HTTP_X_REAL_IP'])) return $_SERVER['HTTP_X_REAL_IP'];
		return $_SERVER['REMOTE_ADDR'];
	}

}
PK     x\yߗ#    $  Services/Gateway/konnect/Payment.phpnu [        <?php

namespace App\Services\Gateway\konnect;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{

		$postParam["receiverWalletId"] = $gateway->parameters->receiver_wallet_Id ?? '6399ed9208ec811bcda4af6e';
		$postParam["token"] = $deposit->payment_method_currency; // "TND" "EUR" "USD"

		if (in_array($postParam["token"], array("EUR", "GBP", "USD"))) {
			$postParam["amount"] = (int)$deposit->payable_amount * 100;
		} else {
			$postParam["amount"] = (int)$deposit->payable_amount;
		}

		$postParam["type"] = "immediate";
		$postParam["description"] = "Payment with konnect";
		$postParam["lifespan"] = 10;
		$postParam["feesIncluded"] = true;
		$postParam["firstName"] = optional($deposit->user)->firstname ?? 'John';
		$postParam["lastName"] = optional($deposit->user)->lastname ?? 'Doe';
		$postParam["phoneNumber"] = optional($deposit->user)->phone ?? '415 123 1234';
		$postParam["email"] = $deposit->email ?? 'example@gmail.com';
		$postParam["orderId"] = $deposit->trx_id;
		$postParam["webhook"] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$postParam["silentWebhook"] = true;
		$postParam["successUrl"] = route('success');
		$postParam["failUrl"] = route('failed');
		$postParam["checkoutForm"] = true;
		$postParam["acceptedPaymentMethods"] = ["wallet", "bank_card", "e-DINAR"];

		if ($gateway->environment == 'test') {
			$baseUrl = "https://api.preprod.konnect.network/api/v2/";
		} else {
			$baseUrl = "https://api.konnect.network/api/v2/";
		}
		$apiKey = $gateway->parameters->api_key ?? '6399ed9208ec811bcda4af6d:9WNA3dfjmDq6ynKb5RsRTYM7dIpq9';
		$headers = [
			'Content-Type:application/json',
			'x-api-key:' . "$apiKey"
		];

		$result = BasicCurl::curlPostRequestWithHeaders($baseUrl . 'payments/init-payment', $headers, $postParam);
		$response = json_decode($result);
		if (isset($response->payUrl)) {
			$deposit->btc_wallet = $response->paymentRef;
			$deposit->save();

			$send['redirect'] = true;
			$send['redirect_url'] = $response->payUrl;
		} else {

			$send['error'] = true;
			$send['message'] = "Error: " . @$response->errors[0]->message ?? 'Something Went wrong';
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$paymentId = $request->payment_ref;

		if ($gateway->environment == 'test') {
			$baseUrl = "https://api.preprod.konnect.network/api/v2/";
		} else {
			$baseUrl = "https://api.konnect.network/api/v2/";
		}

		$apiKey = $gateway->parameters->api_key ?? '6399ed9208ec811bcda4af6d:9WNA3dfjmDq6ynKb5RsRTYM7dIpq9';

		$headers = [
			'Content-Type:application/json',
			'x-api-key:' . "$apiKey"
		];

		$result = BasicCurl::curlGetRequestWithHeaders($baseUrl . 'payments/' . $paymentId, $headers);
		$response = json_decode($result);

		if (in_array($deposit->payment_method_currency, array("EUR", "GBP", "USD"))) {
			$convertedOrderAmount = (int)$deposit->payable_amount * 100;
		} else {
			$convertedOrderAmount = (int)$deposit->payable_amount;
		}
		if ($response->payment->amount == $convertedOrderAmount && $response->payment->status == 'completed') {
			BasicService::preparePaymentUpgradation($deposit);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Invalid response.';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\o߷    %  Services/Gateway/eCitizen/Payment.phpnu [        <?php

namespace App\Services\Gateway\eCitizen;

use App\Models\Deposit;
use Facades\App\Services\BasicService;
use hisorange\BrowserDetect\Exceptions\Exception;
use phpDocumentor\Reflection\Types\This;

class Payment
{
    public static function prepareData(Deposit $deposit, $gateway): string
    {
        if (empty($gateway->parameters->api_client_ID) || empty($gateway->parameters->secret)) {
            throw new \Exception("Unable to process with eCitizen Gateway. Missing API Client ID or Secret.");
        }

        $uri = ($gateway->environment == 'test' ? "https://test.pesaflow.com/PaymentAPI/iframev2.1.php" : "https://account.ecitizen.go.ke");
        $paymentDetails = [
            'apiClientID' => $gateway->parameters->api_client_ID,
            'serviceID' => $gateway->parameters->service_ID,
            'billRefNumber' => $deposit->trx_id,
            'billDesc' => 'Total amount of order items',
            'clientMSISDN' => $deposit->user->phone,
            'clientIDNumber' => $deposit->user->id,
            'clientName' => $deposit->user->firstname && $deposit->user->lastname != '' ? $deposit->user->firstname . ' ' . $deposit->user->lastname : $deposit->user->username,
            'clientEmail' => $deposit->user->email ?? '',
            'notificationURL' => '',
            'pictureURL' => "false",
            'callBackURLOnSuccess' => route('ipn', ['code' => 'eCitizen', 'trx' => $deposit->trx_id]),
            'currency' => $deposit->payment_method_currency,
            'amountExpected' => round($deposit->payable_amount, 2),
            'format' => "html",
            'sendSTK' => "false",
            'secret' => $gateway->parameters->secret,
            'success_url' => route('success'),
            'cancel_url' => twoStepPrevious($deposit),
            'additional_info' => "Payment for order ID: {$deposit->trx_id}",
        ];

        $data_string = implode('', [
            $paymentDetails['apiClientID'],
            $paymentDetails['amountExpected'],
            $paymentDetails['serviceID'],
            $paymentDetails['clientIDNumber'],
            $paymentDetails['currency'],
            $paymentDetails['billRefNumber'],
            $paymentDetails['billDesc'],
            $paymentDetails['clientName'],
            $paymentDetails['secret']
        ]);
        $secure_hash = base64_encode(hash_hmac('sha256', $data_string, $gateway->parameters->key, false));

        $paymentDetails['secureHash'] = $secure_hash;

        $send['url'] = $uri;
        $send['method'] = 'POST';
        $send['view'] = 'redirect';
        $send['val'] = $paymentDetails;
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {

        $_this = new self();
        $deposit = Deposit::where('trx_id', $request->order_id)->orderBy('id', 'desc')->first();
        if (!$deposit) {
            return response()->json(['error' => 'Deposit not found']);
        }

        if ($request->status == 500) {
            return $_this->updateAndMessage($deposit, 3, 'Failed', 'Payment failed.');
        }

        $data_string = implode('', [
            $gateway->parameters->api_client_ID,
            round($request->Amount, 2),
            $gateway->parameters->service_ID,
            $request->order_id,
            $request->currency,
            $request->order_id,
            'Total amount of order items',
            trim(($deposit->user->firstname ?? 'Unknown') . ' ' . ($deposit->user->lastname ?? 'User')),
            $gateway->parameters->secret
        ]);

        $generated_hash = base64_encode(hash_hmac('sha256', $data_string, $gateway->parameters->key, false));

        if (!hash_equals($generated_hash, $request->secure_hash)) {
            return response()->json(['error' => 'Invalid payment details']);
        }

        if ($deposit->status == 0) {
            BasicService::preparePaymentUpgradation($deposit);
            $data['status'] = 'success';
            $data['msg'] = 'Transaction was successful.';
            $data['redirect'] = route('success');
            return response()->json($data);
        }
        return response()->json(['error' => 'Invalid payment details or transaction already processed']);
    }

    protected function updateAndMessage($deposit, $status, $note, $msg)
    {
        $deposit->update([
            'status' => $status,
            'note' => $note
        ]);
        return [
            'status' => 'error',
            'msg' => $msg,
            'redirect' => route('failed')
        ];
    }
}
PK     x\ն|    #  Services/Gateway/stripe/Payment.phpnu [        <?php

namespace App\Services\Gateway\stripe;

use Facades\App\Services\BasicService;
use Stripe\Stripe;
use Stripe\PaymentIntent;
use Stripe\Checkout\Session as CheckoutSession;

class Payment
{
    public static function prepareData($deposit, $gateway)
    {
        $basic = basicControl();
        $amount = (int)(round($deposit->payable_amount) * 100);
        Stripe::setApiKey($gateway->parameters->secret_key);

        $checkoutSession = CheckoutSession::create([
            'line_items' => [[
                'price_data' => [
                    'currency' => $deposit->payment_method_currency,
                    'product_data' => [
                        'name' => optional($deposit->receiver)->name ?? $basic->site_title,
                    ],
                    'unit_amount' => $amount,
                ],
                'quantity' => 1,
            ]],
            'mode' => 'payment',
            'success_url' => route('ipn', [$gateway->code, $deposit->trx_id]). '?payment_intent={CHECKOUT_SESSION_ID}',
            'cancel_url' => route('failed'),
        ]);
        if (isset($checkoutSession->url)) {
            $send['redirect'] = true;
            $send['redirect_url'] = $checkoutSession->url;
        } else {
            $send['error'] = true;
            $send['message'] = 'Unexpected Error! Please Try Again';
        }
        return json_encode($send);
    }

    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {

        Stripe::setApiKey($gateway->parameters->secret_key);


        $checkoutSession = CheckoutSession::retrieve($request->payment_intent);
        $paymentIntentId = $checkoutSession->payment_intent;

        $paymentIntent = PaymentIntent::retrieve($paymentIntentId);

        if ($paymentIntent->status == 'succeeded') {
            BasicService::preparePaymentUpgradation($deposit);

            $data['status'] = 'success';
            $data['msg'] = 'Transaction was successful.';
            $data['redirect'] = route('success');
        } else {
            $data['status'] = 'error';
            $data['msg'] = 'Unsuccessful transaction.';
            $data['redirect'] = route('failed');
        }

        return $data;
    }
}
PK     x\,e    %  Services/Gateway/razorpay/Payment.phpnu [        <?php

namespace App\Services\Gateway\razorpay;

use Facades\App\Services\BasicService;
use Razorpay\Api\Api;


class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$api_key = $gateway->parameters->key_id ?? '';
		$api_secret = $gateway->parameters->key_secret ?? '';
		$razorPayApi = new Api($api_key, $api_secret);
		$finalAmount = round($deposit->payable_amount, 2) * 100;
		$gatewayCurrency = $deposit->payment_method_currency;
		$trx = $deposit->trx_id;

		$razorOrder = $razorPayApi->order->create(
			array(
				'receipt' => $trx,
				'amount' => $finalAmount,
				'currency' => $gatewayCurrency,
				'payment_capture' => '0'
			)
		);

		$val['key'] = $api_key;
		$val['amount'] = $finalAmount;
		$val['currency'] = $gatewayCurrency;
		$val['order_id'] = $razorOrder['id'];
		$val['buttontext'] = "Pay Now";
		$val['name'] = optional($deposit->user)->name ?? $basic->site_title;
		$val['description'] = "Payment By Razorpay";
		$val['image'] = getFile(config('location.logo.path') . 'logo.png');
		$val['prefill.name'] = optional($deposit->user)->name ?? $basic->site_title;
		$val['prefill.email'] = optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? $basic->sender_email;
		$val['prefill.contact'] = optional($deposit->user)->phone ?? '';
		$val['theme.color'] = "#2ecc71";
		$send['val'] = $val;

		$send['method'] = 'POST';
		$send['url'] = route('ipn', [$gateway->code, $deposit->trx_id]);
		$send['custom'] = $trx;
		$send['checkout_js'] = "https://checkout.razorpay.com/v1/checkout.js";
		$send['view'] = 'razorpay';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $order = null, $trx = null, $type = null)
	{
		$api_secret = $gateway->parameters->key_secret ?? '';
		$signature = hash_hmac('sha256', $request->razorpay_order_id . "|" . $request->razorpay_payment_id, $api_secret);

		if ($signature == $request->razorpay_signature) {
			BasicService::preparePaymentUpgradation($order);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\Ԛ    %  Services/Gateway/coingate/Payment.phpnu [        <?php

namespace App\Services\Gateway\coingate;

use CoinGate\CoinGate;
use CoinGate\Merchant\Order;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{

        try {

            $basic = basicControl();
            $env = $gateway->environment == 'live' ? 'live' : 'sandbox';
            if ($deposit) {
                if ($deposit->mode == 1) {
                    $env = 'sandbox';
                }
            }

            CoinGate::config(array(
                'environment' => $env,
                'auth_token' => $gateway->parameters->api_key
            ));

            $postParams = array(
                'order_id' => $deposit->trx_id,
                'price_amount' => round($deposit->payable_amount, 2),
                'price_currency' => $deposit->payment_method_currency,
                'receive_currency' => $deposit->payment_method_currency,
                'callback_url' => route('ipn', [$gateway->code, $deposit->trx_id]),
                'cancel_url' => twoStepPrevious($deposit),
                'success_url' => route('success'),
                'title' => "Pay To $basic->site_title",
                'token' => $deposit->trx_id
            );

            $order = Order::create($postParams);
            if ($order) {
                $send['redirect'] = true;
                $send['redirect_url'] = $order->payment_url;
            } else {
                $send['error'] = true;
                $send['message'] = 'Unexpected Error! Please Try Again';
            }

            return json_encode($send);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$ip = $request->ip();
		$url = 'https://api.coingate.com/v2/ips-v4';
		$response = BasicCurl::curlGetRequest($url);
		if (strpos($response, $ip) !== false) {
			if ($request->status == 'paid' && $request->price_amount == round($deposit->payable_amount, 2) && $deposit->status == 0) {
				BasicService::preparePaymentUpgradation($deposit);
			}
		}
	}
}
PK     x\~-x
  x
  #  Services/Gateway/payeer/Payment.phpnu [        <?php

namespace App\Services\Gateway\payeer;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Deposit;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$m_amount = number_format($deposit->payable_amount, 2, '.', "");

		$arHash = [
			trim($gateway->parameters->merchant_id),
			$deposit->trx_id,
			$m_amount,
			$deposit->payment_method_currency,
			base64_encode("Pay To $basic->site_title"),
			trim($gateway->parameters->secret_key)
		];

		$val['m_shop'] = trim($gateway->parameters->merchant_id);
		$val['m_orderid'] = $deposit->trx_id;
		$val['m_amount'] = round($deposit->payable_amount, 2);
		$val['m_curr'] = $deposit->payment_method_currency;
		$val['m_desc'] = base64_encode("Pay To $basic->site_title");
		$val['m_sign'] = strtoupper(hash('sha256', implode(":", $arHash)));
		$send['val'] = $val;
		$send['view'] = 'redirect';
		$send['method'] = 'get';
		$send['url'] = 'https://payeer.com/merchant';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		if (isset($request->m_operation_id) && isset($request->m_sign)) {
			$sign_hash = strtoupper(hash('sha256', implode(":", array(
				$request->m_operation_id,
				$request->m_operation_ps,
				$request->m_operation_date,
				$request->m_operation_pay_date,
				$request->m_shop,
				$request->m_orderid,
				$request->m_amount,
				$request->m_curr,
				$request->m_desc,
				$request->m_status,
				$gateway->parameters->secret_key
			))));

			if ($request->m_sign != $sign_hash) {
				$data['status'] = 'error';
				$data['msg'] = 'digital signature not matched';
				$data['redirect'] = route('failed');
			} else {
				$deposit = Deposit::with('user')->where('trx_id', $request->m_orderid)->latest()->first();
				if ($request->m_amount == $deposit->payable_amount && $request->m_curr == $deposit->payment_method_currency && $request->m_status == 'success' && $deposit->status == 0) {
					BasicService::preparePaymentUpgradation($deposit);
					$data['status'] = 'success';
					$data['msg'] = 'Transaction was successful.';
					$data['redirect'] = route('success');
					return $data;
				} else {
					$data['status'] = 'error';
					$data['msg'] = 'transaction was unsuccessful';
					$data['redirect'] = route('failed');
					return $data;
				}
			}
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'transaction was unsuccessful';
			$data['redirect'] = route('failed');
		}
		return $data;
	}
}
PK     x\_u    (  Services/Gateway/nowpayments/Payment.phpnu [        <?php

namespace App\Services\Gateway\nowpayments;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$APIkey = $gateway->parameters->api_key ?? '';
		if ($gateway->environment == 'test') {
			$url = 'https://api-sandbox.nowpayments.io/v1/';
		} else {
			$url = 'https://api.nowpayments.io/v1/';
		}

		$postField['price_amount'] = (string)round($deposit->payable_amount, 2);
		$postField['price_currency'] = "USD";
		$postField['pay_currency'] = $deposit->payment_method_currency;
		$postField['ipn_callback_url'] = "https://nowpayments.io";
		$postField['order_id'] = $deposit->trx_id;
		$postField['order_description'] = "Deposit on " . config('basic.site_title') . " account";


		$curl = curl_init();
		curl_setopt_array($curl, array(
			CURLOPT_URL => $url . 'payment',
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS => json_encode($postField),
			CURLOPT_HTTPHEADER => array(
				"x-api-key: $APIkey",
				'Content-Type: application/json'
			),
		));

		$response = curl_exec($curl);
		$result = json_decode($response);
		if (isset($result->status) && $result->status == false) {
			$send['error'] = true;
			$send['message'] = $result->message;
			$send['view'] = 'crypto';
			return json_encode($send);
		} else {
			$deposit['btc_wallet'] = $result->pay_address;
			$deposit['btc_amount'] = $result->pay_amount;
			$deposit['payment_id'] = $result->payment_id;
			$deposit->update();
		}


		$send['amount'] = $deposit->btc_amount;
		$send['sendto'] = $deposit->btc_wallet;
		$send['img'] = BasicService::cryptoQR($deposit->btc_wallet, $deposit->btc_amount);
		$send['currency'] = $deposit->payment_method_currency ?? 'BTC';
		$send['view'] = 'crypto';
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$APIkey = $gateway->parameters->api_key ?? '';
		if ($gateway->environment == 'test') {
			$url = 'https://api-sandbox.nowpayments.io/v1/';
		} else {
			$url = 'https://api.nowpayments.io/v1/';
		}

		$orderData = Deposit::with('gateway')
			->whereHas('gateway', function ($query) {
				$query->where('code', 'nowpayments');
			})
			->where('status', 0)
			->where('btc_amount', '>', 0)
			->whereNotNull('btc_wallet')
			->whereNotNull('payment_id ')
			->latest()
			->get();

		foreach ($orderData as $data) {
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => $url . 'payment/' . $data->payment_id,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => '',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 0,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => 'GET',
				CURLOPT_HTTPHEADER => array(
					"x-api-key: $APIkey"
				),
			));

			$response = curl_exec($curl);
			curl_close($curl);

			$res = json_decode($response);

			if (isset($res->status) && $res->status == false) {
				continue;
			} else {
				if ($res->payment_status == 'finished') {
					BasicService::preparePaymentUpgradation($data);
				}

			}
		}
	}
}
PK     x\Zp  p  $  Services/Gateway/fastpay/Payment.phpnu [        <?php

namespace App\Services\Gateway\fastpay;

use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = (object)config('basic');
		$store_id = $gateway->parameters->store_id ?? '';
		$store_password = $gateway->parameters->store_password ?? '';
		$order_id = $deposit->trx_id;
		$bill_amount = (int)round($deposit->payable_amount, 2);
		$currency = $deposit->payment_method_currency;

		if ($gateway->environment == 'live' && $deposit->mode == 0) {
			$url = "https://apigw-merchant.fast-pay.iq/api/v1/public/pgw/payment/initiation";
		} else {
			$url = "https://staging-apigw-merchant.fast-pay.iq/api/v1/public/pgw/payment/initiation";
		}

		$curl = curl_init();

		curl_setopt_array($curl, array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS => array('store_id' => $store_id, 'store_password' => $store_password, 'order_id' => $order_id, 'bill_amount' => $bill_amount, 'currency' => $currency, 'cart' => '[{"name":"Scarf","qty":1,"unit_price":1000,"sub_total":1000}]'),
			CURLOPT_HTTPHEADER => array(
				'Cookie: cookiesession1=678B286D4B6C7555E2DFC4B98D7F35FE'
			),
		));

		$response = curl_exec($curl);

		curl_close($curl);
		$res = json_decode($response);

		if ($deposit) {
			if (isset($res->data->redirect_uri)) {
				$send['redirect'] = true;
				$send['redirect_url'] = $res->data->redirect_uri;
			} else {
				$send['error'] = true;
				$send['message'] = 'Unexpected Error! Please Try Again';
			}
		} else {
			$send['error'] = true;
			$send['message'] = 'Unexpected Error! Please Try Again';
		}

		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$store_id = $gateway->parameters->store_id ?? '';
		$store_password = $gateway->parameters->store_password ?? '';
		$order_id = $deposit->trx_id;

		if ($gateway->environment == 'live' && $deposit->mode == 0) {
			$url = "https://apigw-merchant.fast-pay.iq/api/v1/public/pgw/payment/validate";
		} else {
			$url = "https://staging-apigw-merchant.fast-pay.iq/api/v1/public/pgw/payment/validate";
		}

		$curl = curl_init();

		curl_setopt_array($curl, array(
			CURLOPT_URL => $url,
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_ENCODING => '',
			CURLOPT_MAXREDIRS => 10,
			CURLOPT_TIMEOUT => 0,
			CURLOPT_FOLLOWLOCATION => true,
			CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
			CURLOPT_CUSTOMREQUEST => 'POST',
			CURLOPT_POSTFIELDS => array('store_id' => $store_id, 'store_password' => $store_password, 'order_id' => $order_id),
			CURLOPT_HTTPHEADER => array(
				'Cookie: cookiesession1=678B286D4B6C7555E2DFC4B98D7F35FE'
			),
		));

		$response = curl_exec($curl);
		curl_close($curl);
		$paymentData = json_decode($response, true);

		if (isset($paymentData['status']) && $paymentData['status'] == 'Success') {
			BasicService::preparePaymentUpgradation($deposit);
			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');

		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}
		return $data;
	}

}
PK     x\ &
  
  (  Services/Gateway/mercadopago/Payment.phpnu [        <?php

namespace App\Services\Gateway\mercadopago;

use App\Models\ApiOrder;
use App\Models\ApiOrderTest;
use App\Models\Invoice;
use App\Models\ProductOrder;
use App\Models\QRCode;
use App\Models\Voucher;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\BasicService;

class Payment
{
	const SANDBOX = true;

	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		$url = "https://api.mercadopago.com/checkout/preferences?access_token=" . $gateway->parameters->access_token;
		$headers = [
			"Content-Type: application/json",
		];
		$postParam = [
			'items' => [
				[
					'id' => $deposit->trx_id,
					'title' => "Pay to $basic->site_title",
					'description' => "Payment To $basic->site_title Account",
					'quantity' => 1,
					'currency_id' => $deposit->payment_method_currency,
					'unit_price' => round($deposit->payable_amount, 2)
				]
			],
			'payer' => [
				'email' => optional($deposit->user)->email ?? optional($deposit->depositable)->email ?? $basic->sender_email,
			],
			'back_urls' => [
				'success' => route('success'),
				'pending' => '',
				'failure' => route('failed'),
			],
			'notification_url' => route('ipn', [$gateway->code, $deposit->trx_id]),
			'auto_return' => 'approved',
		];
		$response = BasicCurl::curlPostRequestWithHeaders($url, $headers, $postParam);
		$response = json_decode($response);
		$send['preference'] = $preference->id ?? '';
		$send['view'] = 'mercado';
		if ($response->auto_return == 'approved') {
			if (self::SANDBOX) {
				$send['redirect'] = true;
				$send['redirect_url'] = $response->sandbox_init_point;
			} else {
				$send['redirect'] = true;
				$send['redirect_url'] = $response->init_point;
			}
			if ($deposit) {
				if ($deposit->mode == 1) {
					$send['redirect'] = true;
					$send['redirect_url'] = $response->sandbox_init_point;
				}
			}
		} else {
			$send['error'] = true;
			$send['message'] = 'Invalid Request';
		}
		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		$url = "https://api.mercadopago.com/v1/payments/" . $request['data']['id'] . "?access_token=" . $gateway->parameters->access_token;
		$response = BasicCurl::curlGetRequest($url);
		$paymentData = json_decode($response);

		if (isset($paymentData->status) && $paymentData->status == 'approved') {
			BasicService::preparePaymentUpgradation($deposit);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'unexpected error!';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\W    #  Services/Gateway/mollie/Payment.phpnu [        <?php

namespace App\Services\Gateway\mollie;

use Facades\App\Services\BasicService;
use Mollie\Laravel\Facades\Mollie;

class Payment
{
	public static function prepareData($deposit, $gateway)
	{
		$basic = basicControl();
		config(['mollie.key' => trim($gateway->parameters->api_key)]);

		$payment = Mollie::api()->payments()->create([
			'amount' => [
				'currency' => $deposit->payment_method_currency,
				'value' => '' . round($deposit->payable_amount, 2),
			],
			'description' => "Payment To $basic->site_title Account",
			'redirectUrl' => route('ipn', [$gateway->code, $deposit->trx_id]),
			'metadata' => [
				"order_id" => $deposit->trx_id,
			],
		]);

		session()->put('payment_id', $payment->id);

		$payment = Mollie::api()->payments()->get($payment->id);

		$send['redirect'] = true;
		$send['redirect_url'] = $payment->getCheckoutUrl();

		return json_encode($send);
	}

	public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
	{
		config(['mollie.key' => trim($gateway->parameters->api_key)]);
		$payment = Mollie::api()->payments()->get(session()->get('payment_id'));
		if ($payment->status == "paid") {
			BasicService::preparePaymentUpgradation($deposit);

			$data['status'] = 'success';
			$data['msg'] = 'Transaction was successful.';
			$data['redirect'] = route('success');
		} else {
			$data['status'] = 'error';
			$data['msg'] = 'Invalid response.';
			$data['redirect'] = route('failed');
		}

		return $data;
	}
}
PK     x\    "  Services/Gateway/nagad/Payment.phpnu [        <?php

namespace App\Services\Gateway\nagad;

use App\Models\Deposit;
use App\Traits\Nagad;
use Facades\App\Services\BasicService;
use Exception;
use Illuminate\Support\Facades\Http;

class Payment
{
    use Nagad;

    public static function prepareData($deposit, $gateway)
    {
        $_this = new self();
        throw_if(empty($gateway->parameters->merchant_id ?? ""), "Unable to process with nagad.");

        $refNo = $deposit->trx_id;
        $additionalInfo = null;
        $sensitiveData = $_this->generateSensitiveData($gateway->parameters->merchant_id, $refNo);

        $response = Http::withHeaders($_this->headers())
            ->acceptJson()
            ->post($_this->getBaseURL($gateway->environment) . "/check-out/initialize/{$gateway->parameters->merchant_id}/{$refNo}", [
                'accountNumber' => $gateway->parameters->merchant_id,
                'dateTime' => now('Asia/Dhaka')->format('YmdHis'),
                'sensitiveData' => $_this->encryptDataWithPublicKey($gateway, json_encode($sensitiveData)),
                'signature' => $_this->signatureGenerate($gateway, json_encode($sensitiveData))
            ]);

        throw_if($response->status() != 200, "Something went wrong while trying to pay with nagad.");

        $nagadData = json_decode($response->body());

        throw_if(isset($nagadData->reason), "Something went wrong while trying to pay with nagad.");

        throw_if(!$_this->decryptInitialResponse($gateway, $nagadData), "Something went wrong while trying to pay with nagad.");

        $sensitiveOrderData = $_this->generateSensitiveDataOrder($gateway->parameters->merchant_id, $refNo, $deposit->payable_amount_in_base_currency, $deposit->base_currency_charge);

        $completeResponse = Http::withHeaders($_this->headers())
            ->acceptJson()
            ->post($_this->getBaseURL($gateway->environment) . "/check-out/complete/{$_this->PAYMENT_REF_ID}", [
                'sensitiveData' => $_this->encryptDataWithPublicKey($gateway, json_encode($sensitiveOrderData)),
                'signature' => $_this->signatureGenerate($gateway, json_encode($sensitiveOrderData)),
                'merchantCallbackURL' => route('ipn', ['code' => 'nagad', 'trx' => $deposit->trx_id]),
                'additionalMerchantInfo' => (object)$additionalInfo
            ]);

        throw_if($completeResponse->status() != 200, "Something went wrong while trying to initiate payment with nagad.");

        $nagadCompleteData = json_decode($completeResponse->body());

        throw_if(isset($nagadCompleteData->reason), "Something went wrong while trying to initiate payment with nagad.");

        $nagadCompleteData->paymentID = $_this->PAYMENT_REF_ID;

        $deposit->update([
            'payment_id' => $nagadCompleteData->paymentID
        ]);

        $data['redirect'] = true;
        $data['redirect_url'] = $nagadCompleteData->callBackUrl;
        return json_encode($data);
    }


    public static function ipn($request, $gateway, $deposit = null, $trx = null, $type = null)
    {
        $_this = new self();
        if (isset($request->status) && $request->status == 'Failed') {
            return $_this->updateAndMessage($deposit, 'Payment Failed', $request->status, $request->message);
        }

        if (isset($request->status) && $request->status == 'Cancelled') {
            return $_this->updateAndMessage($deposit, 'Payment Cancelled', $request->status, $request->message);
        }

        if (isset($request->status) && $request->status == 'InvalidRequest') {
            return $_this->updateAndMessage($deposit, 'Invalid Request', $request->status, $request->message);
        }

        if (isset($request->status) && $request->status == 'Fraud') {
           return  $_this->updateAndMessage($deposit, 'fraudulent activity', $request->status, $request->message);
        }

        if (isset($request->status) && $request->status == 'Aborted') {
           return $_this->updateAndMessage($deposit, 'Aborted', $request->status, $request->message);
        }

        if (isset($request->status) && $request->status == 'UnknownFailed') {
            return $_this->updateAndMessage($deposit, 'Unknown Failed', $request->status, $request->message);
        }

        $merchantId = $gateway->parameters->merchant_id;

        if (isset($request->status, $request->payment_ref_id, $request->merchant) && $request->status == 'Success' && $request->merchant == $merchantId) {
            $verifyPaymentResponse = $_this->verifyPayment($gateway, $request->payment_ref_id);

            if (isset($verifyPaymentResponse->status, $verifyPaymentResponse->merchantId, $verifyPaymentResponse->paymentRefId, $verifyPaymentResponse->issuerPaymentRefNo, $verifyPaymentResponse->amount) && $verifyPaymentResponse->status == 'Success' && $verifyPaymentResponse->merchantId == $merchantId) {
                BasicService::preparePaymentUpgradation($deposit);
                $data['status'] = strtolower($request->status);
                $data['msg'] = $verifyPaymentResponse->message;
                $data['redirect'] = route('success');
                return $data;
            } else {
                return $_this->updateAndMessage($deposit, 'Unknown Failed', 'Failed', $verifyPaymentResponse->message);
            }
        }
    }


    public function verifyPayment($gateway, $paymentId)
    {
        throw_if(empty($this->getBaseURL($gateway->environment)) || empty($gateway->parameters->merchant_id ?? ""), "Unable to process with nagad.");

        $response = Http::withHeaders($this->headers())
            ->acceptJson()
            ->get($this->getBaseURL($gateway->environment) . "/verify/payment/{$paymentId}");

        if ($response->status() == 200) {
            $nagadResponse = json_decode($response->body());
            return $nagadResponse;
        }

        throw new Exception("Something went wrong while trying to verify your payment with nagad.");
    }

    public static function refund($deposit, $refNo, $gateway, $amount)
    {
        $_this = new self();
        throw_if(empty($_this->getBaseURL($gateway->environment)) || empty($gateway->parameters->merchant_id), "Unable to process with nagad.");

        $sensitiveOrderData = [
            'merchantId' => $gateway->parameters->merchant_id,
            "originalRequestDate" => now('Asia/Dhaka')->format('Ymd'),
            'originalAmount' => $deposit->payable_amount,
            'cancelAmount' => $amount,
            'referenceNo' => $refNo,
            'referenceMessage' => "Requested for refund.",
        ];

        $response = Http::withHeaders($_this->headers())
            ->post($_this->getBaseURL($gateway->environment) . "/purchase/cancel?paymentRefId={$deposit->payment_id}&orderId={$refNo}", [
                "sensitiveDataCancelRequest" => $_this->encryptDataWithPublicKey($gateway, json_encode($sensitiveOrderData)),
                "signature" => $_this->signatureGenerate($gateway, json_encode($sensitiveOrderData))
            ]);

        if ($response->status() == 200) {
            $nagadResponse = json_decode($response->body());
            return json_decode($_this->decryptDataWithPrivateKey($gateway, $nagadResponse->sensitiveData));
        }
        throw new Exception("Something went wrong while trying to verify your payment with nagad.");
    }

}
PK     x\$  $  &  Services/Gateway/toyyibpay/Payment.phpnu [        <?php

namespace App\Services\Gateway\toyyibpay;

use App\Models\Deposit;
use App\Traits\ToyyibPay;
use Dflydev\DotAccessData\Data;
use Facades\App\Services\BasicService;
use Exception;
use Illuminate\Support\Facades\Http;

class Payment
{
    use ToyyibPay;

    public static function prepareData($deposit, $gateway)
    {
        throw_if(empty($gateway->parameters->category_code ?? "") || empty($gateway->parameters->secret_key ?? ""), "Unable to process with Toyyib Pay.");
        $_this = new self();
        $data = [
            'userSecretKey' => $gateway->parameters->secret_key,
            'categoryCode' => $gateway->parameters->category_code,
            'billName' => 'Payment for #' . $deposit->trx_id,
            'billDescription' => 'Total amount of order items',
            'billPriceSetting' => 0,
            'billPayorInfo' => 1,
            'billAmount' => round($deposit->payable_amount*100, 2),
            'billReturnUrl' => route('ipn', ['code' => 'toyyibpay', 'trx' => $deposit->trx_id]),
            'billCallbackUrl' => route('ipn', ['code' => 'toyyibpay', 'trx' => $deposit->trx_id]),
            'billExternalReferenceNo' => $deposit->trx_id,
            'billTo' => $deposit->user->firstname . ' ' . $deposit->user->lastname,
            'billEmail' => $deposit->user->email ?? '-',
            'billPhone' => $deposit->user->phone ?? '-',
            'billPaymentChannel' => '2',
            'billContentEmail' => 'Thank you for purchasing our product!',
            'billChargeToCustomer' => '',
        ];

        $uri = $_this->getBaseURL($gateway->environment) . "/index.php/api/createBill";

        $response = Http::asForm()->post($uri, $data);

        if ($response->status() == 200) {
            $tayebPayResponse = json_decode($response->body());

            throw_if(!isset($tayebPayResponse), 'Failed to initiate payment with Toyyib Pay.');

            $deposit->update([
                'payment_id' => $tayebPayResponse[0]->BillCode
            ]);

            $returnData = [
                'redirect' => true,
                'redirect_url' => $_this->getBaseURL($gateway->environment) . '/' . $tayebPayResponse[0]->BillCode
            ];
            return json_encode($returnData);
        }
        throw new Exception("Something went wrong while initiating the payment with Toyyib Pay.");
    }


    public static function ipn($request, $gateway, $deposit = null, $trx = null)
    {
        $_this = new self();
        if ((isset($request->status_id) && $request->status_id == 3) || (isset($request->status) && $request->status == 3)){
            return $_this->updateAndMessage($deposit, 3,'Failed', 'Payment failed.');
        }

        if ((isset($request->status_id) && $request->status_id == 1) || (isset($request->status) && $request->status == 1)){
            $verifyResponse = $_this->verifyPayment($request, $deposit, $gateway);

            if (isset($verifyResponse) && $verifyResponse->billExternalReferenceNo == $deposit->trx_id && $verifyResponse->billpaymentStatus == 1) {
                BasicService::preparePaymentUpgradation($deposit, $verifyResponse->billpaymentInvoiceNo, 'Toyyib Pay Gateway');
                $data['status'] = 'success';
                $data['msg'] = 'Transaction was successful.';
                $data['redirect'] = route('success');
                return $data;
            } else {
                return $_this->updateAndMessage($deposit, 3, 'Unknown Failed', $verifyResponse->msg);
            }
        }
    }


}
PK     x\^      Services/BasicService.phpnu [        <?php

namespace App\Services;

use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\Transaction;
use App\Traits\MakeOrder;
use App\Traits\Notify;

class BasicService
{
    use Notify, MakeOrder;

    public function setEnv($value)
    {
        $envPath = base_path('.env');
        $env = file($envPath);
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            $env[$env_key] = array_key_exists($entry[0], $value) ? $entry[0] . "=" . $value[$entry[0]] . "\n" : $env_value;
        }
        $fp = fopen($envPath, 'w');
        fwrite($fp, implode($env));
        fclose($fp);
    }

    public function preparePaymentUpgradation($deposit): void
    {
        try {
            if ($deposit->status == 0 || $deposit->status == 2) {
                $deposit->status = 1;
                $deposit->save();

                if ($deposit->depositable_type == Order::class) {
                    $order = $deposit->depositable;
                    if ($order) {
                        $this->orderCompleteAction($order, $deposit);
                    }
                } elseif (!$deposit->depositable_type) {
                    $user = $deposit->user;
                    $user->balance += $deposit->amount_in_base;
                    $user->save();

                    $this->makeTransaction($user->id, $deposit->amount_in_base, '+', $deposit->trx_id, 'Add Fund Via ' . $deposit->gateway?->name, $deposit->id, Deposit::class);
                    $this->notifyToAll($deposit);
                }
            }
        } catch (\Exception $e) {

        }
    }

    public function makeTransaction($userId, $amount, $trxType, $trxId, $remark, $transactionalId = null, $transactionalType = null, $charge_in_base_currency = null)
    {
        $transaction = new Transaction();
        $transaction->user_id = $userId;
        $transaction->amount_in_base = $amount;
        $transaction->trx_type = $trxType;
        $transaction->remarks = $remark;
        $transaction->transactional_id = $transactionalId;
        $transaction->transactional_type = $transactionalType;
        $transaction->save();
    }

    public function preparePayoutComplete($payout): void
    {
        if ($payout->status == 1) {
            $payout->status = 2;
            $payout->save();
            $this->userPayoutNotify($payout);
        }
    }

    public function preparePayoutFail($payout)
    {
        if ($payout->status == 1) {
            $payout->status = 3;
            $payout->save();

            updateBalance($payout->user_id, $payout->net_amount_in_base_currency, 1);

            $this->makeTransaction($payout->user_id, $payout->net_amount_in_base_currency, '+',
                $payout->trx_id, 'Payout Amount Refunded', $payout->id, Payout::class);

            $receivedUser = $payout->user;
            $params = [
                'amount' => getAmount($payout->amount),
                'currency' => $payout->payout_currency_code,
                'transaction' => $payout->trx_id,
            ];

            $action = [
                "link" => "#",
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $firebaseAction = "#";
            $this->sendMailSms($receivedUser, 'PAYOUT_CANCEL', $params);
            $this->userPushNotification($receivedUser, 'PAYOUT_CANCEL', $params, $action);
            $this->userFirebasePushNotification($receivedUser, 'PAYOUT_CANCEL', $params, $firebaseAction);
        }
    }

    public function userPayoutNotify($payout):void
    {
        try {
            $msg = [
                'amount' => getAmount($payout->amount),
                'currency' => $payout->payout_currency_code,
                'transaction' => $payout->trx_id,
            ];
            $action = [
                "link" => '#',
                "icon" => "fas fa-money-bill-alt text-white"
            ];
            $fireBaseAction = "#";
            $this->userPushNotification($payout->user, 'PAYOUT_APPROVED', $msg, $action);
            $this->userFirebasePushNotification('PAYOUT_APPROVED', $msg, $fireBaseAction);
            $this->sendMailSms($payout->user, 'PAYOUT_APPROVED', $msg);
        }catch (\Exception $e){

        }
    }

    public function cryptoQR($wallet, $amount, $crypto = null)
    {
        $varb = $wallet . "?amount=" . $amount;
        return "https://quickchart.io/chart?cht=qr&chs=150x150&chl=$varb";
//        return "https://quickchart.io/chart?cht=qr&chl=$cryptoQr";
    }
}
PK     x\:	  	  ,  Services/Translate/AzureTranslateService.phpnu [        <?php

namespace App\Services\Translate;
use Illuminate\Support\Facades\Http;


Class AzureTranslateService {


    public function allKeywordTranslate($shortName)
    {

        $azureCredential = config('translateconfig.translate_method.azure');
        $endpoint = $azureCredential['end_point_url']['value'];
        $subscriptionKey = $azureCredential['subscription_key']['value'];
        $url = $endpoint."translator/text/v3.0/translate?from=en&to=$shortName";

        $path = resource_path("lang/$shortName.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }


        $textToTranslate = array_keys($contents);

        $requestData = [];
        foreach ($textToTranslate as $text) {
            $requestData[] = ['text' => $text];
        }

        $response = Http::withHeaders([
            'Ocp-Apim-Subscription-Key' => $subscriptionKey,
            'Ocp-Apim-Subscription-Region' => $azureCredential['subscription_region']['value'],
            'Content-type' => 'application/json',
        ])->post($url, $requestData);

        $translatedData = $response->json();


        $translatedText = [];
        foreach ($translatedData as $index => $translation) {
            $translatedText[$textToTranslate[$index]] = $translation['translations'][0]['text'];
        }

        return $translatedText;

    }

    public function singleKeywordTranslate($shortName, $key)
    {

        $azureCredential = config('translateconfig.translate_method.azure');
        $endpoint = $azureCredential['end_point_url']['value'];
        $subscriptionKey = $azureCredential['subscription_key']['value'];
        $url = $endpoint."translator/text/v3.0/translate?from=en&to=$shortName";

        $path = resource_path("lang/$shortName.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }

        $text = $key;
        $requestData[] = ['text' => $text];;

        $response = Http::withHeaders([
            'Ocp-Apim-Subscription-Key' => $subscriptionKey,
            'Ocp-Apim-Subscription-Region' => $azureCredential['subscription_region']['value'],
            'Content-type' => 'application/json',
        ])->post($url, $requestData);

        $translatedData = $response->json();
        foreach ($translatedData as $index => $translation) {
            $translatedText = $translation['translations'][0]['text'];
        }

        return $translatedText;

    }

}
PK     x\    +  Services/Translate/BaseTranslateService.phpnu [        <?php

namespace App\Services\Translate;

Class BaseTranslateService {
    public function textTranslate($shortName)
    {

        $translateObj = 'Facades\\App\\Services\\Translate\\' . ucfirst(config('translateconfig.default')) . 'TranslateService';
        $textTranslated = $translateObj::allKeywordTranslate($shortName);

        return $textTranslated;

    }

    public function singleKeywordTranslated($shortName, $key)
    {
        $translateObj = 'Facades\\App\\Services\\Translate\\' . ucfirst(config('translateconfig.default')) . 'TranslateService';
        $singleKeywordTranslated = $translateObj::singleKeywordTranslate($shortName, $key);

        return $singleKeywordTranslated;
    }
}
PK     x\^    -  Services/Translate/GoogleTranslateService.phpnu [        <?php

namespace App\Services\Translate;

use Google\Cloud\Translate\V2\TranslateClient;

class GoogleTranslateService
{

    protected $translate;

    public function __construct()
    {
        $projectId = env("PROJECT_ID"); //main-cedar-391910
        $keyFilePath = base_path('main-cedar-391910-cd7c5ebfdd8b.json');
        $this->translate = new TranslateClient([
            'projectId' => $projectId,
            'keyFilePath' => $keyFilePath,
        ]);
    }

    public function allKeywordTranslate($shortName)
    {
        $path = resource_path("lang/$shortName.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }

        $textToTranslate = array_keys($contents);
        $translatedValue = [];
        foreach ($textToTranslate as $key => $text) {
            $translatedValue[] = $text;
        }

        try {
            $this->translate->translateBatch($translatedValue, [
                'target' => 'en',
            ]);

            return $translatedValue;
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function editKeywordTranslate($shortName, $key)
    {
        $path = resource_path("lang/$shortName.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }
        try {
            $text = $key;
            $translation = $this->translate->translate($text, [
                'target' => $shortName,
            ]);

            return $translation['text'];
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

}
PK     x\d赈T  T    Services/BasicCurl.phpnu [        <?php

namespace App\Services;

class BasicCurl
{
    public function curlPostRequestWithHeaders($url, $headers, $postParam = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParam));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function curlPostRequestWithHeadersJson($url, $headers, $postParam)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParam));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function curlGetRequest($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function curlGetRequestWithHeaders($url, $headers)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function curlPostRequestWithHeadersNew($url, $headers, $postParam = [])
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, '');
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 0);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParam));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function razorpayCurlPostRequestWithHeaders($url, $postParam = [], $KEY_ID, $KEY_SECRET)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postParam));
        curl_setopt($ch, CURLOPT_USERPWD, $KEY_ID . ':' . $KEY_SECRET);

        $headers = array();
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function payoutBinanceCurlRequestWithHeaders($url, $api_key, $request)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $request,
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'X-MBX-APIKEY: ' . $api_key
            ),
        ));
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function binanceCurlOrderRequest($url, $headers, $json_request)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_request);

        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}
PK     x\      Services/SMS/PlivoService.phpnu [        <?php

namespace App\Services\SMS;


use Plivo\Resources\PHLO\PhloRestClient;
use Plivo\Exceptions\PlivoRestException;

class PlivoService
{
    protected $client;
    protected $phlo;

    public function getConnection()
    {
        $this->client = new PhloRestClient(getenv('PLIVO_AUTH_ID'), getenv('PLIVO_AUTH_TOKEN'));
        $this->phlo = $this->client->phlo->get(getenv('PLIVO_ID'));
        return $this;
    }

    public function sendMessage($destination, $message)
    {
        try {
            $response = $this->phlo->run(["From" => "<sender_id>", "To" => "<destination_number>"]);
            dd($response);
        } catch (PlivoRestException $exception) {
            return ['error' => $exception->getMessage(), 'code' => $exception->getCode()];
        }

    }
}

PK     x\Pڤ      Services/SMS/TwilioService.phpnu [        <?php

namespace App\Services\SMS;


use Twilio\Exceptions\TwilioException;
use Twilio\Rest\Client;

class TwilioService
{
    protected $client;

    public function getConnection()
    {
        $this->client = new Client(getenv("TWILIO_ACCOUNT_SID"), getenv("TWILIO_AUTH_TOKEN"));
        return $this;
    }

    public function sendMessage($destination, $message)
    {
        try {
            $sid = env("TWILIO_ACCOUNT_SID");
            $token = env("TWILIO_AUTH_TOKEN");
            $twilio = new Client($sid, $token);

            $message = $twilio->messages
                ->create($destination, [
                    "body" => $message,
                    "from" => env("TWILIO_PHONE_NUMBER"),
                ]);
            return ['sid' => $message->sid];
        } catch (TwilioException $exception) {
            return ['error' => $exception->getMessage(), 'code' => $exception->getCode()];
        }
    }
}
PK     x\x6s  s    Services/SMS/VonageService.phpnu [        <?php

namespace App\Services\SMS;


use Exception;

class VonageService
{
    protected $client;
    protected $clientVerify;

    protected $requestID;

    public function getConnection()
    {
        $basic = new \Vonage\Client\Credentials\Basic(getenv('VONAGE_API_KEY'), getenv('VONAGE_API_SECRET'));
        $this->clientVerify = new \Vonage\Client(new \Vonage\Client\Credentials\Container($basic));
        $this->client = new \Vonage\Client($basic);
        return $this;

    }

    public function sendMessage($destination, $message)
    {
        try {
            $response = $this->client->sms()->send(
                new \Vonage\SMS\Message\SMS($destination, "Vonage APIs", $message)
            );

            $message = $response->current();

            if ($message->getStatus() == 0) {
                return "The message was sent successfully";
            } else {
                return "The message failed with status: " . $message->getStatus();
            }

        } catch (Exception $exception) {
            return ['error' => $exception->getMessage(), 'code' => $exception->getCode()];
        }

    }
}

PK     x\mH  H    Services/SMS/BaseSmsService.phpnu [        <?php

namespace App\Services\SMS;

class BaseSmsService
{
    public function sendSMS($destination, $message)
    {
        $smsObj = 'Facades\\App\\Services\\SMS\\' . ucfirst(config('SMSConfig.default')) . 'Service';
        $data = $smsObj::getConnection()->sendMessage($destination, $message);
        return $data;
    }
}
PK     x\e}G)  )    Services/SMS/InfobipService.phpnu [        <?php

namespace App\Services\SMS;

use Infobip\Api\TfaApi;
use Infobip\Api\SmsApi;
use Infobip\Configuration;
use Infobip\ApiException;
use Infobip\Model\SmsAdvancedTextualRequest;
use Infobip\Model\SmsDestination;
use Infobip\Model\SmsTextualMessage;

class InfobipService
{
    protected $sendSmsApi;
    protected $tfaApi;
    protected $pinId;

    public function getConnection()
    {
        $configuration = new Configuration(
            host: getenv('INFOBIP_URL_BASE_PATH'),
            apiKey: getenv('INFOBIP_API_KEY')
        );
        $this->sendSmsApi = new SmsApi(config: $configuration);
        $this->tfaApi = new TfaApi(config: $configuration);
        return $this;
    }

    public function sendMessage($destination, $message)
    {
        $message = new SmsTextualMessage(
            destinations: [
                new SmsDestination(to: $destination)
            ],
            from: 'InfoSMS',
            text: $message
        );

        $request = new SmsAdvancedTextualRequest(messages: [$message]);

        try {
            $smsResponse = $this->sendSmsApi->sendSmsMessage($request);
            return $smsResponse;
        } catch (ApiException $apiException) {
            return ['error' => $apiException->getMessage(), 'code' => $apiException->getCode()];
        }
    }

}

PK     x\		  	     Services/LocalizationService.phpnu [        <?php

namespace App\Services;

use Illuminate\Support\Facades\File;

class LocalizationService
{
    public function createLang($defaultShortName, $shortName)
    {
        $defaultPaths = [
            resource_path("lang/"),
            resource_path("lang/default/"),
        ];

        foreach ($defaultPaths as $path) {
            if (file_exists($path . "{$defaultShortName}.json")) {
                $data = file_get_contents($path . "{$defaultShortName}.json");
                $destination = $path . strtolower($shortName) . '.json';
                File::put($destination, $data);
            }
        }
        return $defaultPaths;
    }

    public function deleteLang($shortName)
    {
        $defaultPaths = [
            resource_path("lang/{$shortName}.json"),
            resource_path("lang/default/{$shortName}.json"),
        ];

        foreach ($defaultPaths as $path) {
            file_exists($path) ? @unlink($path) : false;
        }
        return $defaultPaths;
    }

    public function renameLang($oldShortName, $newShortName)
    {
        $defaultPaths = [
            resource_path("lang/{$oldShortName}.json") => resource_path("lang/{$newShortName}.json"),
            resource_path("lang/default/{$oldShortName}.json") => resource_path("lang/default/{$newShortName}.json"),
        ];

        foreach ($defaultPaths as $key => $path) {
            file_exists($key) ? @rename($key, $path) : false;
        }
        return $defaultPaths;
    }

    public function deleteLangKeyword($shortName, $key)
    {
        $path = resource_path("lang/{$shortName}.json");

        if (file_exists($path)) {
            $contetns = json_decode(file_get_contents($path), true);
            unset($contetns[$key]);
            file_put_contents($path, stripslashes(json_encode($contetns, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)));
            return true;
        }
        return false;
    }

    public function updateLangKeyword($shortName, $key, $value, $default = false)
    {
        $path = $default ? resource_path("lang/default/{$shortName}.json") : resource_path("lang/{$shortName}.json");

        if (file_exists($path)) {
            $contetns = json_decode(file_get_contents($path), true);
            $contetns[$key] = $value;
            file_put_contents($path, stripslashes(json_encode($contetns, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)));
            return true;
        }
        return false;
    }
}
PK     x\zmD  D  !  Services/CurrencyLayerService.phpnu [        <?php

namespace App\Services;


use App\Models\PayoutMethod;
use Illuminate\Support\Facades\Http;
use Exception;

class CurrencyLayerService
{
    public function getCurrencyRate()
    {
        $endpoint = 'live';
        $source = basicControl()->base_currency;
        $currency_layer_url = "http://api.currencylayer.com";
        $currency_layer_access_key = basicControl()->currency_layer_access_key;

        $payoutCurrencies = PayoutMethod::where('is_automatic', 1)
            ->where('code', '!=', 'coinbase')
            ->where('is_auto_update', 1)
            ->pluck('supported_currency')->toArray();


        $currencyLists = array();
        foreach ($payoutCurrencies as $currency) {
            foreach ($currency as $singleCurrency) {
                $currencyLists[] = $singleCurrency;
            }
        }

        $currencyLists = array_unique($currencyLists);


        $currencies = implode(',', $currencyLists);
        $CurrencyAPIUrl = "$currency_layer_url/$endpoint?access_key=$currency_layer_access_key&source=$source&currencies=$currencies";

        $response = Http::acceptJson()
            ->get($CurrencyAPIUrl);

        if ($response->status() == 200)
            return json_decode($response->body());

        throw new Exception("Something went wrong while fetching user's data from Envato.");
    }

}
PK     x\/o  o  *  Services/Google/GoogleRecaptchaService.phpnu [        <?php

namespace App\Services\Google;

use Illuminate\Support\Facades\Http;

class GoogleRecaptchaService
{

    public function responseRecaptcha($response)
    {
        try {
            $response = Http::asForm()->post(env("GOOGLE_RECAPTCHA_SITE_VERIFY_URL"), [
                'secret' => env('GOOGLE_RECAPTCHA_SECRET_KEY'),
                'response' => $response,
            ]);

            $result = $response->json();

            if ($result['success']) {
                return true;
            }
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     x\              Imports/index.phpnu [        PK     x\Qx3      Imports/TopUpServiceImport.phpnu [        <?php

namespace App\Imports;

use App\Models\TopUpService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Concerns\ToCollection;

class TopUpServiceImport implements ToCollection
{
    private $topUpId;

    public function __construct($topUpId)
    {
        $this->topUpId = $topUpId;
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        foreach ($collection as $key => $value) {
            try {
                if ($key != 0) {
                    TopUpService::firstOrCreate(
                        [
                            'top_up_id' => $this->topUpId,
                            'name' => $value[0],
                        ],
                        [
                            'price' => $value[1],
                            'discount' => $value[2],
                            'discount_type' => $value[3],
                            'status' => $value[4],
                        ]
                    );
                }
            } catch (\Exception  $e) {
                continue;
            }
        }
        return true;
    }
}
PK     x\Vvx      Imports/CodeImport.phpnu [        <?php

namespace App\Imports;

use App\Models\Code;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CodeImport implements ToCollection
{
    private $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        foreach ($collection as $key => $value) {
            try {
                if ($key != 0) {
                    Code::firstOrCreate(
                        [
                            'codeable_type' => $this->data['codeable_type'],
                            'codeable_id' => $this->data['codeable_id'],
                            'passcode' => $value[0],
                        ],
                        [
                            'status' => $value[1],
                        ]
                    );
                }
            } catch (\Exception  $e) {
                continue;
            }
        }
        return true;
    }
}
PK     x\t&w  w    Imports/CardServiceImport.phpnu [        <?php

namespace App\Imports;

use App\Models\CardService;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

class CardServiceImport implements ToCollection
{
    private $cardId;

    public function __construct($cardId)
    {
        $this->cardId = $cardId;
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $collection)
    {
        foreach ($collection as $key => $value) {
            try {
                if ($key != 0) {
                    CardService::firstOrCreate(
                        [
                            'card_id' => $this->cardId,
                            'name' => $value[0],
                        ],
                        [
                            'price' => $value[1],
                            'discount' => $value[2],
                            'discount_type' => $value[3],
                            'status' => $value[4],
                        ]
                    );
                }
            } catch (\Exception  $e) {
                continue;
            }
        }
        return true;
    }
}
PK     x\q	q  q    Traits/ContentDelete.phpnu [        <?php

namespace App\Traits;


trait ContentDelete
{
    public static function booted()
    {
        static::deleting(function ($model) {
            if (isset($model->contentMedia->description->image)) {
				file_exists(config('location.content.path') . '/' . $model->contentMedia->description->image) && is_file(config('location.content.path') . '/' . $model->contentMedia->description->image) ? @unlink(config('location.content.path') . '/' . $model->contentMedia->description->image) : '';
            };
            $model->contentMedia()->delete();
            $model->contentDetails()->delete();
        });
    }
}
PK     x\$  $    Traits/MakeOrder.phpnu [        <?php


namespace App\Traits;

use App\Jobs\CodeSendBuyer;
use App\Jobs\UserTrackingJob;
use App\Models\Campaign;
use App\Models\Collection;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Models\Transaction;
use Carbon\Carbon;
use http\Env\Response;

trait MakeOrder
{
    use Notify;

    public function orderCreate($totalAmount, $orderFor, $info = null, $orderInterface = 'WEB', $user = null)
    {
        $order = Order::create([
            'user_id' => ($orderInterface == 'API') ? $user->id : auth()->id(),
            'amount' => $totalAmount,
            'info' => $info,
            'payment_status' => 0,
            'status' => 0,
            'order_for' => $orderFor,
            'utr' => 'O' . strRandom(),
            'order_interface' => $orderInterface,
        ]);

        return $order;
    }

    public function orderDetailsCreate($order, $services, $model, $quantities = []): void
    {
        if (!$services instanceof \Illuminate\Support\Collection) {
            $services = collect([$services]);
        }
        $orderDetails = [];
        foreach ($services as $key => $service) {
            $orderDetails[] = [
                'user_id' => $order->user_id,
                'order_id' => $order->id,
                'parent_id' => $model == TopUpService::class ? $service->top_up_id : $service->card_id,
                'detailable_type' => $model,
                'detailable_id' => $service->id,
                'name' => $service->name,
                'image' => $service->image,
                'image_driver' => $service->image_driver,
                'price' => $service->price,
                'discount' => $service->getDiscount(),
                'qty' => isset($order->order_interface) && $order->order_interface === 'API'
                    ? ($quantities[$key] ?? 1)
                    : ($quantities[$service->id] ?? 1),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
        }
        OrderDetail::insert($orderDetails);
    }

    public function depositCreate($checkAmountValidate, $depositableType = null, $depositableId = null)
    {
        $deposit = Deposit::create([
            'user_id' => auth()->id(),
            'payment_method_id' => $checkAmountValidate['gateway_id'],
            'payment_method_currency' => $checkAmountValidate['currency'],
            'amount' => $checkAmountValidate['amount'],
            'amount_in_base' => $checkAmountValidate['payable_amount_baseCurrency'],
            'percentage_charge' => $checkAmountValidate['percentage_charge'],
            'fixed_charge' => $checkAmountValidate['fixed_charge'],
            'charge' => $checkAmountValidate['charge'],
            'payable_amount' => $checkAmountValidate['payable_amount'],
            'status' => 0,
            'depositable_type' => $depositableType,
            'depositable_id' => $depositableId,
        ]);

        return $deposit;
    }

    public function orderCompleteAction($order, $deposit): void
    {
        $order->payment_status = 1;
        $order->payment_method_id = $deposit->payment_method_id;
        $order->save();

        $this->increaseCampaignSell($order);

        if ($order->coupon_id) {
            $coupon = $order->coupon;
            $coupon->total_use += 1;
            $coupon->save();
        }

        $this->newTransaction($order->user_id, $order->amount, $this->getRemark($order), '-', $order->id, Order::class);
        $this->notifyToAll($deposit);

        if ($order->order_for == 'card') {
            dispatch(new CodeSendBuyer($order));
        }

        UserTrackingJob::dispatch($order->user_id, request()->ip(), $this->getRemark($order));
    }

    public function increaseCampaignSell($order): void
    {
        $oderDetails = $order->orderDetails;
        if (!empty($oderDetails)) {
            foreach ($oderDetails as $detail) {
                $service = $detail->detailable;

                $campaign = Campaign::firstOrNew();
                if ($service->is_offered && $campaign->status && $campaign->start_date <= Carbon::now() &&
                    $campaign->end_date >= Carbon::now()) {
                    $service->offered_sell += 1;
                    $service->save();
                }
            }
        }
    }

    public function newTransaction($userId, $amount, $remark, $trxType = '+', $transactionalId = null, $transactionalType = null): void
    {
        $transaction = new Transaction();
        $transaction->transactional_id = $transactionalId;
        $transaction->transactional_type = $transactionalType;
        $transaction->user_id = $userId;
        $transaction->amount_in_base = $amount;
        $transaction->trx_type = $trxType;
        $transaction->trx_id = strRandom();
        $transaction->remarks = $remark;
        $transaction->save();
    }

    public function notifyToAll($deposit): void
    {
        $basicControl = basicControl();
        try {
            $params = [
                'amount' => getAmount($deposit->amount_in_base, $basicControl->fraction_number),
                'currency' => $basicControl->currency_symbol,
                'gateway' => $deposit->gateway?->name ?? 'Wallet',
                'transaction' => $deposit->trx_id,
            ];

            $action = [
                "link" => route('user.fund.index'),
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($deposit->user, 'BUYER_PAYMENT', $params);
            $this->userPushNotification($deposit->user, 'BUYER_PAYMENT', $params, $action);
            $this->userFirebasePushNotification($deposit->user, 'BUYER_PAYMENT', $params);

            $adminParams = [
                'username' => optional($deposit->user)->username ?? null,
                'amount' => getAmount($deposit->amount_in_base, $basicControl->fraction_number),
                'currency' => $basicControl->currency_symbol,
                'gateway' => $deposit->gateway->name ?? null,
                'transaction' => $deposit->trx_id,
            ];

            $adminAction = [
                "name" => optional($deposit->user)->firstname . ' ' . optional($deposit->user)->lastname,
                "image" => getFile(optional($deposit->user)->image_driver, optional($deposit->user)->image),
                "link" => route('admin.payment.log'),
                "icon" => "fas fa-ticket-alt text-white"
            ];

            $this->adminMail('BUYER_PAYMENT_ADMIN', $adminParams);
            $this->adminPushNotification('BUYER_PAYMENT_ADMIN', $adminParams, $adminAction);
            $this->adminFirebasePushNotification('BUYER_PAYMENT_ADMIN', $adminAction);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    public function getRemark($order)
    {
        $paymentMethod = $this->getPaymentMethod($order);

        switch ($order->order_for) {
            case 'topup':
                return $this->generateRemark('Direct Top Up', $paymentMethod);
            case 'card':
                return $this->generateRemark('Card', $paymentMethod);
            default:
                return 'Unknown order type';
        }
    }

    protected function getPaymentMethod($order)
    {
        return $order->payment_method_id == '-1' ? 'Wallet' : $order->gateway?->name;
    }

    protected function generateRemark($orderType, $paymentMethod)
    {
        return "Payment For $orderType Via $paymentMethod";
    }

    public function payByWallet($order, $user = null)
    {

        try {
            if (!$user) {
                $user = $order->user()->select(['id', 'firstname', 'lastname', 'balance'])->first();
            }
            if (!$user) {
                return [
                    'status' => false,
                    'message' => 'User not found',
                ];
            }
            if ($user->balance < $order->amount) {
                return [
                    'status' => false,
                    'message' => 'You have sufficient balance to order',
                ];
            }

            $user->balance -= $order->amount;
            $user->save();

            $deposit = new Deposit();
            $deposit->user_id = $user->id;
            $deposit->payment_method_id = -1;
            $deposit->payment_method_currency = basicControl()->base_currency;
            $deposit->amount = $order->amount;
            $deposit->amount_in_base = $order->amount;
            $deposit->percentage_charge = 0;
            $deposit->fixed_charge = 0;
            $deposit->charge = 0;
            $deposit->payable_amount = $order->amount;
            $deposit->trx_id = strRandom();
            $deposit->status = 0;
            $deposit->depositable_type = null;
            $deposit->depositable_id = null;

            $this->orderCompleteAction($order, $deposit);

            return [
                'status' => true
            ];
        } catch (\Exception $e) {
            return [
                'status' => false,
                'message' => $e->getMessage(),
            ];
        }
    }
}
PK     x\I_0  0    Traits/Bkash.phpnu [        <?php

namespace App\Traits;

use Exception;
use Illuminate\Support\Facades\Http;

trait Bkash
{
    protected function getBaseURL($mode = "test")
    {
        return $mode == 'test' ? "https://tokenized.sandbox.bka.sh/v1.2.0-beta/tokenized/checkout" : "https://tokenized.pay.bka.sh/v1.2.0-beta/tokenized/checkout";
    }

    protected function sentHttpRequestToBkash($token, $appKey, $uri, $data)
    {
        return Http::withHeaders([
            'Content-Type' => 'application/json',
            'Authorization' => $token,
            'X-APP-Key' => $appKey,
        ])
            ->acceptJson()
            ->post($uri, $data);
    }

    protected function getToken($gateway)
    {
        throw_if(empty($gateway->parameters->username ?? "") || empty($gateway->parameters->password ?? "") || empty($gateway->parameters->app_key ?? "") || empty($gateway->parameters->app_secret ?? ""), "Unable to process with bKash.");

        $uri = $this->getBaseURL($gateway->environment) . "/token/grant";
        $data = [
            'app_key' => $gateway->parameters->app_key,
            'app_secret' => $gateway->parameters->app_secret,
        ];

        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'username' => $gateway->parameters->username,
            'password' => $gateway->parameters->password,
        ])
            ->acceptJson()
            ->post($uri, $data);

        if ($response->status() == 200) {
            $bkashResponse = json_decode($response->body());
            throw_if(!isset($bkashResponse->id_token), "Something went wrong while trying to pay with bKash.");

            $token = $bkashResponse->id_token;
            return $token;
        }
        throw new Exception("Something went wrong while trying to pay with bKash.");
    }

    public function executePayment($paymentID, $gateway)
    {
        throw_if(empty($gateway->parameters->app_key ?? "") || empty($gateway->parameters->app_secret ?? ""), "Unable to process with bKash.");
        $token = $this->getToken($gateway);
        $uri = $this->getBaseURL($gateway->environment) . "/execute";
        $data = array(
            'paymentID' => $paymentID
        );
        $response = $this->sentHttpRequestToBkash($token, $gateway->parameters->app_key, $uri, $data);

        if ($response->status() == 200) {
            $bkashResponse = json_decode($response->body());
            return $bkashResponse;
        }
        throw new Exception("Something went wrong while trying to verify your payment with bKash.");
    }

    public function queryPayment($paymentID, $gateway)
    {
        throw_if(empty($gateway->parameters->app_key ?? "") || empty($gateway->parameters->app_secret ?? ""), "Unable to process with bKash.");
        $token = $this->getToken($gateway);
        $uri = $this->getBaseURL($gateway->environment) . "/payment/status";
        $data = array(
            'paymentID' => $paymentID
        );
        $response = $this->sentHttpRequestToBkash($token, $gateway->parameters->app_key, $uri, $data);
        if ($response->status() == 200) {
            $bkashResponse = json_decode($response->body());
            return $bkashResponse;
        }
        throw new Exception("Something went wrong while trying to verify your payment with bKash.");
    }

    public function updateAndMessage($deposit, $note, $msg)
    {
        $deposit->update([
            'status' => 3,
            'note' => $note
        ]);
        $data['status'] = 'error';
        $data['msg'] = $msg;
        $data['redirect'] = route('failed');
        return $data;
    }
}
PK     x\&        Traits/Frontend.phpnu [        <?php

namespace App\Traits;

use App\Models\Blog;
use App\Models\Campaign;
use App\Models\Card;
use App\Models\CardService;
use App\Models\ContentDetails;
use App\Models\SellPostCategory;
use App\Models\TopUp;
use App\Models\TopUpService;

trait Frontend
{
    protected function getSectionsData($sections, $content, $selectedTheme)
    {
        if ($sections == null) {
            $data = ['support' => $content,];
            return view("themes.$selectedTheme.support", $data)->toHtml();
        }

        $contentData = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($sections) {
                $query->whereIn('name', $sections);
            })
            ->get();

        foreach ($sections as $section) {

            $singleContent = $contentData->where('content.name', $section)->where('content.type', 'single')->first() ?? [];
            $multipleContents = $contentData->where('content.name', $section)->where('content.type', 'multiple')->values()->map(function ($multipleContentData) {
                return collect($multipleContentData->description)->merge($multipleContentData->content->only('media'));
            });
            $data[$section] = [
                'single' => $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [],
                'multiple' => $multipleContents
            ];

            $data[$selectedTheme . '_hero'] = $this->getHero($section, $singleContent, $multipleContents, $selectedTheme);
            $data[$selectedTheme . '_exclusive_card'] = $this->getExclusiveCard($section, $singleContent, $multipleContents, $selectedTheme);
            $data[$selectedTheme . '_campaign'] = $this->getCampaign($section, $selectedTheme, $singleContent);
            $data[$selectedTheme . '_top_up'] = $this->getTrendingTopUpServices($section, $selectedTheme, $singleContent, $multipleContents);
            $data[$selectedTheme . '_blog'] = $this->getBlog($section, $selectedTheme, $singleContent);
            $data[$selectedTheme . '_trending_item'] = $this->getCards($section, $selectedTheme, $singleContent, $multipleContents);
            $data[$selectedTheme . '_buy_game_id'] = $this->getGameCategory($section, $selectedTheme, $singleContent, $multipleContents);
            $replacement = view("themes.{$selectedTheme}.sections.{$section}", $data)->toHtml();

            $content = str_replace('<div class="custom-block" contenteditable="false"><div class="custom-block-content">[[' . $section . ']]</div>', $replacement, $content);
            $content = str_replace('<span class="delete-block">×</span>', '', $content);
            $content = str_replace('<span class="up-block">↑</span>', '', $content);
            $content = str_replace('<span class="down-block">↓</span></div>', '', $content);
            $content = str_replace('<p><br></p>', '', $content);
        }

        return $content;
    }

    public function getCampaign($section, $selectedTheme, $singleContent)
    {
        if ($section == $selectedTheme . '_campaign') {
            $campaign = Campaign::firstOrNew();
            $trendingTopUpServices = TopUpService::has('topUp')->with(['topUp:id,slug,avg_rating,total_review,image'])
                ->where('status', 1)
                ->where('is_offered', 1)->orderBy('sort_by', 'ASC')->get();

            $trendingCardServices = CardService::has('card')->with(['card:id,slug,avg_rating,total_review,image'])
                ->where('status', 1)
                ->where('is_offered', 1)->orderBy('sort_by', 'ASC')->get();

            $trendingFirstItem = null;
            if ($section == 'light_campaign') {
                $trendingFirstItem = $trendingTopUpServices->first();
            }

            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            return [
                'campaign' => $campaign,
                'single' => $single,
                'trendingTopUpServices' => $trendingTopUpServices,
                'trendingCardServices' => $trendingCardServices,
                'trendingFirstItem' => $trendingFirstItem,
            ];
        }
    }

    public function getTrendingTopUpServices($section, $selectedTheme, $singleContent, $multipleContents)
    {
        if ($section == $selectedTheme . '_top_up') {
            $trendingItems = TopUp::where('status', 1)
                ->take(12)->orderBy('sort_by', 'ASC')->get();
            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = $multipleContents;

            return [
                'trendingItems' => $trendingItems,
                'single' => $single,
                'multiple' => $multiple,

            ];
        }
    }

    public function getCards($section, $selectedTheme, $singleContent, $multipleContents)
    {
        if ($section == $selectedTheme . '_trending_item') {
            $trendingItems = Card::with(['services'])
                ->where('status', 1)
                ->orderBy('sort_by', 'ASC')
                ->take(10)
                ->get();

            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = $multipleContents;

            return [
                'trendingItems' => $trendingItems,
                'single' => $single,
                'multiple' => $multiple
            ];
        }
    }

    public function getBlog($section, $selectedTheme, $singleContent)
    {
        if ($section == $selectedTheme . '_blog') {
            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = Blog::with(['details', 'category'])->take(3)->latest()->get();

            return [
                'single' => $single,
                'multiple' => $multiple
            ];
        }
    }

    public function getHero($section, $singleContent, $multipleContents, $selectedTheme)
    {
        if ($section == $selectedTheme . '_hero') {
            $trendingItems = CardService::has('card')
                ->with(['card:id,name,slug,avg_rating,total_review,trending'])
                ->whereHas('card', function ($query) {
                    $query->where('trending', 1);
                })
                ->take(10)
                ->where('status', 1)
                ->orderBy('sort_by', 'ASC')
                ->get();
            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = $multipleContents;

            return [
                'trendingItems' => $trendingItems,
                'single' => $single,
                'multiple' => $multiple
            ];
        }
    }

    public function getExclusiveCard($section, $singleContent, $multipleContents, $selectedTheme)
    {
        if ($section == $selectedTheme . '_exclusive_card') {
            $cards = Card::with(['services'])
                ->where('status', 1)
                ->where('trending', 1)
                ->orderBy('sort_by', 'ASC')
                ->take(12)
                ->get();
            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = $multipleContents;

            return [
                'cards' => $cards,
                'single' => $single,
                'multiple' => $multiple
            ];
        }
    }

    public function getGameCategory($section, $selectedTheme, $singleContent, $multipleContents)
    {
        if ($section == $selectedTheme . '_buy_game_id') {
            $gameCategory = SellPostCategory::with(['activePost', 'details'])->whereStatus(1)
                ->limit(6)->orderBy('id', 'desc')->get();

            $single = $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [];
            $multiple = $multipleContents;

            return [
                'single' => $single,
                'multiple' => $multiple,
                'gameCategory' => $gameCategory,
            ];
        }
    }
}
PK     x\2!eQ'  '  !  Traits/PaymentValidationCheck.phpnu [        <?php

namespace App\Traits;

use App\Models\Gateway;
use Mockery\Exception;

trait PaymentValidationCheck
{
    public function validationCheck($amount, $gateway, $currency, $cryptoCurrency = null, $isBase = 'no')
    {
        try {
            $selectGateway = Gateway::where('id', $gateway)->where('status', 1)->first();
            if (!$selectGateway) {
                return ['status' => false, 'message' => "Payment method not available for this transaction"];
            }

            $selectedCurrency = array_search($currency, $selectGateway->supported_currency);
            if ($selectedCurrency !== false) {
                $selectedPayCurrency = $selectGateway->supported_currency[$selectedCurrency];
            } else {
                return ['status' => false, 'message' => "Please choose the currency you'd like to use for payment"];
            }

            if ($selectGateway) {
                $receivableCurrencies = $selectGateway->receivable_currencies;
                if (is_array($receivableCurrencies)) {
                    if ($selectGateway->id < 999) {
                        $currencyInfo = collect($receivableCurrencies)->where('name', $selectedPayCurrency)->first();
                    } else {
                        $currencyInfo = collect($receivableCurrencies)->where('currency', $selectedPayCurrency)->first();
                    }
                } else {
                    return null;
                }
            }
            $currencyType = $selectGateway->currency_type;
            $limit = $currencyType == 0 ? 8 : 2;
            if ($isBase == 'yes') {
                $amount = getAmount($amount * $currencyInfo->conversion_rate, $limit);
            } else {
                $amount = getAmount($amount, $limit);
            }

            $payable_amount = $amount;
            $status = false;

            if ($currencyInfo) {
                $percentage = getAmount($currencyInfo->percentage_charge, $limit);
                $percentage_charge = getAmount(($payable_amount * $percentage) / 100, $limit);
                $fixed_charge = getAmount($currencyInfo->fixed_charge, $limit);

                $min_limit = getAmount($currencyInfo->min_limit, $limit);
                $max_limit = getAmount($currencyInfo->max_limit, $limit);
                $charge = getAmount($percentage_charge + $fixed_charge, $limit);
            }

            $basicControl = basicControl();
            $payable_amount_baseCurrency = getAmount($amount / $currencyInfo->conversion_rate, $limit);
            $charge_baseCurrency = getAmount($charge / $currencyInfo->conversion_rate, $limit);
            $payable_amount = getAmount($payable_amount + $charge, $limit);

            if ($payable_amount < $min_limit || $payable_amount > $max_limit) {
                if ($selectGateway->currency_type) {
                    $message = "Minimum payment $min_limit {$currencyInfo->currency_symbol} and maximum payment limit $max_limit {$currencyInfo->currency_symbol}";
                } else {
                    $message = "Minimum payment $min_limit USD and maximum payment limit $max_limit USD";
                }
            } elseif ($payable_amount < 0) {
                $message = "Unprocessable Amount";
            } else {
                $status = true;
                $message = "Amount : $payable_amount_baseCurrency" . " " . $basicControl->base_currency;
            }

            $data['status'] = $status;
            $data['message'] = $message;
            $data['gateway_id'] = $selectGateway->id;
            $data['gateway_name'] = $selectGateway->name;
            $data['fixed_charge'] = $fixed_charge;
            $data['percentage'] = $percentage;
            $data['percentage_charge'] = $percentage_charge;
            $data['min_limit'] = $min_limit;
            $data['max_limit'] = $max_limit;
            $data['payable_amount'] = $payable_amount;
            $data['charge'] = $charge;
            $data['amount'] = $amount;
            $data['conversion_rate'] = $currencyInfo->conversion_rate ?? 1;
            $data['payable_amount_baseCurrency'] = $payable_amount_baseCurrency;
            $data['charge_baseCurrency'] = $charge_baseCurrency;
            $data['currency'] = $selectGateway->currency_type ? ($currencyInfo->name ?? $currencyInfo->currency) : 'USD';
            $data['base_currency'] = $basicControl->base_currency;
            $data['currency_limit'] = $limit;
            $data['payment_crypto_currency'] = $selectGateway->currency_type ? null : ($currencyInfo->name ?? $currencyInfo->currency);

            return $data;

        } catch (Exception $e) {
            return [
                'status' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}
PK     x\n5
  
    Traits/Upload.phpnu [        <?php

namespace App\Traits;

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

trait Upload
{
    public function makeDirectory($path)
    {
        if (file_exists($path)) return true;
        return mkdir($path, 0755, true);
    }

    public function removeFile($path)
    {
        return file_exists($path) && is_file($path) ? @unlink($path) : false;
    }

    public function fileUpload($file, $location, $fileName = null, $size = null, $encodedFormat = null, $encodedQuality = 90, $oldFileName = null, $oldDriver = 'local')
    {
        $activeDisk = config('filesystems.default');

        if (!empty($oldFileName) && Storage::disk($oldDriver)->exists($oldFileName))
            Storage::disk($oldDriver)->delete($oldFileName);

        if (!is_string($file)) {
            $file = new File($file);
            if (str_starts_with($file->getMimeType(), 'image/')) {
                $path = $this->makeImage($activeDisk, $file, $location, $size, $encodedFormat, $encodedQuality, $file->extension());
            } else {
                $path = Storage::disk($activeDisk)->putFileAs($location, $file, $fileName ?? $file->hashName());
            }
        } else {
            if ($this->isImageUrl($file)) {
                $path = $this->makeImage($activeDisk, $file, $location, $size, $encodedFormat, $encodedQuality, pathinfo($file, PATHINFO_FILENAME));
            } else {
                Storage::disk($activeDisk)->put($location, $file);
                $path = $location;
            }
        }

        return [
            'path' => $path,
            'driver' => $activeDisk,
        ];
    }

    protected function makeImage($activeDisk, $file, $location, $size, $encodedFormat, $encodedQuality, $fileExtension)
    {
        $image = Image::make($file);
        if (!empty($size)) {
            $size = explode('x', strtolower($size));
            $image->resize($size[0], $size[1]);
        }

        $path = $location . '/' . Str::random(30) . '.' . $encodedFormat ?? $fileExtension;

        Storage::disk($activeDisk)->put($path, !empty($encodedFormat) ? $image->encode($encodedFormat, $encodedQuality) : $image->encode());
        return $path;
    }

    protected function isImageUrl($url)
    {
        $imageInfo = @getimagesize($url);
        if ($imageInfo != false && str_starts_with($imageInfo['mime'], 'image/'))
            return true;

        return false;
    }

    public function fileDelete($driver = 'local', $old)
    {
        if (!empty($old)) {
            if (Storage::disk($driver)->exists($old)) {
                Storage::disk($driver)->delete($old);
            }
        }
        return 0;
    }
}

PK     x\e#K)  )    Traits/ApiPayment.phpnu [        <?php

namespace App\Traits;

use App\Http\Controllers\PaymentController;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Models\GiftCardSell;
use App\Models\SellPostOffer;
use App\Models\SellPostPayment;
use App\Models\TopUpSell;
use App\Models\VoucherSell;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Facades\App\Services\BasicService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

trait ApiPayment
{
    use ApiValidation, Notify, PaymentValidationCheck;


    public function proposalCheck($user, $sellPost): void
    {
        $sellPost->payment_status = 1;
        $sellPost->lock_for = $user->id;
        $sellPost->save();

        $checkMyProposal = SellPostOffer::where([
            'user_id' => $user->id,
            'sell_post_id' => $sellPost->id,
            'status' => 1,
            'payment_status' => 0,
        ])->first();
        if ($checkMyProposal) {
            $checkMyProposal->payment_status = 1;
            $checkMyProposal->save();
        }

        SellPostOffer::where('user_id', '!=', $user->id)->where('sell_post_id', $sellPost->id)->get()->map(function ($item) {
            $item->uuid = null;
            $item->save();
        });
    }

    public function codeSend($object, $type = 'voucher'): void
    {
        $lackingCode = 0;
        $qty = $object->qty;
        if ($type == 'voucher') {
            $vCodes = $object->service->voucherActiveCodes->take($qty);
        } else {
            $vCodes = $object->service->giftCardActiveCodes->take($qty);
        }
        if ($qty > count($vCodes)) {
            $lackingCode = $qty - count($vCodes);
        }
        $orderCode = [];
        $i = 0;

        foreach ($vCodes as $vCode) {
            if ($i < $qty) {
                array_push($orderCode, $vCode->code);
                $vCode->status = 2;
                $vCode->save();
            }
            $i++;
        }

        $object->stock_short = $lackingCode;
        $object->code = $orderCode;
        $object->status = 1;
        $object->save();
    }

    public function paymentDone(Request $request)
    {
        $rules = [
            'id' => 'required',
        ];
        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $deposit = Deposit::latest()->where('id', $request->id)->orWhere('trx_id', $request->id)->where('status', 0)->first();
        if (!$deposit) {
            return response()->json($this->withErrors('Record not found'));
        }

        BasicService::preparePaymentUpgradation($deposit);
        return response()->json($this->withSuccess('Payment has been completed'));
    }

    public function cardPayment(Request $request)
    {
        $rules = [
            'id' => 'required',
            'card_number' => 'required',
            'card_name' => 'required',
            'expiry_month' => 'required',
            'expiry_year' => 'required',
            'card_cvc' => 'required',
        ];
        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $deposit = Deposit::latest()->where('trx_id', $request->id)->orWhere('id', $request->id)->where('status', 0)->first();
        if (!$deposit) {
            return response()->json($this->withErrors('Record not found'));
        }

        $getwayObj = 'App\\Services\\Gateway\\' . $deposit->gateway->code . '\\Payment';
        if (!method_exists($getwayObj, 'mobileIpn')) {
            return response()->json($this->withErrors("Method mobileIpn does not exist in $getwayObj"));
        }

        $data = $getwayObj::mobileIpn($request, $deposit->gateway, $deposit);

        if ($data == 'success') {
            return response()->json($this->withSuccess('Payment has been complete'));
        } else {
            return response()->json($this->withErrors('unsuccessful transaction.'));
        }
    }

    public function showOtherPayment(Request $request)
    {
        $rules = [
            'id' => 'required',
        ];
        $validate = Validator::make($request->all(), $rules);

        if ($validate->fails()) {
            return response()->json($this->withErrors(collect($validate->errors())->collapse()));
        }

        $deposit = Deposit::latest()->where('trx_id', $request->id)->orWhere('id', $request->id)->where('status', 0)->first();
        if (!$deposit) {
            return response()->json($this->withErrors('Record not found'));
        }

        $val['url'] = route('paymentView', $deposit->id);
        return response()->json($this->withSuccess($val));
    }

    public function paymentView($depositId)
    {
        $deposit = Deposit::latest()->find($depositId);
        try {
            if ($deposit) {
                $getwayObj = 'App\\Services\\Gateway\\' . $deposit->gateway->code . '\\Payment';
                $data = $getwayObj::prepareData($deposit, $deposit->gateway);
                $data = json_decode($data);

                if (isset($data->error)) {
                    $result['status'] = false;
                    $result['message'] = $data->message;
                    return response($result, 200);
                }

                if (isset($data->redirect)) {
                    return redirect($data->redirect_url);
                }

                if ($data->view) {
                    $parts = explode(".", $data->view);
                    $desiredValue = end($parts);
                    $newView = 'mobile-payment.' . $desiredValue;
                    return view($newView, compact('data', 'deposit'));
                }

                abort(404);
            }
        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }

    public function manualPaymentSubmit(Request $request)
    {
        $validator = validator()->make($request->all(), [
            'id' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->withErrors(collect($validator->messages())->collapse());
        }

        $deposit = Deposit::latest()->where('trx_id', $request->id)->orWhere('id', $request->id)->where('status', 0)->first();
        if (!$deposit) {
            return response()->json($this->withErrors('Record not found'));
        }

        try {
            $params = optional($deposit->gateway)->parameters;
            $reqData = $request->except('_token', '_method');
            $rules = [];
            if ($params !== null) {
                foreach ($params as $key => $cus) {
                    $rules[$key] = [$cus->validation == 'required' ? $cus->validation : 'nullable'];
                    if ($cus->type === 'file') {
                        $rules[$key][] = 'image';
                        $rules[$key][] = 'mimes:jpeg,jpg,png';
                        $rules[$key][] = 'max:100240';
                    } elseif ($cus->type === 'text') {
                        $rules[$key][] = 'max:191';
                    } elseif ($cus->type === 'number') {
                        $rules[$key][] = 'integer';
                    } elseif ($cus->type === 'textarea') {
                        $rules[$key][] = 'min:3';
                        $rules[$key][] = 'max:300';
                    }
                }
            }

            $validator = Validator::make($reqData, $rules);
            if ($validator->fails()) {
                return response()->json($this->withErrors(collect($validator->errors())->collapse()));
            }

            $reqField = [];
            if ($params != null) {
                foreach ($request->except('_token', '_method', 'type') as $k => $v) {
                    foreach ($params as $inKey => $inVal) {
                        if ($k == $inKey) {
                            if ($inVal->type == 'file' && $request->hasFile($inKey)) {
                                try {
                                    $file = $this->fileUpload($request[$inKey], config('filelocation.deposit.path'), config('filesystems.default'), null, 'webp', 80, null, 40);
                                    $reqField[$inKey] = [
                                        'field_name' => $inVal->field_name,
                                        'field_value' => $file['path'],
                                        'field_driver' => $file['driver'],
                                        'validation' => $inVal->validation,
                                        'type' => $inVal->type,
                                    ];
                                } catch (\Exception $exp) {
                                    return response()->json($this->withErrors('Could not upload your ' . $inKey));
                                }
                            } else {
                                $reqField[$inKey] = [
                                    'field_name' => $inVal->field_name,
                                    'validation' => $inVal->validation,
                                    'field_value' => $v,
                                    'type' => $inVal->type,
                                ];
                            }
                        }
                    }
                }
            }
            $deposit->update([
                'information' => $reqField,
                'created_at' => Carbon::now(),
                'status' => 2,
            ]);

            $msg = [
                'username' => optional($deposit->user)->username,
                'amount' => currencyPosition($deposit->payable_amount_in_base_currency),
                'gateway' => optional($deposit->gateway)->name
            ];
            $action = [
                "name" => optional($deposit->user)->firstname . ' ' . optional($deposit->user)->lastname,
                "image" => getFile(optional($deposit->user)->image_driver, optional($deposit->user)->image),
                "link" => route('admin.user.payment', $deposit->user_id),
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->adminPushNotification('PAYMENT_REQUEST', $msg, $action);
            $this->adminFirebasePushNotification('PAYMENT_REQUEST', $msg, $action);
            $this->adminMail('PAYMENT_REQUEST', $msg);

            return response()->json($this->withSuccess('You request has been taken.'));

        } catch (\Exception $e) {
            return response()->json($this->withErrors($e->getMessage()));
        }
    }
}
PK     x\G      Traits/Nagad.phpnu [        <?php

namespace App\Traits;

use Illuminate\Support\Facades\Http;

trait Nagad
{
    protected $PAYMENT_REF_ID;
    protected $CHALLANGE;


    protected function getBaseURL($mode = "test")
    {
        return $mode == 'test' ? "http://sandbox.mynagad.com:10080/remote-payment-gateway-1.0/api/dfs" : "https://api.mynagad.com/api/dfs/";
    }

    protected function headers()
    {
        return [
            "Content-Type" => "application/json",
            "X-KM-IP-V4" => request()->ip(),
            "X-KM-Api-Version" => "v-0.2.0",
            "X-KM-Client-Type" => "PC_WEB"
        ];
    }

    protected function generateRandomString($length = 40)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    protected function generateSensitiveData($merchantId, $trx_id): array
    {
        return [
            'merchantId' => $merchantId,
            'datetime' => now('Asia/Dhaka')->format('YmdHis'),
            'orderId' => $trx_id,
            'challenge' => $this->generateRandomString()
        ];
    }

    protected function generateSensitiveDataOrder($merchantId, $orderId, $amount, $charge): array
    {
        return [
            'merchantId' => $merchantId,
            'orderId' => $orderId,
            'currencyCode' => '050',        //050 = BDT
            'amount' => $amount,
            'charge' => $charge,
            'challenge' => $this->CHALLANGE
        ];
    }

    public function signatureGenerate($gateway, $data)
    {
        $merchantPrivateKey = $gateway->parameters->private_key;
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $merchantPrivateKey . "\n-----END RSA PRIVATE KEY-----";
        openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256);
        return base64_encode($signature);
    }

    public function decryptDataWithPrivateKey($gateway, $crypttext)
    {
        $merchantPrivateKey = $gateway->parameters->private_key;
        $private_key = "-----BEGIN RSA PRIVATE KEY-----\n" . $merchantPrivateKey . "\n-----END RSA PRIVATE KEY-----";
        openssl_private_decrypt(base64_decode($crypttext), $plain_text, $private_key);
        return $plain_text;
    }

    protected function decryptInitialResponse($gateway, object $response): bool
    {
        $plainResponse = json_decode($this->DecryptDataWithPrivateKey($gateway, $response->sensitiveData));

        if (isset($plainResponse->paymentReferenceId) && isset($plainResponse->challenge)) {
            $this->PAYMENT_REF_ID = $plainResponse->paymentReferenceId;
            $this->CHALLANGE = $plainResponse->challenge;
            return true;
        }
        return false;
    }

    public function encryptDataWithPublicKey($gateway, $data)
    {
        $pgPublicKey = $gateway->parameters->public_key;
        $public_key = "-----BEGIN PUBLIC KEY-----\n" . $pgPublicKey . "\n-----END PUBLIC KEY-----";
        $key_resource = openssl_get_publickey($public_key);
        openssl_public_encrypt($data, $crypttext, $key_resource);
        return base64_encode($crypttext);
    }

    public function updateAndMessage($deposit, $note, $status, $msg)
    {
        $deposit->update([
            'status' => 3,
            'note' => $note
        ]);
        $data['status'] = strtolower($status);
        $data['msg'] = $msg;
        $data['redirect'] = route('failed');
        return $data;
    }
}
PK     x\e'{l  l    Traits/SellPostTrait.phpnu [        <?php

namespace App\Traits;

trait SellPostTrait
{
    protected function getValueByStatus($status)
    {
        $array = [
            'pending' => 0,
            'approval' => 1,
            'resubmission' => 2,
            'hold' => 3,
            'soft-reject' => 4,
            'hard-reject' => 5,
        ];
        return $array[$status] ?? null;
    }
}
PK     x\/y2w  w    Traits/Rating.phpnu [        <?php


namespace App\Traits;


use App\Models\CardService;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Models\TopUp;
use App\Models\Review;
use App\Models\TopUpService;

trait Rating
{

    public function getTopReview($reviewable_type, $reviewable_id)
    {
        $data['reviews'] = Review::with(['user:id,firstname,lastname,email,image_driver,image'])
            ->where('status', 1)
            ->where('reviewable_type', $reviewable_type)
            ->where('reviewable_id', $reviewable_id)
            ->latest()
            ->take(3)
            ->get();

        $orderType = ($reviewable_type == TopUp::class) ? TopUpService::class : CardService::class;
        $parentModel = ($reviewable_type == TopUp::class) ? 'topUp' : 'card';

        $hasAlreadyOrdered = OrderDetail::with(["detailable" => function ($query) use ($parentModel, $reviewable_id) {
            $query->whereHas($parentModel, function ($q) use ($reviewable_id) {
                $q->where('id', $reviewable_id);
            });
        }])
            ->whereHas('order', function ($qq) {
                $qq->where('payment_status', 1);
            })
            ->where('user_id', auth()->id())
            ->where('detailable_type', $orderType)
            ->exists();

        $data['hasAlreadyOrdered'] = $hasAlreadyOrdered;

        return $data;
    }

    public function getAllReviews($reviewable_type, $reviewable_id)
    {
        $reviews = Review::with(['user:id,firstname,lastname,email,image_driver,image'])
            ->where('status', 1)
            ->where('reviewable_type', $reviewable_type)
            ->where('reviewable_id', $reviewable_id)
            ->latest()
            ->get();


        $data['excellentReview'] = $reviews->where('rating', 5);
        $data['excellentCount'] = count($data['excellentReview']);

        $data['greatReview'] = $reviews->where('rating', 4);
        $data['greatCount'] = count($data['greatReview']);

        $data['averageReview'] = $reviews->where('rating', 3);
        $data['averageCount'] = count($data['averageReview']);

        $data['poorReview'] = $reviews->where('rating', 2);
        $data['poorCount'] = count($data['poorReview']);

        $data['badReview'] = $reviews->where('rating', 1);
        $data['badCount'] = count($data['badReview']);

        return $data;
    }

    public function reviewNotifyToAdmin($reviewer, $name, $rating): void
    {
        try {

            $adminParams = [
                'name' => $name ?? null,
                'rating' => $rating ?? 1,
            ];

            $adminAction = [
                "name" => $reviewer->firstname . ' ' . $reviewer->lastname,
                "image" => getFile($reviewer->image_driver, $reviewer->image),
                "link" => route('admin.review.list'),
                "icon" => "fas fa-ticket-alt text-white"
            ];

            $this->adminMail('BUYER_REVIEW_TO_ADMIN', $adminParams);
            $this->adminPushNotification('BUYER_REVIEW_TO_ADMIN', $adminParams, $adminAction);
            $this->adminFirebasePushNotification('BUYER_REVIEW_TO_ADMIN', $adminAction);
        } catch (\Exception $e) {

        }
    }
}
PK     x\|A  A    Traits/ApiValidation.phpnu [        <?php

namespace App\Traits;

use App\Models\ApiClient;
use App\Models\User;
use Carbon\Carbon;
use Stevebauman\Location\Facades\Location;

trait ApiValidation
{
    public $validationErrorStatus = 422;
    public $uncompletedErrorStatus = 423;
    public $unauthorizedErrorStatus = 403;
    public $notFoundErrorStatus = 404;
    public $invalidErrorStatus = 400;
    public $notAcceptableStatus = 406;
    public $unknownStatus = 419;

    public function validationErrors($error)
    {
        return ['message' => 'The given data was invalid.', 'error' => $error];
    }

    public function withErrors($error)
    {
        return ['status' => 'failed', 'message' => $error];
    }

    public function withSuccess($msg)
    {
        return ['status' => 'success', 'message' => $msg];
    }

    public function user($publicKey, $secretKey, $ip = null)
    {

        if (auth()->check()) {
            $user = auth()->user();
        }else{
            $user = User::where('public_key', $publicKey)->where('secret_key', $secretKey)->first();
        }
        return $user;
    }
}
PK     x\/2  2    Traits/Translatable.phpnu [        <?php


namespace App\Traits;

use App\Models\Language;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;

trait Translatable
{
    public static function booted()
    {
        if (Auth::getDefaultDriver() != 'admin') {
            $lang = app()->getLocale();
            $languageTr = \Cache::rememberForever("languageTr_{$lang}", function () use ($lang) {
                return Language::where('short_name', $lang)->first();
            });

            $languageId = $languageTr ?: Language::where('default_status', true)->first();

            if ($languageId) {
                static::addGlobalScope('language', function (Builder $builder) use ($languageId) {
                    $builder->where('language_id', $languageId->id);
                });
            }
        }
    }
}
PK     x\      Traits/ToyyibPay.phpnu [        <?php

namespace App\Traits;

use Illuminate\Support\Facades\Http;

trait ToyyibPay
{
    protected function getBaseURL($mode = "test")
    {
        return $mode == 'test' ? "https://dev.toyyibpay.com" : "https://api.toyyibpay.com";
    }

    public function verifyPayment($request, $deposit, $gateway)
    {
        throw_if(empty($this->getBaseURL($gateway->environment)) || empty($gateway->parameters->secret_key ?? "") || empty($gateway->parameters->secret_key ?? ""), "Unable to process with Toyyib Pay.");

        $data = [
            'userSecretKey' => $gateway->parameters->secret_key,
            'billCode' => $deposit->payment_id,
        ];

        $uri = $this->getBaseURL($gateway->environment) . "/index.php/api/getBillTransactions";
        $response = Http::asForm()->post($uri, $data);
        $tayebPayResponse = json_decode($response->body());

        if (isset($tayebPayResponse[0]->billpaymentStatus)) {
            return $tayebPayResponse[0];
        }
        throw new \Exception("Failed to verify payment with Toyyib Pay.");
    }

    protected function updateAndMessage($deposit, $status, $note, $msg)
    {
        $deposit->update([
            'status' => $status,
            'note' => $note
        ]);

        return [
            'status' => 'error',
            'msg' => $msg,
            'redirect' => route('failed')
        ];
    }
}
PK     x\/?^  ^    Traits/Notify.phpnu [        <?php

namespace App\Traits;

use App\Events\AdminNotification;
use App\Events\UserNotification;
use App\Mail\SendMail;
use App\Models\Admin;
use App\Models\FireBaseToken;
use App\Models\InAppNotification;
use App\Models\ManualSmsConfig;
use App\Models\NotificationSettings;
use App\Models\NotificationTemplate;
use App\Models\SmsControl;
use Google\Auth\CredentialsLoader;
use Google\Auth\Middleware\AuthTokenMiddleware;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Facades\App\Services\BasicCurl;
use Facades\App\Services\SMS\BaseSmsService;


trait Notify
{
    public function sendMailSms($user, $templateKey, $params = [], $subject = null, $requestMessage = null)
    {

        $this->mail($user, $templateKey, $params, $subject, $requestMessage);
        $this->sms($user, $templateKey, $params, $requestMessage = null);
    }

    public function mail($user, $templateKey = null, $params = [], $subject = null, $requestMessage = null)
    {
        try {
            $basic = basicControl();

            $notificationPermission = NotificationSettings::where('notifyable_id',$user->id)->first();


            if ($notificationPermission && $notificationPermission->template_email_key){
                if (!in_array($templateKey, $notificationPermission->template_email_key)) {
                    return false;
                }
            }

            if ($basic->email_notification != 1) {
                return false;
            }

            $email_body = $basic->email_description;

            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('language_id', $user->language_id)->where('notify_for', 0)->first();
            if (!$templateObj) {
                $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 0)->first();
            }

            $message = str_replace("[[name]]", $user->username, $email_body);

            if (!$templateObj && $subject == null) {
                return false;
            } else {
                if ($templateObj) {
                    $message = str_replace("[[message]]", $templateObj->email, $message);
                    if (empty($message)) {
                        $message = $email_body;
                    }
                    foreach ($params as $code => $value) {
                        $message = str_replace('[[' . $code . ']]', $value, $message);
                    }
                } else {
                    $message = str_replace("[[message]]", $requestMessage, $message);
                }
            }

            $subject = ($subject == null) ? $templateObj->subject : $subject;
            $email_from = $basic->sender_email;

            Mail::to($user)->queue(new SendMail($email_from, $subject, $message));
        } catch (\Exception $exception) {
            return true;
        }
    }

    public function sms($user, $templateKey, $params = [], $requestMessage = null)
    {
        $basic = basicControl();

        $notificationPermission = NotificationSettings::where('notifyable_id',$user->id)->first();


        if ($notificationPermission && $notificationPermission->template_sms_key){
            if (!in_array($templateKey, $notificationPermission->template_sms_key)) {
                return false;
            }
        }


        if ($basic->sms_notification != 1) {
            return false;
        }

        $smsControl = ManualSmsConfig::firstOrCreate();

        $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('language_id', $user->language_id)->where('notify_for', 0)->first();
        if (!$templateObj) {
            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 0)->first();
        }
        if (!$templateObj) {
            return 0;
        }

        if (!$templateObj->status['sms']) {
            return false;
        }

        if (!$templateObj && $requestMessage == null) {
            return false;
        } else {
            if ($templateObj) {
                $template = $templateObj->sms;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
            } else {
                $template = $requestMessage;
            }
        }

        if (config('SMSConfig.default') == 'manual') {

            $paramData = is_null($smsControl->param_data) ? [] : json_decode($smsControl->param_data, true);
            $paramData = http_build_query($paramData);
            $actionUrl = $smsControl->action_url;
            $actionMethod = $smsControl->action_method;
            $formData = is_null($smsControl->form_data) ? [] : json_decode($smsControl->form_data, true);

            $headerData = is_null($smsControl->header_data) ? [] : json_decode($smsControl->header_data, true);
            if ($actionMethod == 'GET') {
                $actionUrl = $actionUrl . '?' . $paramData;
            }

            $formData = recursive_array_replace("[[receiver]]", $user->phone, recursive_array_replace("[[message]]", $template, $formData));

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $actionUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $actionMethod,
                CURLOPT_POSTFIELDS => http_build_query($formData),
                CURLOPT_HTTPHEADER => $headerData,
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            return $response;
        } else {
            BaseSmsService::sendSMS($user->phone_code . $user->phone, $template);
            return true;
        }
    }


    public function verifyToMail($user, $templateKey = null, $params = [], $subject = null, $requestMessage = null)
    {
        $basic = basicControl();
        if ($basic->email_verification != 1) {
            return false;
        }

        $email_body = $basic->email_description;
        $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('language_id', $user->language_id)->first();
        if (!$templateObj) {
            $templateObj = NotificationTemplate::where('template_key', $templateKey)->first();
        }

        if (!$templateObj) {
            return 0;
        }

        if (!$templateObj->status['mail']) {
            return false;
        }

        $message = str_replace("[[name]]", $user->username, $email_body);

        if (!$templateObj && $subject == null) {
            return false;
        } else {
            if ($templateObj) {
                $message = str_replace("[[message]]", $templateObj->email, $message);
                if (empty($message)) {
                    $message = $email_body;
                }
                foreach ($params as $code => $value) {
                    $message = str_replace('[[' . $code . ']]', $value, $message);
                }
            } else {
                $message = str_replace("[[message]]", $requestMessage, $message);
            }
        }

        $subject = ($subject == null) ? $templateObj->subject : $subject;
        $email_from = ($templateObj) ? $templateObj->email_from : $basic->sender_email;

        Mail::to($user)->send(new SendMail($email_from, $subject, $message));
    }

    public function verifyToSms($user, $templateKey, $params = [], $requestMessage = null)
    {

        $basic = basicControl();
        if ($basic->sms_verification != 1) {
            return false;
        }

        $smsControl = ManualSmsConfig::firstOrCreate(['id' => 1]);
        $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('language_id', $user->language_id)->where('notify_for', 0)->first();
        if (!$templateObj) {
            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 0)->first();
        }


        if (!$templateObj || $templateObj->status['sms'] == 0) {
            return false;
        }


        if (!$templateObj && $requestMessage == null) {
            return false;
        } else {
            if ($templateObj) {
                $template = $templateObj->sms;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
            } else {
                $template = $requestMessage;
            }
        }

        if (config('SMSConfig.default') == 'manual') {

            $paramData = is_null($smsControl->param_data) ? [] : json_decode($smsControl->param_data, true);
            $paramData = http_build_query($paramData);
            $actionUrl = $smsControl->action_url;
            $actionMethod = $smsControl->action_method;
            $formData = is_null($smsControl->form_data) ? [] : json_decode($smsControl->form_data, true);

            $headerData = is_null($smsControl->header_data) ? [] : json_decode($smsControl->header_data, true);
            if ($actionMethod == 'GET') {
                $actionUrl = $actionUrl . '?' . $paramData;
            }

            $formData = recursive_array_replace("[[receiver]]", $user->phone, recursive_array_replace("[[message]]", $template, $formData));

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $actionUrl,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => $actionMethod,
                CURLOPT_POSTFIELDS => http_build_query($formData),
                CURLOPT_HTTPHEADER => $headerData,
            ));

            $response = curl_exec($curl);
            curl_close($curl);
            return $response;
        } else {
            BaseSmsService::sendSMS($user->phone_code . $user->phone, $template);
            return true;
        }
    }

    public function userFirebasePushNotification($user, $templateKey, $params = [], $action = null)
    {
        try {
            $basic = basicControl();
            $notify = config('firebase');

            $notificationPermission = NotificationSettings::where('notifyable_id',$user->id)->first();
            if ($notificationPermission && $notificationPermission->template_push_key){
                if (!in_array($templateKey, $notificationPermission->template_push_key)) {
                    return false;
                }
            }



            if (!$basic->push_notification) {
                return false;
            }
            if ($notify['user_foreground'] == 0 && $notify['user_background'] == 0) {
                return false;
            }




            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('language_id', $user->language_id)->first();
            if ($templateObj && !$templateObj->status['push']) {
                return false;
            }


            if (!$templateObj) {
                $templateObj = NotificationTemplate::where('template_key', $templateKey)->first();
                if ($templateObj && !$templateObj->status['push']) {
                    return false;
                }
            }



            $template = '';
            if ($templateObj) {
                $template = $templateObj->push;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
            }
            $users = FireBaseToken::where('tokenable_id', $user->id)->latest()->get();


            $auth = CredentialsLoader::makeCredentials(
                ['https://www.googleapis.com/auth/cloud-platform'],
                json_decode(file_get_contents(base_path(getFirebaseFileName())), true)
            );
            $stack = HandlerStack::create();
            $middleware = new AuthTokenMiddleware($auth);
            $stack->push($middleware);
            $client = new Client(['handler' => $stack]);

            foreach ($users as $user) {
                try {
                    $data = [
                        'message' => [
                            'token' => $user->token,
                            'notification' => [
                                'title' => $templateObj->name . ' from ' . $basic->site_title,
                                'body' => $template,
                            ],
                            "data" => [
                                'foreground' => (string)$notify['user_foreground'],
                                'background' => (string)$notify['user_background'],
                                "click_action" => $action,
                                'redirect' => 'notification',
                            ],
                        ],
                    ];

                    $url = 'https://fcm.googleapis.com/v1/projects/' . $notify['projectId'] . '/messages:send';

                    $response = $client->post($url, [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $auth->fetchAuthToken()['access_token'],
                            'Content-Type' => 'application/json',
                        ],
                        'json' => $data,
                    ]);


                } catch (\Exception $e) {
                    continue;
                }
            }

        } catch (\Exception $e) {
            return 0;
        }
    }

    public function userPushNotification($user, $templateKey, $params = [], $action = [])
    {


        try {

            $basic = basicControl();

            $notificationPermission = NotificationSettings::where('notifyable_id',$user->id)->first();


            if ($notificationPermission && $notificationPermission->template_in_app_key){
                if (!in_array($templateKey, $notificationPermission->template_in_app_key)) {
                    return false;
                }
            }

            if ($basic->in_app_notification != 1) {
                return false;
            }

            $templateObj = NotificationTemplate::where('template_key', $templateKey)
                ->where('language_id', $user->language_id)->where('notify_for', 0)
                ->first();

            if (!$templateObj) {
                $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 0)->first();
                if (!$templateObj || !$templateObj->status['in_app']) {
                    return false;
                }
            }

            if ($templateObj) {
                $template = $templateObj->in_app;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
                $action['text'] = $template;
            }

            $inAppNotification = new InAppNotification();
            $inAppNotification->description = $action;
            $user->inAppNotification()->save($inAppNotification);
            event(new UserNotification($inAppNotification, $user->id));

        } catch (\Exception $e) {
            return 0;
        }

    }

    public function adminFirebasePushNotification($templateKey, $params = [], $action = null)
    {
        try {
            $basic = basicControl();
            $notify = config('firebase');
            if (!$notify) {
                return false;
            }

            if (!$basic->push_notification) {
                return false;
            }

            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 1)->first();
            if ($templateObj && !$templateObj->status['push']) {
                return false;
            }

            if (!$templateObj) {
                return false;
            }

            $template = '';
            if ($templateObj) {
                $template = $templateObj->push;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
            }
            $admins = FireBaseToken::where('tokenable_type', Admin::class)->get();

            $auth = CredentialsLoader::makeCredentials(
                ['https://www.googleapis.com/auth/cloud-platform'],
                json_decode(file_get_contents(base_path(getFirebaseFileName())), true)
            );
            $stack = HandlerStack::create();
            $middleware = new AuthTokenMiddleware($auth);
            $stack->push($middleware);
            $client = new Client(['handler' => $stack]);

            foreach ($admins as $admin) {

                try {
                    $data = [
                        'message' => [
                            'token' => $admin->token,
                            'notification' => [
                                'title' => $templateObj->name . ' from ' . $basic->site_title,
                                'body' => $template,
                                "icon" => getFile(basicControl()->favicon_driver, basicControl()->favicon),
                                "content_available" => true,
                                "mutable_content" => true
                            ],
                            "data" => [
                                "foreground" => (string) $notify['admin_foreground'],
                                "background" => (string) $notify['admin_background'],
                                "click_action" => $action,
                                'redirect' => 'notification',
                            ],
                        ],
                    ];

                    $url = 'https://fcm.googleapis.com/v1/projects/' . $notify['projectId'] . '/messages:send';
                    $response = $client->post($url, [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $auth->fetchAuthToken()['access_token'],
                            'Content-Type' => 'application/json',
                        ],
                        'json' => $data,
                    ]);
                }catch (\Exception $exception){
                    continue;
                }
            }
        } catch (\Exception $e) {
            return 0;
        }
    }

    public function adminPushNotification($templateKey, $params = [], $action = [])
    {


        try {
            $basic = basicControl();
            if ($basic->in_app_notification != 1) {
                return false;
            }

            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 1)->first();

            if (!$templateObj){
                return false;
            }
            if (!$templateObj->status['in_app']) {
                return false;
            }

            if ($templateObj) {
                $template = $templateObj->in_app;
                foreach ($params as $code => $value) {
                    $template = str_replace('[[' . $code . ']]', $value, $template);
                }
                $action['text'] = $template;
            }

            $admins = Admin::all();
            foreach ($admins as $admin) {
                $inAppNotification = new InAppNotification();
                $inAppNotification->description = $action;
                $admin->inAppNotification()->save($inAppNotification);
                event(new AdminNotification($inAppNotification, $admin->id));
            }
        } catch (\Exception $e) {

            return 0;
        }
    }

    public function adminMail($templateKey = null, $params = [], $subject = null, $requestMessage = null)
    {
        $basic = basicControl();

        if ($basic->email_notification != 1) {
            return false;
        }

        $email_body = $basic->email_description;
        $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 1)->first();
        if (!$templateObj) {
            $templateObj = NotificationTemplate::where('template_key', $templateKey)->where('notify_for', 1)->first();
        }

        if (!$templateObj){
            return false;
        }
        if (!$templateObj->status['mail']) {
            return false;
        }

        $message = $email_body;
        if ($templateObj) {
            $message = str_replace("[[message]]", $templateObj->email, $message);

            if (empty($message)) {
                $message = $email_body;
            }
            foreach ($params as $code => $value) {
                $message = str_replace('[[' . $code . ']]', $value, $message);
            }
        } else {
            $message = str_replace("[[message]]", $requestMessage, $message);
        }

        $subject = ($subject == null) ? $templateObj->subject : $subject;
        $email_from = $basic->sender_email;
        $admins = Admin::all();
        foreach ($admins as $admin) {
            $message = str_replace("[[name]]", $admin->username, $message);
            Mail::to($admin)->queue(new SendMail($email_from, $subject, $message));
        }
    }
    public function sendRealTimeMessageThrowFirebase($user, $message, $chatUId): void
    {
        $notify = config('firebase');
        $users = FireBaseToken::where('tokenable_id', $user->id)->get();

        try {
            $auth = CredentialsLoader::makeCredentials(
                ['https://www.googleapis.com/auth/cloud-platform'],
                json_decode(file_get_contents(base_path(getFirebaseFileName())), true)
            );
            $stack = HandlerStack::create();
            $middleware = new AuthTokenMiddleware($auth);
            $stack->push($middleware);
            $client = new Client(['handler' => $stack]);

            foreach ($users as $user) {
                try {
                    $data = [
                        'message' => [
                            'token' => $user->token,
                            'notification' => [
                                'title' => "Chatting",
                                'body' => json_encode($message),
                            ],
                            'data' => [
                                'chat_uid' => $chatUId,
                                'redirect' => 'chat',
                            ],
                        ],
                    ];


                    $url = 'https://fcm.googleapis.com/v1/projects/' . $notify['projectId'] . '/messages:send';
                    $response = $client->post($url, [
                        'headers' => [
                            'Authorization' => 'Bearer ' . $auth->fetchAuthToken()['access_token'],
                            'Content-Type' => 'application/json',
                        ],
                        'json' => $data,
                    ]);
                } catch (\Exception $e) {
                    continue;
                }
            }
        } catch (\Exception $e) {

        }
    }
}
PK     x\.      Traits/Sample.phpnu [        <?php


namespace App\Traits;

use Illuminate\Database\Eloquent\Builder;

trait Sample
{
    public function csvSampleDownload($file, $title)
    {
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $mimetype = mime_content_type('assets/' . $file);
        header('Content-Disposition: attachment; filename="' . $title . '.' . $ext . '";');
        header("Content-Type: " . $mimetype);
        return readfile('assets/' . $file);
    }
}
PK     x\0F      Traits/CurrencyRateUpdate.phpnu [        <?php

namespace App\Traits;


use Facades\App\Services\BasicCurl;

trait CurrencyRateUpdate
{
    public function fiatRateUpdate($source, $currencies)
    {
        if (basicControl()->currency_layer_access_key) {
            $endpoint = 'live';
            $currency_layer_url = "http://api.currencylayer.com";
            $currency_layer_access_key = basicControl()->currency_layer_access_key;

            $baseCurrencyAPIUrl = "$currency_layer_url/$endpoint?access_key=$currency_layer_access_key&source=$source&currencies=$currencies";
            $baseCurrencyConvert = BasicCurl::curlGetRequest($baseCurrencyAPIUrl);
            $result = json_decode($baseCurrencyConvert);

            if (isset($result->success) && isset($result->quotes)) {
                return [
                    'status' => true,
                    'res' => $result->quotes,
                ];
            }

            return [
                'status' => false,
                'res' => 'something went wrong',
            ];
        }
        return [
            'status' => false,
            'res' => 'Please set currencylayer api key',
        ];
    }
}
PK     x\3dB      Mail/TestMail.phpnu [        <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class TestMail extends Mailable
{
    use Queueable, SerializesModels;


    /**
     * Create a new message instance.
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Test Mail with mail gun',
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'email.test_email',
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}
PK     x\UR  R    Mail/SendMail.phpnu [        <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class SendMail extends Mailable
{
	use Queueable, SerializesModels;

	public $from_email;
	public $site_title;
	public $subject;
	public $message;

	/**
	 * Create a new message instance.
	 *
	 * @return void
	 */
	public function __construct($email_from, $subject, $message, $fromName = null)
	{
		$basic = basicControl();
		$this->from_email = $email_from;
		$this->site_title = ($fromName) ?: $basic->site_title;
		$this->subject = $subject;
		$this->message = $message;
	}


	/**
	 * Build the message.
	 *
	 * @return $this
	 */
	public function build()
	{
		return $this->from($this->from_email, $this->site_title)->view('layouts.mail')->with('msg', $this->message);
	}
}
PK     x\M?r      Mail/sendTestMail.phpnu [        <?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Address;


class sendTestMail extends Mailable
{
    use Queueable, SerializesModels;

    public $from_email;
    public $site_title;
    public $subject;
    public $message;

    /**
     * Create a new message instance.
     */
    public function __construct($email_from, $subject, $message, $fromName = null)
    {
        $basic = basicControl();
        $this->from_email = $email_from;
        $this->site_title = ($fromName) ?: $basic->site_title;
        $this->subject = $subject;
        $this->message = $message;
    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            from: $this->from_email,
            subject: $this->subject,
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'email.test_email',
            with: [
                'msg' => $this->message
            ]
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}
PK     x\8tnt  t  "  Providers/EventServiceProvider.phpnu [        <?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event to listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
    ];

    /**
     * Register any events for your application.
     */
    public function boot(): void
    {
        //
    }

    /**
     * Determine if events and listeners should be automatically discovered.
     */
    public function shouldDiscoverEvents(): bool
    {
        return false;
    }
}
PK     x\O'  '  "  Providers/RouteServiceProvider.phpnu [        <?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;

class RouteServiceProvider extends ServiceProvider
{
    /**
     * The path to your application's "home" route.
     *
     * Typically, users are redirected here after authentication.
     *
     * @var string
     */

    public const HOME = '/user/dashboard';
    public const ADMIN = '/admin/dashboard';

    /**
     * Define your route model bindings, pattern filters, and other route configuration.
     */
    public function boot(): void
    {
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        $this->routes(function () {
            Route::middleware('api')
                ->prefix('api')
                ->group(base_path('routes/api.php'));

            Route::middleware('web')
                ->group(base_path('routes/admin.php'));

            Route::middleware('web')
                ->group(base_path('routes/web.php'));

            Route::middleware('web')
                ->group(base_path('routes/module/admin-module.php'));
            Route::middleware('web')
                ->group(base_path('routes/module/user-module.php'));
            Route::middleware('web')
                ->group(base_path('routes/module/frontend-module.php'));
        });
    }
}
PK     x\Ɩ    !  Providers/AuthServiceProvider.phpnu [        <?php

namespace App\Providers;

// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The model to policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        //
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot(): void
    {
        //
    }
}
PK     x\              Providers/index.phpnu [        PK     x\ԇ=       Providers/AppServiceProvider.phpnu [        <?php

namespace App\Providers;

use App\Models\Category;
use App\Models\Content;
use App\Models\ContentDetails;
use App\Models\Currency;
use App\Models\Language;
use App\Models\ManageMenu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Bridge\Mailchimp\Transport\MandrillTransportFactory;
use Symfony\Component\Mailer\Bridge\Sendgrid\Transport\SendgridTransportFactory;
use Symfony\Component\Mailer\Bridge\Sendinblue\Transport\SendinblueTransportFactory;
use Symfony\Component\Mailer\Transport\Dsn;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        try {
            DB::connection()->getPdo();

            $data['basicControl'] = basicControl();
            View::share($data);

            view()->composer([
                'themes.dark.partials.nav',
                'themes.light.partials.nav',
                'themes.dark.sections.footer',
                'themes.light.sections.footer',
                'themes.light.page',
                'themes.dark.page',
            ], function ($view) {
                $languages = \Cache::get("language");
                if(!$languages || empty($languages)){
                    $languages = Language::where('status',1)->get();
                    \Cache::put('language', $languages);
                }

                $currencies = \Cache::get("currency");
                if(!$currencies || empty($currencies)){
                    $currencies = Currency::where('status',1)->get();
                    \Cache::put('currency', $currencies);
                }

                $lang = new \App\Http\Middleware\Language();
                $code = $lang->getCode();
                $defaultLanguage = $languages->where('short_name', $code)->first();

                $contentDetails = \Cache::get("manage_content");
                if(!$contentDetails || empty($languages)){
                    $contentDetails = ContentDetails::with('content')
                        ->whereIn('content_id', Content::whereIn('name', ['cookie', 'footer'])->pluck('id'))
                        ->get()
                        ->groupBy(function ($item) {
                            return $item->content->name;
                        });
                    \Cache::put('manage_content', $contentDetails);
                }

                $footerData = $this->prepareContentData($contentDetails->get('footer'), $defaultLanguage, 'footer', $languages);

                $view->with([
                    'footer' => $footerData,
                    'languages' => $languages,
                    'currencies' => $currencies,
                ]);
            });

            if (basicControl()->force_ssl == 1) {
                if ($this->app->environment('production') || $this->app->environment('local')) {
                    \URL::forceScheme('https');
                }
            }

            $this->registerMailTransport('sendinblue', new SendinblueTransportFactory);
            $this->registerMailTransport('sendgrid', new SendgridTransportFactory);
            $this->registerMailTransport('mandrill', new MandrillTransportFactory);

        } catch (\Exception $e) {
        }

    }

    private function registerMailTransport(string $name, $factory)
    {
        Mail::extend($name, fn() => $factory->create(
            new Dsn("{$name}+api", 'default', config("services.{$name}.key"))
        ));
    }
    private function prepareContentData($contents ,$default ,$contentType ,$language = null )
    {
        if (is_null($contents)) {
            return [
                'single' => [],
                'multiple' => collect(),
                'languages' => $language,
                'defaultLanguage' => $default,
            ];
        }

        $singleContent = $contents->where('content.name', $contentType)
            ->where('content.type', 'single')
            ->first() ?? [];

        $multipleContents = $contents->where('content.name', $contentType)
            ->where('content.type', 'multiple')
            ->values()
            ->map(fn($content) => collect($content->description)->merge($content->content->only('media')));

        return [
            'single' => $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [],
            'multiple' => $multipleContents,
            'languages' => $language,
            'defaultLanguage' => $default,
        ];
    }
}
PK     x\RPQ8g  g  &  Providers/BroadcastServiceProvider.phpnu [        <?php

namespace App\Providers;

use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;

class BroadcastServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Broadcast::routes();

        require base_path('routes/channels.php');
    }
}
PK     x\!  !    Helpers/GoogleAuthenticator.phpnu [        <?php

namespace App\Helpers;


class GoogleAuthenticator
{
    protected $_codeLength = 6;


    public function createSecret($secretLength = 16)
    {
        $validChars = $this->_getBase32LookupTable();

        // Valid secret lengths are 80 to 640 bits
        if ($secretLength < 16 || $secretLength > 128) {
            throw new \Exception('Bad secret length');
        }
        $secret = '';
        $rnd = false;
        if (function_exists('random_bytes')) {
            $rnd = random_bytes($secretLength);
        } elseif (function_exists('mcrypt_create_iv')) {
            $rnd = mcrypt_create_iv($secretLength, MCRYPT_DEV_URANDOM);
        } elseif (function_exists('openssl_random_pseudo_bytes')) {
            $rnd = openssl_random_pseudo_bytes($secretLength, $cryptoStrong);
            if (!$cryptoStrong) {
                $rnd = false;
            }
        }
        if ($rnd !== false) {
            for ($i = 0; $i < $secretLength; ++$i) {
                $secret .= $validChars[ord($rnd[$i]) & 31];
            }
        } else {
            throw new \Exception('No source of secure random');
        }

        return $secret;
    }


    public function getCode($secret, $timeSlice = null)
    {
        if ($timeSlice === null) {
            $timeSlice = floor(time() / 30);
        }

        $secretkey = $this->_base32Decode($secret);

        // Pack time into binary string
        $time = chr(0) . chr(0) . chr(0) . chr(0) . pack('N*', $timeSlice);
        // Hash it with users secret key
        $hm = hash_hmac('SHA1', $time, $secretkey, true);
        // Use last nipple of result as index/offset
        $offset = ord(substr($hm, -1)) & 0x0F;
        // grab 4 bytes of the result
        $hashpart = substr($hm, $offset, 4);

        // Unpak binary value
        $value = unpack('N', $hashpart);
        $value = $value[1];
        // Only 32 bits
        $value = $value & 0x7FFFFFFF;

        $modulo = pow(10, $this->_codeLength);

        return str_pad($value % $modulo, $this->_codeLength, '0', STR_PAD_LEFT);
    }

    /**
     * Get QR-Code URL for image, from google charts.
     *
     * @param string $name
     * @param string $secret
     * @param string $title
     * @param array  $params
     *
     * @return string
     */
    public function getQRCodeGoogleUrl($name, $secret, $title = null, $params = array())
    {
        $width = !empty($params['width']) && (int) $params['width'] > 0 ? (int) $params['width'] : 200;
        $height = !empty($params['height']) && (int) $params['height'] > 0 ? (int) $params['height'] : 200;
        $level = !empty($params['level']) && array_search($params['level'], array('L', 'M', 'Q', 'H')) !== false ? $params['level'] : 'M';

        $urlencoded = urlencode('otpauth://totp/' . $name . '?secret=' . $secret . '');
        if (isset($title)) {
            $urlencoded .= urlencode('&issuer=' . urlencode($title));
        }

        return 'https://chart.googleapis.com/chart?chs=' . $width . 'x' . $height . '&chld=' . $level . '|0&cht=qr&chl=' . $urlencoded . '';
    }

    public function verifyCode($secret, $code, $discrepancy = 1, $currentTimeSlice = null)
    {
        if ($currentTimeSlice === null) {
            $currentTimeSlice = floor(time() / 30);
        }

        if (strlen($code) != 6) {
            return false;
        }

        for ($i = -$discrepancy; $i <= $discrepancy; ++$i) {
            $calculatedCode = $this->getCode($secret, $currentTimeSlice + $i);
            if ($this->timingSafeEquals($calculatedCode, $code)) {
                return true;
            }
        }

        return false;
    }

    public function setCodeLength($length)
    {
        $this->_codeLength = $length;

        return $this;
    }

    protected function _base32Decode($secret)
    {
        if (empty($secret)) {
            return '';
        }

        $base32chars = $this->_getBase32LookupTable();
        $base32charsFlipped = array_flip($base32chars);

        $paddingCharCount = substr_count($secret, $base32chars[32]);
        $allowedValues = array(6, 4, 3, 1, 0);
        if (!in_array($paddingCharCount, $allowedValues)) {
            return false;
        }
        for ($i = 0; $i < 4; ++$i) {
            if (
                $paddingCharCount == $allowedValues[$i] &&
                substr($secret, -($allowedValues[$i])) != str_repeat($base32chars[32], $allowedValues[$i])
            ) {
                return false;
            }
        }
        $secret = str_replace('=', '', $secret);
        $secret = str_split($secret);
        $binaryString = '';
        for ($i = 0; $i < count($secret); $i = $i + 8) {
            $x = '';
            if (!in_array($secret[$i], $base32chars)) {
                return false;
            }
            for ($j = 0; $j < 8; ++$j) {
                $x .= str_pad(base_convert(@$base32charsFlipped[@$secret[$i + $j]], 10, 2), 5, '0', STR_PAD_LEFT);
            }
            $eightBits = str_split($x, 8);
            for ($z = 0; $z < count($eightBits); ++$z) {
                $binaryString .= (($y = chr(base_convert($eightBits[$z], 2, 10))) || ord($y) == 48) ? $y : '';
            }
        }

        return $binaryString;
    }

    protected function _getBase32LookupTable()
    {
        return array(
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //  7
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', // 15
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', // 23
            'Y', 'Z', '2', '3', '4', '5', '6', '7', // 31
            '=',  // padding char
        );
    }

    private function timingSafeEquals($safeString, $userString)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($safeString, $userString);
        }
        $safeLen = strlen($safeString);
        $userLen = strlen($userString);

        if ($userLen != $safeLen) {
            return false;
        }

        $result = 0;

        for ($i = 0; $i < $userLen; ++$i) {
            $result |= (ord($safeString[$i]) ^ ord($userString[$i]));
        }

        // They are only identical strings if $result is exactly 0...
        return $result === 0;
    }
}
PK     x\`      Helpers/UserSystemInfo.phpnu [        <?php

namespace App\Helpers;
use Illuminate\Support\Str;

class UserSystemInfo
{

    private static function get_user_agent(){
        return $_SERVER['HTTP_USER_AGENT'];
    }

    public static function get_ip(){

        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if(isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if(isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;

    }

    public static function get_os(){

        $user_agent = self::get_user_agent();
        $os_platform = "Unknown OS Platform";
        $os_array = array(
            '/windows nt 10/i'  => 'Windows 10',
            '/windows nt 6.3/i'  => 'Windows 8.1',
            '/windows nt 6.2/i'  => 'Windows 8',
            '/windows nt 6.1/i'  => 'Windows 7',
            '/windows nt 6.0/i'  => 'Windows Vista',
            '/windows nt 5.2/i'  => 'Windows Server 2003/XP x64',
            '/windows nt 5.1/i'  => 'Windows XP',
            '/windows xp/i'  => 'Windows XP',
            '/windows nt 5.0/i'  => 'Windows 2000',
            '/windows me/i'  => 'Windows ME',
            '/win98/i'  => 'Windows 98',
            '/win95/i'  => 'Windows 95',
            '/win16/i'  => 'Windows 3.11',
            '/macintosh|mac os x/i' => 'Mac OS X',
            '/mac_powerpc/i'  => 'Mac OS 9',
            '/linux/i'  => 'Linux',
            '/ubuntu/i'  => 'Ubuntu',
            '/iphone/i'  => 'iPhone',
            '/ipod/i'  => 'iPod',
            '/ipad/i'  => 'iPad',
            '/android/i'  => 'Android',
            '/blackberry/i'  => 'BlackBerry',
            '/webos/i'  => 'Mobile',
        );

        foreach ($os_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $os_platform = $value;
            }
        }
        return $os_platform;
    }

    public static function get_browsers(){

        $user_agent= self::get_user_agent();

        $browser = "Unknown Browser";

        $browser_array = array(
            '/msie/i'  => 'Internet Explorer',
            '/Trident/i'  => 'Internet Explorer',
            '/firefox/i'  => 'Firefox',
            '/safari/i'  => 'Safari',
            '/chrome/i'  => 'Chrome',
            '/edge/i'  => 'Edge',
            '/opera/i'  => 'Opera',
            '/netscape/'  => 'Netscape',
            '/maxthon/i'  => 'Maxthon',
            '/knoqueror/i'  => 'Konqueror',
            '/ubrowser/i'  => 'UC Browser',
            '/mobile/i'  => 'Safari Browser',
        );

        foreach($browser_array as $regex => $value){
            if(preg_match($regex, $user_agent)){
                $browser = $value;
            }
        }
        return $browser;

    }

    public static function get_device(){

        $tablet_browser = 0;
        $mobile_browser = 0;

        if(preg_match('/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $tablet_browser++;
        }

        if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile)/i', strtolower($_SERVER['HTTP_USER_AGENT']))){
            $mobile_browser++;
        }

        if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),
                    'application/vnd.wap.xhtml+xml')> 0) or
            ((isset($_SERVER['HTTP_X_WAP_PROFILE']) or
                isset($_SERVER['HTTP_PROFILE'])))){
            $mobile_browser++;
        }

        $mobile_ua = strtolower(substr(self::get_user_agent(), 0, 4));
        $mobile_agents = array(
            'w3c','acs-','alav','alca','amoi','audi','avan','benq','bird','blac','blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
            'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-','maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',

            'newt','noki','palm','pana','pant','phil','play','port','prox','qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',

            'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-','tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
            'wapr','webc','winw','winw','xda','xda-');

        if(in_array($mobile_ua,$mobile_agents)){
            $mobile_browser++;
        }

        if(strpos(strtolower(self::get_user_agent()),'opera mini') > 0){
            $mobile_browser++;

            //Check for tables on opera mini alternative headers

            $stock_ua =
                strtolower(isset($_SERVER['HTTP_X_OPERAMINI_PHONE_UA'])?
                    $_SERVER['HTTP_X_OPERAMINI_PHONE_UA']:
                    (isset($_SERVER['HTTP_DEVICE_STOCK_UA'])?
                        $_SERVER['HTTP_DEVICE_STOCK_UA']:''));

            if(preg_match('/(tablet|ipad|playbook)|(android(?!.*mobile))/i', $stock_ua)){
                $tablet_browser++;
            }
        }

        if($tablet_browser > 0){
            //do something for tablet devices

            return 'Tablet';
        }
        else if($mobile_browser > 0){
            //do something for mobile devices

            return 'Mobile';
        }
        else{
            //do something for everything else
            return 'Computer';
        }
    }

}
PK     x\q      Helpers/helpers.phpnu [        <?php

use App\Models\BasicControl;
use App\Models\Category;
use App\Models\Content;
use App\Models\ContentDetails;
use App\Models\Currency;
use App\Models\ManageMenu;
use App\Models\Page;
use App\Models\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use App\Models\Language;
use App\Models\PageDetail;
use App\Models\TopUp;
use App\Models\Card;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Schema;

if (!function_exists('template')) {
    function template($asset = false)
    {
        $activeTheme = getTheme();

        $currentRouteName = Route::currentRouteName();
        if (Str::startsWith($currentRouteName, 'user.') || request()->param == 'user') {
            if ($asset) return 'assets/themes/dark/';

            return 'themes.dark.';
        }

        if ($asset) return 'assets/themes/' . $activeTheme . '/';
        return 'themes.' . $activeTheme . '.';
    }
}

if (!function_exists('getTheme')) {
    function getTheme()
    {
        $theme = session('theme') ?? basicControl()->theme ?? null;
        return $theme;
    }
}
if (!function_exists('getDash')) {
    function getDash()
    {
        return auth()->user()->active_dashboard ?? 'nightfall';
    }
}


if (!function_exists('getThemesNames')) {
    function getThemesNames()
    {
        $directory = resource_path('views/themes');
        return File::isDirectory($directory) ? array_map('basename', File::directories($directory)) : [];
    }
}

if (!function_exists('stringToTitle')) {
    function stringToTitle($string)
    {
        return implode(' ', array_map('ucwords', explode(' ', preg_replace('/[^a-zA-Z0-9]+/', ' ', $string))));
    }
}

if (!function_exists('getTitle')) {
    function getTitle($title)
    {
        if ($title == "sms") {
            return strtoupper(preg_replace('/[^A-Za-z0-9]/', ' ', $title));
        }
        return ucwords(preg_replace('/[^A-Za-z0-9]/', ' ', $title));
    }
}

if (!function_exists('getRoute')) {
    function getRoute($route, $params = null)
    {
        return isset($params) ? route($route, $params) : route($route);
    }
}

if (!function_exists('getPageSections')) {
    function getPageSections()
    {
        $sectionsPath = resource_path('views/') . str_replace('.', '/', template()) . 'sections';
        $pattern = $sectionsPath . '/*';
        $files = glob($pattern);

        $fileBaseNames = [];

        foreach ($files as $file) {
            if (is_file($file)) {
                $basename = basename($file);
                $basenameWithoutExtension = str_replace('.blade.php', '', $basename);
                $fileBaseNames[$basenameWithoutExtension] = $basenameWithoutExtension;
            }
        }

        return $fileBaseNames;
    }
}
if (!function_exists('strRandomNum')) {
    function strRandomNum($length = 15)
    {
        $characters = '1234567890';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
}

if (!function_exists('hex2rgba')) {
    function hex2rgba($color, $opacity = false)
    {
        $default = 'rgb(0,0,0)';

        if (empty($color))
            return $default;

        if ($color[0] == '#') {
            $color = substr($color, 1);
        }

        if (strlen($color) == 6) {
            $hex = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
        } elseif (strlen($color) == 3) {
            $hex = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
        } else {
            return $default;
        }

        $rgb = array_map('hexdec', $hex);

        if ($opacity) {
            if (abs($opacity) > 1)
                $opacity = 1.0;
            $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
        } else {
            $output = 'rgb(' . implode(",", $rgb) . ')';
        }
        return $output;
    }
}

if (!function_exists('basicControl')) {
    function basicControl()
    {
        if (session()->get('themeMode') == null) {
            session()->put('themeMode', 'auto');
        }

        try {
            $configure = null;
            DB::connection()->getPdo();
            $configure = \Cache::get('ConfigureSetting');
            if (!$configure) {
                if (Schema::hasTable('basic_controls')) {
                    $configure = BasicControl::firstOrCreate();
                    \Cache::put('ConfigureSetting', $configure);
                }
            }

            return $configure;
        } catch (\Exception $e) {
        }
    }
}

if (!function_exists('checkTo')) {
    function checkTo($currencies, $selectedCurrency = 'USD')
    {
        foreach ($currencies as $key => $currency) {
            if (property_exists($currency, strtoupper($selectedCurrency))) {
                return $key;
            }
        }
    }
}


if (!function_exists('controlPanelRoutes')) {
    function controlPanelRoutes()
    {
        $listRoutes = collect([]);
        $listRoutes->push(config('generalsettings.settings'));
        $listRoutes->push(config('generalsettings.plugin'));
        $listRoutes->push(config('generalsettings.in-app-notification'));
        $listRoutes->push(config('generalsettings.push-notification'));
        $listRoutes->push(config('generalsettings.email'));
        $listRoutes->push(config('generalsettings.sms'));
        $list = $listRoutes->collapse()->map(function ($item) {
            return $item['route'];
        })->values()->push('admin.settings')->unique();
        return $list;
    }
}


if (!function_exists('menuActive')) {
    function menuActive($routeName, $type = null)
    {
        $class = 'active';
        if ($type == 3) {
            $class = 'active collapsed';
        } elseif ($type == 2) {
            $class = 'show';
        }

        if (is_array($routeName)) {
            foreach ($routeName as $key => $value) {
                if (request()->routeIs($value)) {
                    return $class;
                }
            }
        } elseif (request()->routeIs($routeName)) {
            return $class;
        }
    }
}

if (!function_exists('isMenuActive')) {
    function isMenuActive($routes, $type = 0)
    {
        $class = [
            '0' => 'active',
            '1' => 'style=display:block',
            '2' => true
        ];

        if (is_array($routes)) {
            foreach ($routes as $key => $route) {
                if (request()->routeIs($route)) {
                    return $class[$type];
                }
            }
        } elseif (request()->routeIs($routes)) {
            return $class[$type];
        }

        if ($type == 1) {
            return 'style=display:none';
        } else {
            return false;
        }
    }
}


if (!function_exists('strRandom')) {
    function strRandom($length = 12)
    {
        $characters = 'ABCDEFGHJKMNOPQRSTUVWXYZ123456789';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }
}


if (!function_exists('getFile')) {
    function getFile($disk = 'local', $image = '', $upload = false)
    {
        $default = ($upload == true) ? asset(config('filelocation.default2')) : asset(config('filelocation.default'));
        try {
            if ($disk == 'local') {
                $localImage = asset('/assets/upload') . '/' . $image;
                return !empty($image) && Storage::disk($disk)->exists($image) ? $localImage : $default;
            } else {
                return !empty($image) && Storage::disk($disk)->exists($image) ? Storage::disk($disk)->url($image) : $default;
            }
        } catch (Exception $e) {
            return $default;
        }
    }
}

if (!function_exists('getFileForEdit')) {
    function getFileForEdit($disk = 'local', $image = null)
    {
        try {
            if ($disk == 'local') {
                $localImage = asset('/assets/upload') . '/' . $image;
                return !empty($image) && Storage::disk($disk)->exists($image) ? $localImage : null;
            } else {
                return !empty($image) && Storage::disk($disk)->exists($image) ? Storage::disk($disk)->url($image) : asset(config('location.default'));
            }
        } catch (Exception $e) {
            return null;
        }
    }
}

if (!function_exists('title2snake')) {
    function title2snake($string)
    {
        return Str::title(str_replace(' ', '_', $string));
    }
}

if (!function_exists('snake2Title')) {
    function snake2Title($string)
    {
        return Str::title(str_replace('_', ' ', $string));
    }
}
if (!function_exists('formatFieldName')) {
    function formatFieldName($fieldName)
    {
        $formatted = preg_replace('/([a-z])([A-Z])/', '$1 $2', $fieldName);

        $formatted = str_replace('_', ' ', $formatted);
        return $formatted;
    }
}


if (!function_exists('kebab2Title')) {
    function kebab2Title($string)
    {
        return Str::title(str_replace('-', ' ', $string));
    }
}

if (!function_exists('getMethodCurrency')) {
    function getMethodCurrency($gateway)
    {
        foreach ($gateway->currencies as $key => $currency) {
            if (property_exists($currency, $gateway->currency)) {
                if ($key == 0) {
                    return $gateway->currency;
                } else {
                    return 'USD';
                }
            }
        }
    }
}

if (!function_exists('twoStepPrevious')) {
    function twoStepPrevious($deposit)
    {
        if ($deposit->depositable_type == \App\Models\Fund::class) {
            return route('fund.initialize');
        }
    }
}


if (!function_exists('slug')) {
    function slug($title)
    {
        return Str::slug($title);
    }
}

if (!function_exists('clean')) {
    function clean($string)
    {
        $string = str_replace(' ', '_', $string); // Replaces all spaces with hyphens.
        return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
    }
}

if (!function_exists('diffForHumans')) {
    function diffForHumans($date)
    {
        $lang = session()->get('lang');
        \Carbon\Carbon::setlocale($lang);
        return \Carbon\Carbon::parse($date)->diffForHumans();
    }
}

if (!function_exists('loopIndex')) {
    function loopIndex($object)
    {
        return ($object->currentPage() - 1) * $object->perPage() + 1;
    }
}

if (!function_exists('dateTime')) {
    function dateTime($date, $format = null)
    {
        if (!$format) {
            $format = basicControl()->date_time_format;
        }
        return date($format, strtotime($date));
    }
}


if (!function_exists('getProjectDirectory')) {
    function getProjectDirectory()
    {
        return str_replace((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]", "", url("/"));
    }
}

if (!function_exists('defaultLang')) {
    function defaultLang()
    {
        return Language::where('default_status', true)->first();
    }
}

if (!function_exists('removeHyphenInString')) {
    function removeHyphenInString($string)
    {
        return str_replace("_", " ", $string);
    }
}


function updateBalance($user_id, $amount, $action = 0)
{
    try {
        $user = User::where('id', $user_id)->firstOr(function () {
            throw new \Exception('User not found!');
        });
        if ($amount > $user->balance) {
            return back()->with('error', 'Insufficient Balance to deducted.');
        }
        if ($action == 1) { //add money
            $balance = $user->balance + $amount;
            $user->balance = $balance;
        } elseif ($action == 0) { //deduct money
            $balance = $user->balance - $amount;
            $user->balance = $balance;
        }
        $user->save();
    } catch (Exception $e) {
        return back()->with('error', $e->getMessage());
    }
}


function getAmount($amount, $length = 0)
{
    if ($amount == 0) {
        return 0;
    }
    if ($length == 0) {
        preg_match("#^([\+\-]|)([0-9]*)(\.([0-9]*?)|)(0*)$#", trim($amount), $o);
        return $o[1] . sprintf('%d', $o[2]) . ($o[3] != '.' ? $o[3] : '');
    }

    return round($amount, $length);
}

function formatAmount($amount)
{
    if ($amount) {
        if ($amount != floor($amount)) {
            return number_format($amount, 2);
        }
        return number_format($amount);
    }
    return 0;
}

if (!function_exists('currencyPosition')) {
    function currencyPosition($amount)
    {
        $basic = basicControl();
        $amount = fractionNumber((float)$amount);
        return $basic->is_currency_position == 'left' && $basic->has_space_between_currency_and_amount ? "{$basic->currency_symbol} {$amount}" :
            ($basic->is_currency_position == 'left' && !$basic->has_space_between_currency_and_amount ? "{$basic->currency_symbol}{$amount}" :
                ($basic->is_currency_position == 'right' && $basic->has_space_between_currency_and_amount ? "{$amount} {$basic->base_currency} " :
                    "{$amount}{$basic->base_currency}"));
    }

}

if (!function_exists('userCurrencyPosition')) {
    function userCurrencyPosition($amount)
    {
        $basic = basicControl();
        $amount = round((float)$amount * (session()->get('currency_rate', 1)), 2);
        $currency_symbol = session()->get('currency_symbol', $basic->currency_symbol);
        $currency_code = session()->get('currency_code', $basic->currency_symbol);

        $space = $basic->has_space_between_currency_and_amount ? ' ' : '';

        if ($basic->is_currency_position == 'left') {
            return "{$currency_symbol}{$space}{$amount}";
        } else {
            return "{$amount}{$space}{$currency_code}";
        }
    }
}


if (!function_exists('fractionNumber')) {
    function fractionNumber($amount, $afterComma = true)
    {
        $basic = basicControl();
        if (!$afterComma) {
            return number_format($amount + 0);
        }
        $formattedAmount = number_format($amount, $basic->fraction_number ?? 2);

        return rtrim(rtrim($formattedAmount, '0'), '.');

    }
}


function hextorgb($hexstring)
{
    $integar = hexdec($hexstring);
    return array("red" => 0xFF & ($integar >> 0x10),
        "green" => 0xFF & ($integar >> 0x8),
        "blue" => 0xFF & $integar);
}

function renderCaptCha($rand)
{
//    session_start();
    $captcha_code = '';
    $captcha_image_height = 50;
    $captcha_image_width = 130;
    $total_characters_on_image = 6;

    $possible_captcha_letters = 'bcdfghjkmnpqrstvwxyz23456789';
    $captcha_font = 'assets/monofont.ttf';

    $random_captcha_dots = 50;
    $random_captcha_lines = 25;
    $captcha_text_color = "0x142864";
    $captcha_noise_color = "0x142864";


    $count = 0;
    while ($count < $total_characters_on_image) {
        $captcha_code .= substr(
            $possible_captcha_letters,
            mt_rand(0, strlen($possible_captcha_letters) - 1),
            1);
        $count++;
    }


    $captcha_font_size = $captcha_image_height * 0.65;
    $captcha_image = @imagecreate(
        $captcha_image_width,
        $captcha_image_height
    );

    /* setting the background, text and noise colours here */
    $background_color = imagecolorallocate(
        $captcha_image,
        255,
        255,
        255
    );

    $array_text_color = hextorgb($captcha_text_color);
    $captcha_text_color = imagecolorallocate(
        $captcha_image,
        $array_text_color['red'],
        $array_text_color['green'],
        $array_text_color['blue']
    );

    $array_noise_color = hextorgb($captcha_noise_color);
    $image_noise_color = imagecolorallocate(
        $captcha_image,
        $array_noise_color['red'],
        $array_noise_color['green'],
        $array_noise_color['blue']
    );

    /* Generate random dots in background of the captcha image */
    for ($count = 0; $count < $random_captcha_dots; $count++) {
        imagefilledellipse(
            $captcha_image,
            mt_rand(0, $captcha_image_width),
            mt_rand(0, $captcha_image_height),
            2,
            3,
            $image_noise_color
        );
    }

    /* Generate random lines in background of the captcha image */
    for ($count = 0; $count < $random_captcha_lines; $count++) {
        imageline(
            $captcha_image,
            mt_rand(0, $captcha_image_width),
            mt_rand(0, $captcha_image_height),
            mt_rand(0, $captcha_image_width),
            mt_rand(0, $captcha_image_height),
            $image_noise_color
        );
    }

    /* Create a text box and add 6 captcha letters code in it */
    $text_box = imagettfbbox(
        $captcha_font_size,
        0,
        $captcha_font,
        $captcha_code
    );
    $x = ($captcha_image_width - $text_box[4]) / 2;
    $y = ($captcha_image_height - $text_box[5]) / 2;
    imagettftext(
        $captcha_image,
        $captcha_font_size,
        0,
        $x,
        $y,
        $captcha_text_color,
        $captcha_font,
        $captcha_code
    );

    /* Show captcha image in the html page */
// defining the image type to be shown in browser widow
    header('Content-Type: image/jpeg');
    imagejpeg($captcha_image); //showing the image
    imagedestroy($captcha_image); //destroying the image instance
//    $_SESSION['captcha'] = $captcha_code;

    session()->put('captcha', $captcha_code);
}

function getIpInfo()
{
//	$ip = '210.1.246.42';
    $ip = null;
    $deep_detect = TRUE;

    if (filter_var($ip, FILTER_VALIDATE_IP) === FALSE) {
        $ip = $_SERVER["REMOTE_ADDR"];
        if ($deep_detect) {
            if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP))
                $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
    }
    $xml = @simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=" . $ip);

    $country = @$xml->geoplugin_countryName;
    $city = @$xml->geoplugin_city;
    $area = @$xml->geoplugin_areaCode;
    $code = @$xml->geoplugin_countryCode;
    $long = @$xml->geoplugin_longitude;
    $lat = @$xml->geoplugin_latitude;


    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $os_platform = "Unknown OS Platform";
    $os_array = array(
        '/windows nt 10/i' => 'Windows 10',
        '/windows nt 6.3/i' => 'Windows 8.1',
        '/windows nt 6.2/i' => 'Windows 8',
        '/windows nt 6.1/i' => 'Windows 7',
        '/windows nt 6.0/i' => 'Windows Vista',
        '/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
        '/windows nt 5.1/i' => 'Windows XP',
        '/windows xp/i' => 'Windows XP',
        '/windows nt 5.0/i' => 'Windows 2000',
        '/windows me/i' => 'Windows ME',
        '/win98/i' => 'Windows 98',
        '/win95/i' => 'Windows 95',
        '/win16/i' => 'Windows 3.11',
        '/macintosh|mac os x/i' => 'Mac OS X',
        '/mac_powerpc/i' => 'Mac OS 9',
        '/linux/i' => 'Linux',
        '/ubuntu/i' => 'Ubuntu',
        '/iphone/i' => 'iPhone',
        '/ipod/i' => 'iPod',
        '/ipad/i' => 'iPad',
        '/android/i' => 'Android',
        '/blackberry/i' => 'BlackBerry',
        '/webos/i' => 'Mobile'
    );
    foreach ($os_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $os_platform = $value;
        }
    }
    $browser = "Unknown Browser";
    $browser_array = array(
        '/msie/i' => 'Internet Explorer',
        '/firefox/i' => 'Firefox',
        '/safari/i' => 'Safari',
        '/chrome/i' => 'Chrome',
        '/edge/i' => 'Edge',
        '/opera/i' => 'Opera',
        '/netscape/i' => 'Netscape',
        '/maxthon/i' => 'Maxthon',
        '/konqueror/i' => 'Konqueror',
        '/mobile/i' => 'Handheld Browser'
    );
    foreach ($browser_array as $regex => $value) {
        if (preg_match($regex, $user_agent)) {
            $browser = $value;
        }
    }

    $data['country'] = $country;
    $data['city'] = $city;
    $data['area'] = $area;
    $data['code'] = $code;
    $data['long'] = $long;
    $data['lat'] = $lat;
    $data['os_platform'] = $os_platform;
    $data['browser'] = $browser;
    $data['ip'] = request()->ip();
    $data['time'] = date('d-m-Y h:i:s A');

    return $data;
}


if (!function_exists('convertRate')) {
    function convertRate($currencyCode, $payout)
    {
        $convertRate = 0;
        $rate = optional($payout->method)->convert_rate;
        if ($rate) {
            $convertRate = $rate->$currencyCode;
        }
        return (float)$convertRate;
    }
}
if (!function_exists('stringToRouteName')) {
    function stringToRouteName($string)
    {
        $result = preg_replace('/[^a-zA-Z0-9]+/', '.', $string);
        return empty($result) || $result == '.' ? 'home' : $result;
    }
}
function browserIcon($string)
{
    $list = [
        "Unknown Browser" => "unknown",
        'Internet Explorer' => 'internetExplorer',
        'Firefox' => 'firefox',
        'Safari' => 'safari',
        'Chrome' => 'chrome',
        'Edge' => 'edge',
        'Opera' => 'opera',
        'Netscape' => 'netscape',
        'Maxthon' => 'maxthon',
        'Konqueror' => 'unknown',
        'UC Browser' => 'ucBrowser',
        'Safari Browser' => 'safari'];
    return $list[$string] ?? 'unknown';

}


function deviceIcon($string)
{
    $list = [
        'Tablet' => 'bi-laptop',
        'Mobile' => 'bi-phone',
        'Computer' => 'bi-display'];
    return $list[$string] ?? '';

}

if (!function_exists('timeAgo')) {
    function timeAgo($timestamp)
    {
        //$time_now = mktime(date('h')+0,date('i')+30,date('s'));
        $datetime1 = new DateTime("now");
        $datetime2 = date_create($timestamp);
        $diff = date_diff($datetime1, $datetime2);
        $timemsg = '';
        if ($diff->y > 0) {
            $timemsg = $diff->y . ' year' . ($diff->y > 1 ? "s" : '');

        } else if ($diff->m > 0) {
            $timemsg = $diff->m . ' month' . ($diff->m > 1 ? "s" : '');
        } else if ($diff->d > 0) {
            $timemsg = $diff->d . ' day' . ($diff->d > 1 ? "s" : '');
        } else if ($diff->h > 0) {
            $timemsg = $diff->h . ' hour' . ($diff->h > 1 ? "s" : '');
        } else if ($diff->i > 0) {
            $timemsg = $diff->i . ' minute' . ($diff->i > 1 ? "s" : '');
        } else if ($diff->s > 0) {
            $timemsg = $diff->s . ' second' . ($diff->s > 1 ? "s" : '');
        }
        if ($timemsg == "")
            $timemsg = "Just now";
        else
            $timemsg = $timemsg . ' ago';

        return $timemsg;
    }
}

if (!function_exists('code')) {
    function code($length)
    {
        if ($length == 0) return 0;
        $min = pow(10, $length - 1);
        $max = 0;
        while ($length > 0 && $length--) {
            $max = ($max * 10) + 9;
        }
        return random_int($min, $max);
    }
}


if (!function_exists('recursive_array_replace')) {
    function recursive_array_replace($find, $replace, $array)
    {
        if (!is_array($array)) {
            return str_ireplace($find, $replace, $array);
        }
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key] = recursive_array_replace($find, $replace, $value);
        }
        return $newArray;
    }
}

if (!function_exists('getHeaderMenuData')) {
    function getHeaderMenuData()
    {
        $menu = \Cache::get('headerMenu');
        if (!$menu) {
            $menu = ManageMenu::where('menu_section', 'header')->where('theme', basicControl()->theme)->first();
            \Cache::put('headerMenu', $menu);
        }
        $menuData = [];

        foreach ($menu->menu_items ?? [] as $key => $menuItem) {
            $pageDetails = getPageDetails($menuItem);

            if ($pageDetails->type == 1 && $pageDetails->name != 'Blog' && is_numeric($key)) {

                $cat_type = strtolower(str_replace(' ', '_', $pageDetails->name));

                $catData = \Cache::get('cat_data');
                if (!$catData) {
                    $catData = Category::where('status', 1)
                        ->orderBy('sort_by', 'asc')->get();
                    \Cache::put('cat_data', $catData);
                }
                $menuIDetails = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $menuItem,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($menuItem)),
                    'categories' => $catData->where('type', $cat_type)
                        ->map(function ($item) use ($cat_type) {
                            $item->search_url = ($cat_type == 'top_up') ? route('top-up', ['category' => $item->id]) : route('cards', ['category' => $item->id]);
                            return $item;
                        }),
                ];
            } elseif (is_numeric($key)) {

                $menuIDetails = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $menuItem,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($menuItem)),
                ];
            } elseif (is_array($menuItem)) {
                $child = getHeaderChildMenu($menuItem);
                $menuIDetails = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($key)),
                    'child' => $child
                ];
            }
            $menuData[] = $menuIDetails;
        }
        return $menuData;
    }
}

if (!function_exists('staticPagesAndRoutes')) {
    function staticPagesAndRoutes($name)
    {
        return [
                'blog' => 'blog',
            ][$name] ?? $name;
    }
}


if (!function_exists('getHeaderChildMenu')) {
    function getHeaderChildMenu($menuItem, $menuData = [])
    {
        foreach ($menuItem as $key => $item) {
            if (is_numeric($key)) {
                $pageDetails = getPageDetails($item);
                $menuData[] = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $item,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($item)),
                ];
            } elseif (is_array($item)) {
                $pageDetails = getPageDetails($key);
                $child = getHeaderChildMenu($item);
                $menuData[] = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $key,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($key)),
                    'child' => $child
                ];
            } else {
                $pageDetails = getPageDetails($key);
                $child = getHeaderChildMenu([$item]);
                $menuData[] = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $key,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($key)),
                    'child' => $child
                ];
            }
        }
        return $menuData;
    }
}


if (!function_exists('getPageDetails')) {
    function getPageDetails($name)
    {
        try {
            DB::connection()->getPdo();

            $sessionLang = session('lang') ?? auth()->user()->language_id;

            return \Cache::remember("page_details_{$name}", now()->addMinutes(30), function () use ($name) {
                $lang = session('lang');
                return Page::select('id', 'name', 'slug', 'custom_link', 'type', 'slug')
                    ->where('name', $name)
                    ->addSelect([
                        'page_name' => PageDetail::with('language')
                            ->select('name')
                            ->whereHas('language', function ($query) use ($lang) {
                                $query->where('short_name', $lang);
                            })
                            ->whereColumn('page_id', 'pages.id')
                            ->limit(1)
                    ])
                    ->first();
            });

        } catch (\Exception $e) {
            \Log::error("Error fetching page details: " . $e->getMessage());
            return null;
        }
    }
}

if (!function_exists('renderHeaderMenu')) {
    function renderHeaderMenu($menuItems, $isDropdown = false)
    {
        foreach ($menuItems as $menuItem) {
            $isActive = strtolower(getLastSegment()) == strtolower(basename($menuItem['route']));

            if (isset($menuItem['categories']) && count($menuItem['categories']) > 0) {
                echo '<li class="nav-item with-mega-menu">';
                echo '<a href="' . $menuItem['route'] . '" class="nav-link ' . ($isActive ? 'active' : '') . '">';
                echo $menuItem['name'];
                echo ' <i class="fa-solid fa-chevron-down headerIconCheev"></i>';
                echo '</a>';
                echo '<div class="mega-menu">';
                echo '<ul>';
                foreach ($menuItem['categories'] as $category) {
                    echo '<li>';
                    echo '<a href="' . $category['search_url'] . '" class="nav-link">';
                    echo '<div class="icon-box"><i class="' . $category['icon'] . '"></i></div>';
                    echo '<div class="text-box">' . $category['name'] . '<span>(' . $category['active_children'] . ')</span></div>';
                    echo '</a>';
                    echo '</li>';
                }
                echo '</ul>';
                echo '</div>';
                echo '</li>';
            } elseif (isset($menuItem['child']) && count($menuItem['child']) > 0) {
                echo '<li class="dropdown hover-dropdown p_relative">';
                echo '<a href="javascript:void(0);" class="' . ($isActive ? 'active' : '') . '">';
                echo $menuItem['name'];
                echo '</a>';
                echo '<ul>';
                renderHeaderMenu($menuItem['child']);
                echo '</ul>';
            } else {
                echo '<li class="nav-item">';
                echo '<a class="nav-link ' . ($isActive ? 'active' : '') . '" href="' . $menuItem['route'] . '">' . $menuItem['name'] . '</a>';
            }
            echo '</li>';
        }
    }
}

function getLastSegment()
{
    $currentUrl = url()->current();
    $lastSegment = last(explode('/', $currentUrl));
    return $lastSegment;
}


if (!function_exists('getFooterMenuData')) {
    function getFooterMenuData($type)
    {
        $menu = \Cache::get('footerMenu');
        if (!$menu) {
            $menu = ManageMenu::where('menu_section', 'footer')->where('theme', basicControl()->theme)->first();
            \Cache::put('footerMenu', $menu);
        }
        $menuData = [];

        if (isset($menu->menu_items[$type])) {
            foreach ($menu->menu_items[$type] as $key => $menuItem) {
                $pageDetails = getPageDetails($menuItem);
                $menuIDetails = [
                    'name' => $pageDetails->page_name ?? $pageDetails->name ?? $menuItem,
                    'route' => isset($pageDetails->slug) ? route('page', $pageDetails->slug) : ($pageDetails->custom_link ?? staticPagesAndRoutes($menuItem)),
                ];
                $menuData[] = $menuIDetails;
            }

            $flattenedMenuData = [];
            foreach ($menuData as $item) {

                $isActive = request()->url() == $item['route'] ? 'active ' : '';
                $che = '<li><a class="widget-link ' . $isActive . '" href="' . $item['route'] . '">' . $item['name'] . '</a></li>';
                $flattenedMenuData[] = $che;
            }

            return $flattenedMenuData;
        }

        return [];
    }
}

function getPageName($name)
{
    try {
        DB::connection()->getPdo();
        $defaultLanguage = Language::where('default_status', true)->first();
        $pageDetails = PageDetail::with(['page'])->select('id', 'page_id', 'name')
            ->with('page:id,name,slug')
            ->where('language_id', $defaultLanguage->id)
            ->whereHas('page', function ($query) use ($name) {
                $query->where('name', $name);
            })
            ->first();
        return $pageDetails->name ?? $pageDetails->page->name ?? $name;
    } catch (\Exception $e) {

    }
}


function filterCustomLinkRecursive($collection, $lookingKey = '')
{

    $filterCustomLinkRecursive = function ($array) use (&$filterCustomLinkRecursive, $lookingKey) {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = $filterCustomLinkRecursive($value);
            } elseif ($value === $lookingKey || $key === $lookingKey) {
                unset($array[$key]);
            }
        }
        return $array;
    };
    $filteredCollection = $filterCustomLinkRecursive($collection);

    return $filteredCollection;
}

if (!function_exists('maskString')) {
    function maskString($input)
    {
        $length = strlen($input);
        $visibleCharacters = 2;
        $maskedString = '<span class="masked ms-2">' . substr($input, 0, $visibleCharacters) . '<span class="highlight">' . str_repeat('*', $length - 2 * $visibleCharacters) . '</span>' . substr($input, -$visibleCharacters) . '</span>';
        return $maskedString;
    }
}

if (!function_exists('maskEmail')) {
    function maskEmail($email)
    {
        list($username, $domain) = explode('@', $email);
        $usernameLength = strlen($username);
        $visibleCharacters = 2;
        $maskedUsername = substr($username, 0, $visibleCharacters) . str_repeat('*', $usernameLength - 2 * $visibleCharacters) . substr($username, -$visibleCharacters);
        $maskedEmail = $maskedUsername . '@' . $domain;
        return $maskedEmail;
    }
}

if (!function_exists('removeValue')) {
    function removeValue(&$array, $value)
    {
        foreach ($array as $key => &$subArray) {
            if (is_array($subArray)) {
                removeValue($subArray, $value);
            } else {
                if ($subArray === $value) {
                    unset($array[$key]);
                }
            }
        }
    }
}


if (!function_exists('showActualPrice')) {
    function showActualPrice($service)
    {
        return getAmount($service->price - $service->getDiscount(), 2);
    }
}

if (!function_exists('showAmount')) {
    function showAmount($price)
    {
        if (session()->get('currency_rate') && session()->get('currency_code') && session()->get('currency_symbol')) {
            return round($price * session()->get('currency_rate'), 2);
        }
        return $price;
    }
}

if (!function_exists('calculateDiscountAmount')) {
    function calculateDiscountAmount($amount, $discount, $discountType)
    {
        $discountAmount = $discount;
        if ($discountType == 'percentage') {
            $discountAmount = ($discount * $amount) / 100;
        }

        return $discountAmount;
    }
}


if (!function_exists('formatNumber')) {
    function formatNumber($number)
    {
        if ($number >= 1000000) {
            return round($number / 1000000, 1) . 'M';
        } elseif ($number >= 1000) {
            return round($number / 1000, 1) . 'k';
        } else {
            return $number;
        }
    }
}

if (!function_exists('getGameLists')) {
    function getGameLists()
    {
        $topUps = TopUp::select(['id', 'name', 'image', 'status', 'sort_by'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->type = 'Direct Top Up';
                return $query;
            });

        $cards = Card::select(['id', 'name', 'image', 'status', 'sort_by'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->type = 'Card';
                return $query;
            });

        $combined = $topUps->concat($cards);
        return $combined;
    }
}

if (!function_exists('getFooterExtraData')) {
    function getFooterExtraData()
    {
        $extraInfo = ContentDetails::with(['content' => function ($query) {
            $query->whereIn('name', ['footer', 'social']);
        }])
            ->whereHas('content', function ($query) {
                $query->whereIn('name', ['footer', 'social']);
            })
            ->get()
            ->groupBy('content.name');

        return $extraInfo;
    }
}

if (!function_exists('adminAccessRoute')) {
    function adminAccessRoute($search)
    {
        $permissionLists = auth()->guard('admin')->user()->role->permission ?? null;
        if (!$permissionLists) {
            return true;
        }
        if (in_array(title2snake($search), $permissionLists)) {
            return true;
        }

        return false;
    }
}
if (!function_exists('getSocialData')) {
    function getSocialData()
    {
        $content = 'social';
        $contentData = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
            })
            ->get();
        $singleContent = $contentData->where('content.name', $content)->where('content.type', 'single')->first() ?? [];
        $multipleContents = $contentData->where('content.name', $content)->where('content.type', 'multiple')->values()->map(function ($multipleContentData) {
            return collect($multipleContentData->description)->merge($multipleContentData->content->only('media'));
        });
        $languages = Language::orderBy('name')->where('status', 1)->get();
        $currency = Currency::orderBy('sort_by', 'asc')->where('status', 1)->get();
        $activeCurrency = session('currency_code') ?? basicControl()->base_currency;

        $lang = new \App\Http\Middleware\Language();
        $code = $lang->getCode();
        $defaultLanguageCode = session('lang') ?? $code;;
        $defaultLanguage = $languages->where('short_name', $defaultLanguageCode)->first();
        return [
            'single' => $singleContent,
            'multiple' => $multipleContents,
            'language' => $languages,
            'defaultLanguage' => $defaultLanguage,
            'currency' => $currency,
            'activeCurrency' => $activeCurrency,
        ];
    }
}
if (!function_exists('displayStarRating')) {
    function displayStarRating($rating)
    {
        $fullStars = floor($rating);
        $decimalPart = $rating - $fullStars;

        $output = '';

        for ($i = 0; $i < $fullStars; $i++) {
            $output .= '<i class="active fa-solid fa-star"></i>';
        }

        if ($decimalPart > 0) {
            if ($decimalPart <= 0.5) {
                $output .= '<i class="active fa-solid fa-star-half-alt"></i>';
            } else {
                $output .= '<i class="active fa-solid fa-star"></i>';
            }
            $fullStars++;
        }

        $emptyStars = 5 - $fullStars;
        for ($i = 0; $i < $emptyStars; $i++) {
            $output .= '<i class="fa-solid fa-star"></i>';
        }

        return $output;
    }
}
if (!function_exists('displayStarRatingSection')) {
    function displayStarRatingSection($rating)
    {
        $fullStars = floor($rating);
        $decimalPart = $rating - $fullStars;

        $output = '<li>';

        for ($i = 0; $i < $fullStars; $i++) {
            $output .= '<i class="active fa-solid fa-star"></i>';
        }

        if ($decimalPart > 0) {
            if ($decimalPart <= 0.5) {
                $output .= '<i class="active fa-solid fa-star-half-alt"></i>';
            } else {
                $output .= '<i class="active fa-solid fa-star"></i>';
            }
            $fullStars++;
        }

        $emptyStars = 5 - $fullStars;
        for ($i = 0; $i < $emptyStars; $i++) {
            $output .= '<i class="fa-solid fa-star"></i>';
        }

        $output .= '</li>';

        return $output;
    }
}
if (!function_exists('footerData')) {
    function footerData()
    {
        $languages = \Cache::get("footer_language");
        if (!$languages || $languages->isEmpty()) {
            $languages = Language::all();
            \Cache::put('footer_language', $languages);
        }

        $language = new App\Http\Middleware\Language();
        $code = $language->getCode();
        $defaultLanguage = $languages->where('short_name', $code)->first();

        $contentDetails = \Cache::get("footer_content");
        if (!$contentDetails || $contentDetails->isEmpty()) {
            $contentDetails = ContentDetails::with('content')
                ->whereIn('content_id', Content::whereIn('name', ['footer'])->pluck('id'))
                ->get()
                ->groupBy(function ($item) {
                    return $item->content->name;
                });

            \Cache::put('footer_content', $contentDetails);
        }

        return prepareContentData($contentDetails->get('footer'), $languages, $defaultLanguage);
    }
}

if (!function_exists('prepareContentData')) {
    function prepareContentData($footerContents, $languages, $defaultLanguage)
    {
        if (is_null($footerContents)) {
            return [
                'single' => [],
                'multiple' => collect(),
                'languages' => $languages,
                'defaultLanguage' => $defaultLanguage,
            ];
        }

        $singleContent = $footerContents->where('content.name', 'footer')
            ->where('content.type', 'single')
            ->first();

        $multipleContents = $footerContents->where('content.name', 'footer')
            ->where('content.type', 'multiple')
            ->values()
            ->map(function ($content) {
                return collect($content->description)->merge($content->content->only('media'));
            });

        return [
            'single' => $singleContent ? collect($singleContent->description ?? [])->merge($singleContent->content->only('media')) : [],
            'multiple' => $multipleContents,
            'languages' => $languages,
            'defaultLanguage' => $defaultLanguage,
        ];
    }
}

if (!function_exists('getFirebaseFileName')) {
    function getFirebaseFileName()
    {
        return 'firebase-service.json';
    }
}

if (!function_exists('getTextColorClass')) {
    function getTextColorClass(): string
    {
        $theme = getTheme();
        $dashboard = auth()->user()->active_dashboard;
        $isUserRoute = Str::contains(request()->route()->getName(), 'user.');

        if ($theme == 'light' && $dashboard == 'daybreak' && $isUserRoute) {
            return 'text-dark';
        }
        if ($theme == 'dark' && $dashboard == 'daybreak' && $isUserRoute) {
            return 'text-dark';
        }
        if ($theme == 'light' && $dashboard == 'nightfall' && $isUserRoute) {
            return 'text-light';
        }
        if ($theme == 'dark' && $dashboard == 'nightfall' && $isUserRoute) {
            return 'text-light';
        }
        if ($theme == 'light' && !$isUserRoute) {
            return 'text-dark';
        }
        if ($theme == 'dark' && !$isUserRoute) {
            return 'text-light';
        }

        return '';
    }
}

PK     9S\.o     Http/Controllers/Admin/Admin.zipnu [        PK    |D<ZAA     !   AdminProfileSettingController.phpV[o0~`IN0<t@IN$6R1;Iܮj&~|.*qzrzHJ+!לiZ.,U{ ">j5-hF44&<겮[mW\;=QU$TwQsNsjѬ/REpZSVrdKհ[*ZShims$f@dzAX3f%2O[Ӈ/r
l@B\\=6\%R2j</Xt+{CQ[o7~o.r#3ٽDn<|yKj~`xR	D;{zXhGnw3YdiT$-*Ύ:>hCJ/ں&5)L+ӟLKZ ymc>\C)Z$DUWp:'Nq3]QItأqe-]9^_Zܹ Yg+X
.O:%dd=v?SwtO_akoG,F0JP3Tb\RqY%sqEpDݚ3 jgvU t )Hlq 4=b]B6a۝m|(L&WSDD+`$gߓa
,INU2QmRM\EPst
S]ІȔfVd:f>vcs0Ь!JMJ	Ll؇:ɻa?s}L6^,JoHs3`X6+3PNs5jl'0'n;}Z{p{k4[M+aq[]lRmoF2ޏ-@l
tqQ|C4-7;ByJ*781.8]w<?PK     9jZ               Auth/PK    ZfUhU)    "   Auth/ConfirmPasswordController.phpRj1W0'CI!`4RM$PKJԓju[T{xlj:IiuJ{^Gt.v4%#^퓮)O0~F;]y__1b	F# uk.¯0Ec0wrsΈ7kY=axoˠESm<6XwY&gV2	uI2)\оqXZջH5	!J<H8!Ț bDΠ?a[*	.c~UU<]6u2Lsdb"B#ag1\UozEikYDP7^S{}q~c}=\ȬGb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E
	
Z{}|i1."g3ɱc;i*M;뺴|8,ڊ;R!3_:e]n<br,ZV4T*恊WdONL)֕/3S6?ͩkuk+m7-/	X6l.[G̷bXeؐ%Ma=|OTfuhi`~
1<T^JNd$^\vMfw QITUxY(ȿ37_YO"?gb哘Gwxct?z)`AtkD<W)bj1+Z*^ep %I gv_Czhpk~JMk>0] :lDDQ\o߇:ZvnJg4_
/+f㺽svTA"`#j@MǅrJU ^]]6;\lVVVVVV4*/Ն       ΀X'_^Ŭz(ZSV2nY 
: cccvLXiK^LzAi)wˉE!&sǍe13uN	:NP4QdtdoPK?     |D<ZAA     ! $               AdminProfileSettingController.php
         Nq                PK?      9jZ             $          +  Auth/
         "O{                PK?     ZfUhU)    " $           N  Auth/ConfirmPasswordController.php
          9\                PK?     8v7Z    ! $           L  Auth/ForgotPasswordController.php
         "Hm                PK?     9jZT  S   $             Auth/LoginController.php
         "O{                PK?     8v7ZV9[ɱ  O    $           h  Auth/ResetPasswordController.php
          qHm                PK?     ZfU+  q   $           W  Auth/VerificationController.php
          9\                PK?     AcZۖi  Q   $           n  BasicControlController.php
         ^                PK?     e;ZN     $             BlogCategoryController.php
          +Dup                PK?     mZZ>V  ,   $           ?!  BlogController.php
         < D                PK?     |D<Z%](  )   $           )  ContentController.php
          ƽNq                PK?     cYb     $            0  CookiePolicyController.php
         zS                PK?     J6"Zx  #*   $           2  CurrencyController.php
         C\                PK?     @nY>5  :   $           7;  DashboardController.php
         0`[6                PK?     AjX^rv     $           F  EmailConfigController.php
         SYr                PK?     58'Z@Wݺ  n   $           NL  FirebaseConfigController.php
         
=`                PK?     jB^WF9     $           )P  GoogleApiSettingController.php
          
                PK?     F8YF
  6   $           R  KycController.php
         B}wZ                PK?     mZZf  H2   $           ]  LanguageController.php
          1'BD                PK?     nZZcJ  j   $           f  LogoController.php
          	VD                PK?     |D<Zc      $           Ui  MaintenanceModeController.php
         0Nq                PK?     r&Zk[=     $           Ul  ManageMenuController.php
         I5`                PK?     nZZdb[E  H+   $           r  ManualGatewayController.php
         `!iD                PK?      +eiZ             $          y  Module/
         ߐ                PK?     CYkY@5]     $           &y  Module/CampaignController.php
         P54                PK?     
,+[G!-  H   $           f}  Module/CardController.php
         I"                PK?     kpYb9  z<   $           '  Module/CardOrderController.php
         p>8                PK?     {X?  "  $ $           I  Module/CardServiceCodeController.php
          NK}q                PK?     
,+[[V  E8    $             Module/CardServiceController.php
         I"                PK?     9pYW,  '   $             Module/CategoryController.php
         0#67                PK?     6eY]\     $           е  Module/CouponController.php
         @W=/                PK?     kmpYИ  "   $           e  Module/ReviewController.php
         &t8                PK?     3fZSY65  g  % $             Module/SellPostCategoryController.php
         CcP                PK?     $4fZϵ  )    $             Module/SellSummaryController.php
         5P                PK?     
,+[1;  F   $             Module/TopUpController.php
         C"                PK?     D`jYƫ  5   $             Module/TopUpOrderController.php
         hW3                PK?     
,+[G&x  5  ! $             Module/TopUpServiceController.php
         C"                PK?     egXpU  k<  " $           _ NotificationTemplateController.php
          {p                PK?     nZZu
  CA   $           
 PageController.php
         p3=E                PK?     xopYPI  M   $           w PaymentLogController.php
         ༤8                PK?     XnZZS  z   $             PaymentMethodController.php
         BD                PK?     6=ZY
  1   $           ' PayoutLogController.php
          }	r                PK?     dnZZ7
  <   $           I2 PayoutMethodController.php
         `V͸D                PK?     &Xqγns     $           f= PluginController.php
          1A                PK?     _:WOl[!  n   $           B PusherConfigController.php
          _                PK?     
,+[-Br
  2   $           dD RolePermissionController.php
         C"                PK?     ELYIZg0  g   $           IO SellPostCategoryController.php
         yaV[                PK?     FpiZYʎ  
   $           a SmsConfigController.php
         `                PK?     ]Y"t  ^   $           g SocialiteController.php
         0N                PK?     ZcZ&  g   $           k StorageController.php
                          PK?     X0Yt0X  M   $           )q SubscribeController.php
                         PK?     `<Z2D
  -   $           t SupportTicketController.php
         Tgkq                PK?      GcZO  5   $           o TempleteController.php
         pQ	                PK?     x&Z  J   $           & TransactionLogController.php
         V/;`                PK?     liZKI  	  ! $            TranslateAPISettingController.php
         OW                PK?     KeZX"  =%  $           ` UsersController.php
          _                PK    8 8   9   PK     :S\A    Http/Controllers/AAdmin.zipnu [        PK
     "*[              Admin/UT	 *hAhux     PK    nZZcJ  j    Admin/LogoController.phpUT	 ag hux     ݖ]o0+|QɉV!.VV4!&vN㜦NW߱$]
l4	_TI\K$-	t&1r!Feҋ8eby>I9b
?rf'|W<#%SNF_$kPDQ~yGOuGQ5,[70rhF+&:EK?\	apc:0eR|!Yj;g|"m_TnY1r\(Asuav3$ KɵLB)ZBrɫ7SvA+aAXE˖CH
fރtnM9
0AX$ȬWPڮEv@gb]
(q\d"Y D"ŷI뜷Ӱ[NM	.c6Zv
-V۲*\B}!vپ5d`+dW_D̬}Jemyc$2"@y-OA	;oި?=*`'qVyQWuo+nH4'`?̣4O}zQ LԘe\~.03ٺخW`b5ـ>[j9uQ] "FS~@XMZJ;7PK    mZZf	  H2    Admin/LanguageController.phpUT	 aghux     Zo6=@6&|vܥEpٺX$ђxM{DJb;vrj|_~^glwgw'	gTdሒ7Yv/)˷i"yM41[f/iD|&<b儱j6THe,((g#>,+qǷ#AN"*Pᴻ3b<9%& We5Gd'#TIDo^,
IUR1lT<!71^闄}d*^dqߥֈS8K/1M<0Fi2'k%-x[UK-HXAQ!SN"r>_z+߾@pf?ƾG^ƜFwB8]dP6P$A0ۼ,&G.f䌅׌ŉApVA2DtLQ(,,(HgTົ39M,2ZجzUG?c?cF}-GW}^OE<C(i,4NY[
`-Ɵ,S4ZoN3P;LiOJOIr0To*wE^&<}ѽ
ŗC_HAk(m~&QHC`d&-еL"6ogu`xۇU>:Q#Iar3䔧sй醾w:D4dS:VE&ƨ2qB=׌V8s6F~aOW3ǯNoGȡ$
f Y^4G/ e]9ymE2 "`ri>|GGW iB%
_5@(!κ+B/wxYz(PGJ]P#}_XN# bgh?H$PkJKp	ѣ)/')4G:C/ %L ;Q8z[jUD	zƟk2N$ro;,:QƅMu_K7lbOgG(s8WGWBy4"}<mSpTl]k؁}Dͮ Zχő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!	{%m²PR)FǱ"(R-;fcmf0M,@~A'6JAAUx7q`_]DjP/V^R>pH<8Bqȓ1{	ߌup"AM%s7q D? QK#yj@_krpb7#XhYA->- sh][	&:".Uri],x\NȒ^XW}
dhʠ	V-eęXc<TKc9M;cE9^MO[:'=75-7lZ4+jy1b#tȝ~qѻz61V]jRZܐғ#VaO{D?"\YX$V:/8T_ "*wP,tNPK    48'Z@Wݺ  n  "  Admin/FirebaseConfigController.phpUT	 }ghux     VQo8~W$}=%rPҪTI68>ۡE'@X~}3h48]4 1\\8@.h4UcPHnh@C@ { W,+Xef(Jj(G_J-zԓDT)r$LaE$^5PbApdhs2a[QfjF3>ZS~e=/<a.Al"v*$Drbb[$<ȸ}A9DXQN8akc4m8?\шE\XMi8kBdkKIB? >O2W:t4	AAe(:_a9<T%PHX?y#"Qb5GxEt W,0qÏc4xlZ׿8JdTf4P:+s}߹S8r !{ 13~w}7z.Dr~4׽~{
1095s*B:Fw=Ϲn}t~8v4/x{ڎxw24c#p<+z_9wn7*Zex*IȌr/thlVŰYG-&Eh=V_~A }@=	fuv¶@X.gsnً\PI#$CNHluH7bSFkW.D|DPLfmɖT%y:om4Xљ	;sV~R	Ti;}	k	&~9c89Y ݍ_x1جޠ،fӁW4Ҕ|pUBa~ZXOm|oPK
     9jZ              Admin/Auth/UT	 g&$hux     PK    ZfUhU)    (  Admin/Auth/ConfirmPasswordController.phpUT	 gc!hux     SKO0Wia%vl_+
P*EB^{Xrl3gIXV|q}g&>&VW-4:9֧3R6:s^=&]PCfYw;w.bbrkM*] _;1`L=77%ctU*;ޤ&1O߄qllX$c>ٍCFy㬿8iӃdbBmZ&e8e#alyF@}EG$e C"`Q,ro .O9_Ve:p EFp5`נ/O_4VYcSI6X `^듓^;%56{=Ob9.X\M8	ׂ&ã1|h1wpJ}u_= PK    8v7Z    '  Admin/Auth/ForgotPasswordController.phpUT	 \g!hux     WmOFCHv8	^hJ=Wlv5IkՋ8y}ȋ=ɖh
"\'k{%VB6l䢴.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3/F#KP1/"- <XH9OЅjHmGOJom8RO>PDR3Ev_(g"kX&KM>'Ok+s"b@b_'3|&xt=ZGNdDV\JuixGmplxkc'ɜE2KMݬn)ӗ*7{L	z!יv<o@f-ӆJ+G3.䌤v}4rWysnwI-!m<N"=eCz1LBwsZXJS)J83,0i>/j	lehBʸrʼ]{HR
6 a'hmsoWZ/iuG]W2DcdE;
qޤdo
*`N8N$|"3.@+*h_Dx-etBYܭc3FQ;\bK!y6iS:ןnO_߲0uǃhp}=5Fhпތ.@[TTcД"c{D
:lsj&J8̬rDْv*ݎ%Jkx7!(A996%ڐjC[ΙMWm8N>^^Ԇ?zrjÎQ6XWm(!_o3!:lR_!4bӨ!UЩJQR?xuKb}U}f!9O-РS=<L +ME.B!b$TY)Kiޭ J!xElNNZ-k%Y;;rMG]#ˀQܑ/2g:N*
Q8M-kqPK
     "*[                     A    Admin/UT *hux     PK    nZZcJ  j           @   Admin/LogoController.phpUT agux     PK    mZZf	  H2           $  Admin/LanguageController.phpUT agux     PK    E8YFA  6             Admin/KycController.phpUT rgux     PK    XnZZ}  z  !           Admin/PaymentMethodController.phpUT bgux     PK    `<Z2
  -  !           Admin/SupportTicketController.phpUT gux     PK    \nYR8_
  2  "         )  Admin/RolePermissionController.phpUT '6gux     PK    "*[oN,b  )           D5  Admin/ContentController.phpUT *hux     PK    ZcZL  g           ;  Admin/StorageController.phpUT Hgux     PK    I6"Zx0	  #*           A  Admin/CurrencyController.phpUT z}vgux     PK    nZZu=  CA           "K  Admin/PageController.phpUT zcgux     PK    r&Zk[=!             V  Admin/ManageMenuController.phpUT H-|gux     PK    {D<Zc     #         *]  Admin/MaintenanceModeController.phpUT :ݘgux     PK    6=ZY
  1           Q`  Admin/PayoutLogController.phpUT gux     PK    @nY>  :           k  Admin/DashboardController.phpUT 5gux     PK    nZZdb[m  H+  !         w  Admin/ManualGatewayController.phpUT bgux     PK    e;ZN              V~  Admin/BlogCategoryController.phpUT Ɨgux     PK    egXpU)  k<  (           Admin/NotificationTemplateController.phpUT eux     PK    &Xqγn             C  Admin/PluginController.phpUT fux     PK    AcZۖ  Q            )  Admin/BasicControlController.phpUT gux     PK    X0Yt0X  M           2  Admin/SubscribeController.phpUT Ifux     PK    {D<ZAA     '         /  Admin/AdminProfileSettingController.phpUT :ݘgux     PK    wopYPֹ  M             Admin/PaymentLogController.phpUT 8gux     PK    mZZ>  ,             Admin/BlogController.phpUT agux     PK    x&Z  J  "           Admin/TransactionLogController.phpUT 8|gux     PK    liZKI  	  '         з  Admin/TranslateAPISettingController.phpUT gux     PK    FcZO  5           B  Admin/TempleteController.phpUT gux     PK    _:WOl[%  n               Admin/PusherConfigController.phpUT Jeux     PK
     {*[                     A  Admin/Module/UT Ahux     PK    6eY]    !           Admin/Module/CouponController.phpUT *gux     PK    {*[G!-  H             Admin/Module/CardController.phpUT Ahux     PK    <pYyk  5  '         8  Admin/Module/TopUpServiceController.phpUT ȑ8gux     PK    "apYWz	L  D8  &         n  Admin/Module/CardServiceController.phpUT 8gux     PK    #4fZ  )  &           Admin/Module/SellSummaryController.phpUT gux     PK    A=pY*  F            l  Admin/Module/TopUpController.phpUT 8gux     PK    kpYb9L  z<  $          Admin/Module/CardOrderController.phpUT 8gux     PK    CYkY@5]"    #          Admin/Module/CampaignController.phpUT ^,2gux     PK    jmpYИ.  "  !          Admin/Module/ReviewController.phpUT 8gux     PK    {X?:  "  *          Admin/Module/CardServiceCodeController.phpUT Bfux     PK    C`jY  5  %         @' Admin/Module/TopUpOrderController.phpUT 0gux     PK    9pYW,/	  '  #         3 Admin/Module/CategoryController.phpUT N8gux     PK    3fZSY6  g  +         2= Admin/Module/SellPostCategoryController.phpUT `gux     PK    jB^WFA    $         P Admin/GoogleApiSettingController.phpUT H?eux     PK    KeZX$  =%          HS Admin/UsersController.phpUT _gux     PK    EpiZYʎ  
           *x Admin/SmsConfigController.phpUT gux     PK    
AjX^r             ~ Admin/EmailConfigController.phpUT eux     PK    ELYIZg  g  $         u Admin/SellPostCategoryController.phpUT  tgux     PK    dnZZ7E  <            ߗ Admin/PayoutMethodController.phpUT bgux     PK    cYb              ~ Admin/CookiePolicyController.phpUT fgux     PK    48'Z@Wݺ  n  "          Admin/FirebaseConfigController.phpUT }gux     PK
     9jZ                     A Admin/Auth/UT gux     PK    ZfUhU)    (          Admin/Auth/ConfirmPasswordController.phpUT gcux     PK    8v7Z    '          Admin/Auth/ForgotPasswordController.phpUT \gux     PK    ZfU+  q  %         ! Admin/Auth/VerificationController.phpUT gcux     PK    9jZTB  S           ] Admin/Auth/LoginController.phpUT gux     PK    8v7ZV9[  O  &          Admin/Auth/ResetPasswordController.phpUT \gux     PK    ]Y"t  ^            Admin/SocialiteController.phpUT ]gux     PK    9 9   Q   PK     :S\cJj  j  *  Http/Controllers/AAdmin/LogoController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Traits\Upload;

class LogoController extends Controller
{
    use Upload;

    public function logoSetting()
    {
        $basicControl = basicControl();
        return view('admin.control_panel.logo', compact('basicControl'));
    }

    public function logoUpdate(Request $request)
    {

        $request->validate([
            'logo' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
            'favicon' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
            'admin_logo' => 'sometimes|required|mimes:jpg,png,jpeg|max:10240',
        ]);

        $basicControl = basicControl();
        if ($request->hasFile('logo')) {
            try {
                $image = $this->fileUpload($request->logo, config('filelocation.logo.path'), null, null,'webp', 60, $basicControl->logo, $basicControl->logo_driver);
                if ($image) {
                    $basicControl->logo = $image['path'];
                    $basicControl->logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Logo could not be uploaded.');
            }
        }

        if ($request->hasFile('favicon')) {
            try {
                $image = $this->fileUpload($request->favicon, config('filelocation.logo.path'), null, null, 'webp', 60, $basicControl->favicon,$basicControl->favicon_driver);
                if ($image) {
                    $basicControl->favicon = $image['path'];
                    $basicControl->favicon_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Favicon could not be uploaded.');
            }
        }

        if ($request->hasFile('admin_logo')) {
            try {
                $image = $this->fileUpload($request->admin_logo, config('filelocation.logo.path'), null, null, 'webp', 60,$basicControl->admin_logo, $basicControl->admin_logo_driver);
                if ($image) {
                    $basicControl->admin_logo = $image['path'];
                    $basicControl->admin_logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Admin Logo could not be uploaded.');
            }
        }

        if ($request->hasFile('admin_dark_mode_logo')) {
            try {
                $image = $this->fileUpload($request->admin_dark_mode_logo, config('filelocation.logo.path'), null, null, 'webp', 60,$basicControl->admin_dark_mode_logo,$basicControl->admin_dark_mode_logo_driver);
                if ($image) {
                    $basicControl->admin_dark_mode_logo = $image['path'];
                    $basicControl->admin_dark_mode_logo_driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Admin Logo could not be uploaded.');
            }
        }

        $basicControl->save();

        return back()->with('success', 'Logo, favicon and breadcrumb has been updated.');

    }

}
PK     :S\fH2  H2  .  Http/Controllers/AAdmin/LanguageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use Illuminate\Http\Request;
use App\Traits\Upload;
use Facades\App\Services\LocalizationService;
use Exception;
use Facades\App\Services\Translate\BaseTranslateService;

class LanguageController extends Controller
{
    use Upload;

    public function index()
    {
        $languages = Language::all();
        return view('admin.language.list', compact('languages'));
    }

    public function create()
    {
        $shortNames = config('languages.langCode');
        return view('admin.language.create', compact('shortNames'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:languages,name',
            'short_name' => 'required|string|max:3|unique:languages,short_name',
            'rtl' => 'nullable|integer|in:0,1',
            'status' => 'nullable|integer|in:0,1',
            'default_lang' => 'nullable|integer|in:0,1',
            'flag' => ' sometimes|required|mimes:jpg,png,jpeg|max:10240',
        ]);

        try {
            if ($request->file('flag') && $request->file('flag')->isValid()) {
                $image = $this->fileUpload($request->flag, config('filelocation.language.path'), null, null, 'webp', 60);
                if ($image) {
                    $flagImage = $image['path'];
                    $driver = $image['driver'] ?? 'local';
                }
            }

            $response = Language::create([
                'name' => $request->name,
                'short_name' => $request->short_name,
                'status' => $request->status,
                'rtl' => $request->rtl,
                'default_status' => $request->default_lang,
                'flag' => $flagImage ?? null,
                'flag_driver' => $driver ?? 'local'
            ]);

            if (!$response) {
                throw new Exception('Something went wrong while storing language. Please try again later.');
            }

            LocalizationService::createLang(defaultLang()->short_name, $request->short_name);

            if ($response->default_status == 1) {
                session()->put('lang', $response->short_name);
                session()->put('rtl', $response ? $response->rtl : 0);
                Language::whereNotIn('id', [$response->id])->get()->map(function ($item) {
                    $item->default_status = 0;
                    $item->save();
                });
            }
            return redirect()->route('admin.language.index')->with('success', "`{$response->name}` language has been created successfully.");
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit($id)
    {
        try {
            $language = Language::where('id', $id)->firstOr(function () {
                throw new Exception('No Language found.');
            });

            $shortNames = config('languages.langCode');
            return view('admin.language.edit', compact('language', 'shortNames'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:100|unique:languages,name,' . $id,
            'short_name' => 'required|string|max:3|unique:languages,short_name,' . $id,
            'rtl' => 'nullable|integer|in:0,1',
            'status' => 'nullable|integer|in:0,1',
            'default_lang' => 'nullable|integer|in:0,1',
            'flag' => 'sometimes|required|mimes:jpg,png,jpeg,svg|max:10240',
        ]);

        try {
            $language = Language::where('id', $id)->firstOr(function () {
                throw new \Exception('No Language found.');
            });

            $oldShortName = $language->short_name;

            if ($request->file('flag') && $request->file('flag')->isValid()) {
                $image = $this->fileUpload($request->flag, config('filelocation.language.path'), null, null, 'webp', 60, $language->flag, $language->flag_driver);
                if ($image) {
                    $flagImage = $image['path'];
                    $flagDriver = $image['driver'];
                }
            }

            $response = $language->update([
                'name' => $request->name,
                'short_name' => $request->short_name,
                'status' => $request->status,
                'rtl' => $request->rtl,
                'flag' => $flagImage ?? $language->flag,
                'flag_driver' => $flagDriver ?? $language->flag_driver,
                'default_status' => $request->default_lang == 1 ? 1 : 0,
            ]);

            if (!$response) {
                throw new Exception('Something went wrong. Please try again later.');
            }

            LocalizationService::renameLang($oldShortName, $language->short_name);

            if ($language->default_status == 1) {
                session()->put('lang', $language->short_name);
                session()->put('rtl', $language ? $language->rtl : 0);
                Language::whereNotIn('id', [$language->id])->get()->map(function ($item) {
                    $item->default_status = 0;
                    $item->save();
                });
            }

            return back()->with('success', "`{$language->name}` language has been updated successfully");

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    function destroy(Request $request, $id)
    {
        try {
            $language = Language::where(['id' => $id, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you had selected default language.');
            });

            if (strtolower($language->short_name) != 'en') {
                $language->notificationTemplates()->delete();
                $language->pageDetails()->delete();
                $language->contentDetails()->delete();
                $response = $language->delete();
            }

            throw_if(!$response, 'Something went wrong. Please try again later.');
            LocalizationService::deleteLang($language->short_name);
            return back()->with('success', "`{$language->name}` language has been deleted successfully.");
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function keywords($shortName)
    {
        try {
            $language = Language::where('short_name', $shortName)->firstOr(function () {
                throw new \Exception('No Language found.');
            });
            $languages = Language::all();
            $keywords = json_decode(file_get_contents(resource_path('lang/') . strtolower($shortName) . '.json'));
            $pageTitle = $language->name . " Language Keyword";
            return view('admin.language.keywords', compact('language', 'keywords', 'languages', 'pageTitle'));
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function addKeyword(Request $request, $shortName)
    {
        $this->validate($request, [
            'key' => 'required|string|min:1|max:100',
            'value' => 'required|string|min:1|max:100'
        ], [
            'required' => 'This field is required.',
            'string' => 'This field must be string.'
        ]);
        try {
            $response = LocalizationService::updateLangKeyword($shortName, $request->key, $request->value);

            throw_if(!$response, 'Something went wrong. Please try again later.');

            session()->flash('success', "`{$request->key}` keyword has been added successfully.");
        } catch (\Exception $exception) {
            session()->flash('error', $exception->getMessage());
        }
        return response()->json(['url' => route('admin.language.keywords', $shortName)]);
    }


    public function updateKeyword(Request $request, $shortName, $key)
    {
        $this->validate($request, [
            'value' => 'required|string'
        ], [
            'required' => 'This field is required.',
            'string' => 'This field must be string.'
        ]);

        try {
            $key = urldecode($key);
            $routeName = request()->route()->getName();
            $default = $routeName == 'admin.update.language.default.keyword' ? true : false;
            $response = LocalizationService::updateLangKeyword($shortName, $key, $request->value, $default);
            throw_if(!$response, 'Something went wrong. Please try again later.');
            session()->flash('success', "`{$key}` keyword has been updated successfully.");
        } catch (\Exception $exception) {
            session()->flash('alert', $exception->getMessage());
        }
        return response()->json(['url' => route('admin.language.keywords', $shortName)]);
    }

    public function deleteKeyword($shortName, $key)
    {
        try {
            $key = urldecode($key);
            $response = LocalizationService::deleteLangKeyword($shortName, $key);

            throw_if(!$response, 'Something went wrong. Please try again later.');
            return back()->with('success', "`{$key}` keyword has been deleted successfully.");
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }


    public function importJson(Request $request)
    {
        try {
            $myLang = Language::where(['id' => $request->my_lang, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you selected default language.');
            });

            $lang = Language::findOrFail($request->lang_id);
            $json = file_get_contents(resource_path('lang/') . $lang->short_name . '.json');
            $jsonArray = json_decode($json, true);

            file_put_contents(resource_path('lang/') . $myLang->short_name . '.json', json_encode($jsonArray));
            return back()->with('success', 'Import data successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function changeStatus($id)
    {
        try {
            $language = Language::where(['id' => $id, 'default_status' => false])->firstOr(function () {
                throw new \Exception('No language found or may be you selected default language.');
            });

            $response = $language->update([
                'status' => !$language->status
            ]);

            throw_if(!$response, 'Something went wrong. Please try again later.');

            $status = $language->status == 1 ? 'activated' : 'deactivated';
            return back()->with('success', "`{$language->name}` language has been {$status} successfully.");
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function singleKeywordTranslate(Request $request)
    {
        $shortName = $request->shortName;
        $key = $request->key;
        $singleTranslatedText = BaseTranslateService::singleKeywordTranslated($shortName, $key);

        $path = resource_path("lang/{$shortName}.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }

        $contents[$key] = $singleTranslatedText;
        file_put_contents($path, stripslashes(json_encode($contents, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)));
        return response([
            'message' => 'Keyword Translation Successfully.',
            'translatedText' => $singleTranslatedText
        ]);
    }

    public function allKeywordTranslate(Request $request, $shortName)
    {
        $allTranslatedText = BaseTranslateService::textTranslate($shortName);
        $path = resource_path("lang/{$shortName}.json");
        if (file_exists($path)) {
            $contents = json_decode(file_get_contents($path), true);
        }
        $mergedTranslations = array_merge($contents, $allTranslatedText);
        file_put_contents($path, json_encode($mergedTranslations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
        return back()->with('success', 'Keyword Translation Successfully.');
    }
}
PK     :S\F6  6  )  Http/Controllers/AAdmin/KycController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Kyc;
use App\Models\UserKyc;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Exception;
use Yajra\DataTables\Facades\DataTables;

class KycController extends Controller
{

    use Notify;

    public function index()
    {
        $data['kycList'] = Kyc::get();
        return view('admin.kyc.list', $data);
    }

    public function create()
    {
        return view('admin.kyc.create');
    }

    public function store(Request $request)
    {
        $requestData = $request->all();
        $rules = [
            'name' => 'required|string',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
        ];

        $validator = Validator::make($requestData, $rules, $customMessages);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $inputForm = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_label'] = ucwords($request->field_name[$a]);
                    $arr['type'] = $request->input_type[$a];
                    $arr['validation'] = $request->is_required[$a];
                    $inputForm[$arr['field_name']] = $arr;
                }
            }

            $kyc = Kyc::create([
                'name' => $request->name,
                'slug' => Slug($request->name),
                'input_form' => $inputForm,
                'status' => $request->status
            ]);

            if (!$kyc) {
                throw new Exception('something went wrong, Please try again');
            }

            return back()->with('success', 'KYC Store successfully');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function edit($id)
    {
        try {
            $data['kyc'] = Kyc::where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });

            return view('admin.kyc.edit', $data);

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

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

        $requestData = $request->all();
        $rules = [
            'name' => 'required|string',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
        ];

        $validator = Validator::make($requestData, $rules, $customMessages);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {

            $inputForm = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_label'] = ucwords($request->field_name[$a]);
                    $arr['type'] = $request->input_type[$a];
                    $arr['validation'] = $request->is_required[$a];
                    $inputForm[$arr['field_name']] = $arr;
                }
            }

            $kyc = Kyc::where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });

            $kyc->update([
                'name' => $request->name,
                'slug' => slug($request->name),
                'input_form' => $inputForm,
                'status' => $request->status
            ]);

            if (!$kyc) {
                throw new Exception('Something went wrong');
            }

            return back()->with('success', 'KYC updated successfully');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function userKycList($status = 'all')
    {

        $userKYCRecord = \Cache::get('userKYCRecord');
        if (!$userKYCRecord){
            $userKYCRecord = UserKyc::selectRaw('COUNT(id) AS totalKYC')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingKYCPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvedKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvedKYCPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS rejectedKYC')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS rejectedKYCPercentage')
                ->get()
                ->toArray();
            \Cache::put('userKYCRecord', $userKYCRecord);
        }
        return view('admin.kyc.user_kyc', compact('status', 'userKYCRecord'));
    }

    public function userKycSearch(Request $request, $status = 'all')
    {
        $filterVerificationType = $request->filterVerificationType;
        $filterStatus = $request->filterStatus;
        $search = $request->search['value']??null;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $userKyc = UserKyc::query()->with(['user:id,username,firstname,lastname,image,image_driver'])
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('kyc_type', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%");
                            $q->orWhere('lastname', 'LIKE', "%$search%");
                            $q->orWhere('username', 'LIKE', "%$search%");
                            $q->orWhere('email', 'LIKE', "%$search%");
                        });
                });
            })
            ->when($status == 'all', function ($query) {
                return $query->whereIn('status', [0, 1, 2]);
            })
            ->when($status == 'pending', function ($query) {
                return $query->whereStatus(0);
            })
            ->when($status == 'approve', function ($query) {
                return $query->whereStatus(1);
            })
            ->when($status == 'rejected', function ($query) {
                return $query->whereStatus(2);
            })
            ->when(!empty($filterVerificationType), function ($query) use ($filterVerificationType) {
                return $query->where('kyc_type', $filterVerificationType);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($userKyc)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('verification type', function ($item) {
                return $item->kyc_type;
            })
            ->addColumn('status', function ($item) {
                $statusLabels = [
                    0 => '<span class="badge bg-soft-warning text-warning">
                            <span class="legend-indicator bg-warning"></span> ' . trans('Pending') . '
                        </span>',
                    1 => '<span class="badge bg-soft-success text-success">
                            <span class="legend-indicator bg-success"></span> ' . trans('Verified') . '
                        </span>',
                    2 => '<span class="badge bg-soft-danger text-danger">
                            <span class="legend-indicator bg-danger"></span> ' . trans('Rejected') . '
                        </span>'
                ];
                return isset($statusLabels[$item->status]) ? $statusLabels[$item->status] : '';
            })
            ->addColumn('action', function ($item) {
                $url = route('admin.kyc.view', $item->id);
                return '<a class="btn btn-white btn-sm" href="' . $url . '">
                      <i class="bi-eye"></i> ' . trans("View") . '
                    </a>';
            })
            ->rawColumns(['name', 'status', 'action'])
            ->make(true);
    }

    public function view($id)
    {
        try {
            $data['userKyc'] = UserKyc::with('user')->where('id', $id)->firstOr(function () {
                throw new Exception('No KYC found.');
            });
            return view('admin.kyc.view', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function action(Request $request, $id)
    {
        $req = $request->except('_token', '_method');
        $rules = [
            'rejected_reason' => 'sometimes|required|string|min:3',
            'status' => 'nullable|integer|in:0,1,2'
        ];

        $validator = Validator::make($req, $rules);
        if ($validator->fails()) {
            $newArr = $validator->getMessageBag();
            $newArr->add('rejectedMessage', 1);
            return back()->withErrors($newArr)->withInput();
        }

        try {
            $userKyc = UserKyc::findOrFail($id);
            if ($request->status == 1) {
                $userKyc->status = 1;
                $userKyc->approved_at = now();
                $message = 'Approved Successfully';
                $this->userSendMailNotify($userKyc->user, 'approve');
            } elseif ($request->status == 2) {
                $userKyc->status = 2;
                $userKyc->reason = $request->rejected_reason;
                $message = 'Rejected Successfully';
                $this->userSendMailNotify($userKyc->user, 'reject');
            }

            $userKyc->save();
            return back()->with('success', $message);

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function userSendMailNotify($user, $type)
    {
        if ($type == 'approve') {
            $templateKey = 'KYC_APPROVED';
        } else {
            $templateKey = 'KYC_REJECTED';
        }
        $action = [
            "link" => "#",
            "icon" => "fa-light fa-address-book"
        ];
        $this->sendMailSms($user, $templateKey);
        $this->userPushNotification($user, $templateKey, $action);
        $this->userFirebasePushNotification($user, $templateKey);
        return 0;
    }

    public function kycIsMandatory(Request $request){


        $validated = $request->validate([
            'kycMandatory' => 'required',
        ]);

        $setting = basicControl();
        $setting->isKycMandatory = $validated['kycMandatory'];
        $setting->save();

        return response()->json([
            'success' => true,
            'message' => 'KYC status updated successfully.',
            'currentStatus' => $setting->isKycMandatory
        ]);
    }
}
PK     :S\z  z  3  Http/Controllers/AAdmin/PaymentMethodController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Gateway;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Validator;

class PaymentMethodController extends Controller
{
    use Upload;

    public function index()
    {
        $data['paymentGateways'] = Gateway::automatic()->orderBy('sort_by', 'ASC')->get();
        return view('admin.payment_methods.list', $data);
    }

    public function sortPaymentMethods(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Gateway::where('code', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function edit($id)
    {
        try {
            $data['basicControl'] = basicControl();
            $data['method'] = Gateway::findOrFail($id);
            return view('admin.payment_methods.edit', $data);
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|string',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.name' => 'required|string',
            'receivable_currencies.*.currency_symbol' => 'required|string|max:255',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'description' => 'required|string|min:3',
            'is_active' => 'nullable|integer|in:0,1',
            'test_environment' => 'sometimes|required|string|in:test,live',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'receivable_currencies.*.currency_symbol.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $gateway = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception('No payment method found');
        });

        $parameters = [];
        foreach ($request->except('_token', '_method', 'image') as $k => $v) {
            foreach ($gateway->parameters as $key => $cus) {
                if ($k != $key) {
                    continue;
                } else {
                    $rules[$key] = 'required';
                    $parameters[$key] = $v;
                }
            }
        }

        $validator = Validator::make($request->all(), $rules, $customMessages);

        if ($validator->fails()) {
            $names = collect(request()->receivable_currencies)
                ->filter(function ($item) {
                    return isset($item['name']) && $item['name'] !== null;
                })
                ->pluck('name')
                ->toArray();
            return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput($request->input())
                ->with('selectedCurrencyList', $names);
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 70, $gateway->image, $gateway->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $collection = collect($request->receivable_currencies);
            $supportedCurrency = $collection->pluck('name')->all();
            $response = $gateway->update([
                'name' => $request->name,
                'supported_currency' => $supportedCurrency,
                'receivable_currencies' => $request->receivable_currencies,
                'description' => $request->description,
                'parameters' => $parameters,
                'image' => $gatewayImage ?? $gateway->image,
                'driver' => $driver ?? $gateway->driver,
                'environment' => $request->test_environment ?? null,
                'status' => $request->is_active
            ]);

            if (!$response) {
                throw new \Exception('Unexpected error! Please try again.');
            }
            return back()->with('success', 'Gateway data has been updated.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }


    public function deactivate(Request $request)
    {
        try {
            $gateway = Gateway::where('code', $request->code)->firstOrFail();
            $gateway->update([
                'status' => $gateway->status == 1 ? 0 : 1
            ]);
            return back()->with('success', 'Gateway status updated successfully.');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     :S\2-  -  3  Http/Controllers/AAdmin/SupportTicketController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SupportTicket;
use App\Models\SupportTicketAttachment;
use App\Models\SupportTicketMessage;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Exception;
use App\Traits\Upload;
use App\Traits\Notify;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class SupportTicketController extends Controller
{
    use Upload, Notify;

    public function tickets($status = 'all')
    {
        $ticketRecord = \Cache::get('ticketRecord');
        if (!$ticketRecord) {
            $ticketRecord = SupportTicket::selectRaw('COUNT(id) AS totalTicket')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS openTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS openTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS answerTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS answerTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS repliedTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS repliedTicketPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS closedTicket')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS closedTicketPercentage')
                ->get()
                ->toArray();
            \Cache::put('ticketRecord', $ticketRecord);
        }
        return view('admin.support_ticket.list', compact('status', 'ticketRecord'));
    }


    public function ticketSearch(Request $request)
    {

        $filterSubject = $request->subject;
        $filterStatus = $request->filterStatus;
        $search = $request->search['value'];
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $supportTicket = SupportTicket::query()->with('user:id,username,firstname,lastname,image,image_driver')
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('subject', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%");
                            $q->orWhere('lastname', 'LIKE', "%$search%");
                            $q->orWhere('username', 'LIKE', "%$search%");
                            $q->orWhere('email', 'LIKE', "%$search%");
                        });
                });
            })
            ->when(!empty($filterSubject), function ($query) use ($filterSubject) {
                return $query->where('subject', $filterSubject);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });

        return DataTables::of($supportTicket)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('username', function ($item) {
                $url = route("admin.user.edit", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('subject', function ($item) {
                return Str::limit($item->subject, 30);

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return ' <span class="badge bg-soft-warning text-warning">
                                    <span class="legend-indicator bg-warning"></span> ' . trans('Open') . '
                                </span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                                    <span class="legend-indicator bg-success"></span> ' . trans('Answered') . '
                                </span>';

                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-info text-info">
                                    <span class="legend-indicator bg-info"></span> ' . trans('Customer Reply') . '
                                </span>';

                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">
                                    <span class="legend-indicator bg-danger"></span> ' . trans('Closed') . '
                                </span>';
                }
            })
            ->addColumn('lastReply', function ($item) {
                return dateTime($item->last_reply);
            })
            ->addColumn('action', function ($item) {
                $url = route('admin.ticket.view', $item->id);
                return '<a class="btn btn-white btn-sm" href="' . $url . '">
                      <i class="bi-eye"></i> ' . trans("View") . '
                    </a>';
            })
            ->rawColumns(['username', 'subject', 'status', 'action'])
            ->make(true);
    }


    public function ticketView($id)
    {
        $data['ticket'] = SupportTicket::where('id', $id)->with('user', 'messages')->firstOrFail();
        $data['title'] = "Ticket #" . $data['ticket']->ticket;
        return view('admin.support_ticket.view', $data);
    }


    public function ticketReplySend(Request $request, $id)
    {
        $request->validate([
            'message' => 'required|string',
        ]);

        DB::beginTransaction();
        try {
            $admin = Auth::guard('admin')->user();

            $ticketRes = SupportTicket::where('id', $id)->firstOr(function () {
                throw new \Exception('No data found!');
            });

            $ticketRes->update([
                'last_reply' => Carbon::now(),
                'status' => 1,
            ]);

            if (!$ticketRes) {
                DB::rollBack();
                throw new Exception('Something went wrong while updating data.');
            }

            $resTicketDetails = SupportTicketMessage::create([
                'support_ticket_id' => $id,
                'admin_id' => $admin->id,
                'message' => $request->message,
            ]);

            if (!$resTicketDetails) {
                DB::rollBack();
                throw new Exception('Something went wrong while updating data.');
            }

            if (!empty($request->attachments)) {
                $attachments = [];
                $numberOfAttachments = count($request->attachments);

                for ($i = 0; $i < $numberOfAttachments; $i++) {
                    if ($request->hasFile('attachments.' . $i)) {
                        $file = $request->file('attachments.' . $i);
                        $supportFile = $this->fileUpload($file, config('filelocation.ticket.path'), null, null, 'webp', null);
                        if (empty($supportFile['path'])) {
                            throw new Exception('File could not be uploaded.');
                        }
                        $attachments[] = [
                            'support_ticket_message_id' => $resTicketDetails->id,
                            'file' => $supportFile['path'],
                            'driver' => $supportFile['driver'] ?? 'local',
                        ];
                    }
                }
            }

            if (!empty($attachments)) {
                $attachmentResponse = DB::table('support_ticket_attachments')->insert($attachments);
                if (!$attachmentResponse) {
                    DB::rollBack();
                    throw new Exception('Something went wrong while storing attachments. Please try again later.');
                }
            }

            DB::commit();

            $msg = [
                'ticket_id' => $ticketRes->ticket
            ];
            $action = [
                "link" => route('user.ticket.view', $ticketRes->ticket),
                "icon" => "fas fa-ticket-alt text-white"
            ];

            $this->userPushNotification($ticketRes->user, 'ADMIN_REPLIED_TICKET', $msg, $action);
            $this->userFirebasePushNotification($ticketRes->user, 'ADMIN_REPLIED_TICKET', $msg, $action);
            $this->sendMailSms($ticketRes->user, 'ADMIN_REPLIED_TICKET', [
                'ticket_id' => $ticketRes->ticket,
                'ticket_subject' => $ticketRes->subject,
                'reply' => $request->message,
            ]);

            return back()->with('success', "Ticket has been replied");

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }

    }

    public function ticketClosed($id)
    {
        $ticket = SupportTicket::findOrFail($id);
        $ticket->update([
            'status' => 3
        ]);
        return back()->with('success', "Ticket has been closed");
    }

    public function ticketDownload($ticket_id)
    {
        $attachment = SupportTicketAttachment::with('supportMessage', 'supportMessage.ticket')->findOrFail(decrypt($ticket_id));
        $file = $attachment->file;
        $full_path = getFile($attachment->driver, $file);
        $title = slug($attachment->supportMessage->ticket->subject) . '-' . $file;
        header('Content-Disposition: attachment; filename="' . $title);
        header("Content-Type: " . $full_path);
        return readfile($full_path);
    }


}
PK     :S\R8_2  2  4  Http/Controllers/AAdmin/RolePermissionController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTables;

class RolePermissionController extends Controller
{
    protected $admin;
    public function editStaff($id)
    {
        $staff = Admin::findOrFail($id);
        $roles = Role::where('status',1)->get();
        return view('admin.manage_staff.edit',compact('staff','roles'));
    }
    public function staffUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => ['required',Rule::exists('admins', 'id')],
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users', 'email')->ignore($request->id)],
            'username' => ['required', 'string', 'max:50', Rule::unique('admins', 'username')->ignore($request->id)],
            'role' => ['required'],
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->messages()], 422);
        }

        $user = Admin::findOrFail($request->id);
        $user->name = $request->name;
        $user->email = $request->email;
        $user->username = $request->username;
        $user->role_id = $request->role;
        $user->status = $request->status?1:0;
        if ($request->password){
            $user->password = Hash::make($request->password);
        }
        $user->save();
        session()->flash('success', 'User Updated Successfully');
        return redirect()->route('admin.role.staff');
    }

   public function index()
   {
       return view('admin.role_permission.index');
   }

    public function getRoleList(Request $request)
    {
        $roles = Role::query()
            ->when(!empty($request->search['value']),function ($query) use ($request){
                $query->where('name','LIKE','%'.$request->search['value'].'%');
            })
            ->orderBy('id', 'desc');

        return DataTables::of($roles)
            ->addColumn('no',function ($item){
                static $counter = 0;
                return ++$counter;
            })
            ->addColumn('name',function ($item){
                return $item->name;
            })
            ->addColumn('status',function ($item){
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                $bg = $item->status == 1 ? 'success' : 'danger';
                return "<span class='badge  bg-soft-success text-$bg bg-soft-$bg text-$bg'><span class='legend-indicator bg-$bg'></span>".$status."</span>";
            })
            ->addColumn('action',function ($item){
                $id = $item->id;
                $deleteUrl = route('admin.role.delete',$item->id);

                    return "<div class='btn-group' role='group'>
                      <a href='javascript:void(0)' class='btn btn-white btn-sm edit_user_btn edit_role_btn' data-bs-toggle='modal' data-bs-target='#EditRoleModal' data-id='$id'>
                        <i class='bi bi-pencil-square dropdown-item-icon'></i> ".trans('Edit')."
                      </a>
                    <div class='btn-group'>
                      <button type='button' class='btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty' id='userEditDropdown' data-bs-toggle='dropdown' aria-expanded='false'></button>
                      <div class='dropdown-menu dropdown-menu-end mt-1' aria-labelledby='userEditDropdown'>
                         <a class='dropdown-item loginAccount DeleteBtn' data-route='$deleteUrl' href='javascript:void(0)' data-bs-toggle='modal' data-bs-target='#deleteModal'>
                           <i class='bi bi-trash dropdown-item-icon'></i>
                          ".trans("Delete")."
                        </a>
                      </div>
                    </div>
                  </div>";
            })
            ->rawColumns(['no','name','status','action'])
            ->make(true);
    }

    public function getRole($id)
    {
        $role = Role::findOrFail($id);
        return response()->json([
            'role' => $role,
        ]);
    }

    public function staffList()
    {
        return view('admin.manage_staff.index');
    }

    public function getStaffList(Request $request)
    {
        $staffs = Admin::query()->with('role')
            ->where('id','!=',auth()->guard('admin')->id())
            ->whereNotNull('role_id')
            ->orderBy('name', 'asc')
            ->when(!empty($request->search['value']),function ($query)use($request){
                $query->where('name','LIKE','%'.$request->search['value'].'%')
                    ->orWhere('username','LIKE','%'.$request->search['value'].'%')
                    ->orWhereHas('role',function ($subQuery)use($request){
                        $subQuery->where('name','LIKE','%'.$request->search['value'].'%');
                    });
            });
        return DataTables::of($staffs)
            ->addColumn('no',function (){
                static  $count = 0;
                return ++$count;
            })
            ->addColumn('user',function ($item){
                $profile = '';
                if (!$item->image) {
                    $firstLetter = substr($item->name, 0, 1);
                    $profile =  '<div class="avatar avatar-sm avatar-soft-primary avatar-circle">
                        <span class="avatar-initials">' . $firstLetter . '</span>
                     </div>';

                } else {
                    $url = getFile($item->image_driver, $item->image);
                    $profile =  '<div class="avatar avatar-sm avatar-circle">
                        <img class="avatar-img" src="' . $url . '" alt="Image Description">
                     </div>';

                }
                return  '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                            <div class="flex-shrink-0">
                                    '.$profile.'
                             </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                              <h5 class="text-hover-primary mb-0">' . optional($item)->name.'</h5>
                              <span class="fs-6 text-body">@' . optional($item)->username ?? 'Unknown' . '</span>
                            </div>
                          </a>';
            })
            ->addColumn('role',function ($item){
                return "<span class='badge bg-primary rounded-pill'>".optional($item->role)->name."</span>";
            })
            ->addColumn('status',function ($item){
                $status = $item->status == 1 ? 'Active' : 'Inactive';
                $bg = $item->status == 1 ? 'success' : 'danger';
                return "<span class='badge  bg-soft-success text-$bg bg-soft-$bg text-$bg'><span class='legend-indicator bg-$bg'></span>".$status."</span>";
            })
            ->addColumn('action',function ($item){
                $editUrl = route('admin.edit.staff',$item->id);
                $status = $item->status == 1?'Inactive':'Active';
                $statsChangeUrl = route('admin.role.statusChange', $item->id);
                $loginUrl = route('admin.role.usersLogin',$item->id);
                $icon = $item->status==1?"<i class='fa-light fa-circle-xmark dropdown-item-icon'></i>":'<i class="fa-sharp fa-light fa-check dropdown-item-icon"></i>';
                return adminAccessRoute(config('role.manage_staff.access.edit'))?"<div class='btn-group' role='group'>
                      <a href='$editUrl' class='btn btn-white btn-sm edit_user_btn'>
                        <i class='bi bi-pencil-square dropdown-item-icon'></i> ".trans('Update Staff')."
                      </a>
                    <div class='btn-group'>
                      <button type='button' class='btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty' id='userEditDropdown' data-bs-toggle='dropdown' aria-expanded='false'></button>
                      <div class='dropdown-menu dropdown-menu-end mt-1' aria-labelledby='userEditDropdown'>
                          <a class='dropdown-item LoginAccount'  href='javascript:void(0)' data-route='$loginUrl' >
                           <i class='fa-sharp fa-light fa-right-to-bracket dropdown-item-icon'></i>
                          ".trans("Login as Staff")."
                        </a>
                        <a class='dropdown-item  statusChangeButton' href='javascript:void(0)' data-route='$statsChangeUrl' data-bs-toggle='modal' data-bs-target='#statusChangeModal' data-status='$status'>
                       $icon
                          ".trans($status)."
                        </a>
                      </div>
                    </div>
                  </div>":'';
            })
            ->rawColumns(['no','user','role','status','action'])
            ->make(true);
    }

    public function staffCreate()
    {
        $roles = Role::where('status',1)->get();
        return view('admin.manage_staff.create',compact('roles'));
    }

    public function staffStore(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users,email'],
            'username' => ['required', 'string', 'max:50', 'unique:admins,username'],
            'password' => ['required', 'string', 'min:6'],
            'role' => ['required'],
        ]);
        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $user = new Admin();
        $user->name = $request->name;
        $user->email = $request->email;
        $user->username = $request->username;
        $user->password = Hash::make($request->password);
        $user->role_id = $request->role;
        $user->status = $request->status == 'on'?1:0;

        $user->save();
        session()->flash('success', 'Saved Successfully');
        return redirect()->route('admin.role.staff');
    }

    public function statusChange($id)
    {
        $user = Admin::findOrFail($id);
        if ($user) {
            if ($user->status == 1) {
                $user->status = 0;
            } else {
                $user->status = 1;
            }
            $user->save();
            return back()->with('success', 'Updated Successfully');
        }
    }

    public function userLogin($id)
    {
        Auth::guard('admin')->loginUsingId($id);
        $list = collect(config('role'))->pluck(['access','view'])->collapse()->intersect(optional(optional(Auth::guard('admin')->user())->role)->permission);
        if(count($list) == 0){
            $list = collect(['admin.profile']);
        }
        return redirect()->intended(route($list->first()));
    }

    public function roleCreate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'status' => 'required|boolean',
            'access' => 'required|array|min:1',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $role = new Role();
        $role->user_id = auth()->id();
        $role->name = $request->name;
        $role->status = $request->status;
        $role->permission =  (isset($request->access)) ? $request->access : [];

        $role->save();
        session()->flash('success', 'Saved Successfully');
        return redirect()->back();
    }

    public function roleUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'status' => 'required|boolean',
            'access' => 'required|array|min:1',
        ]);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->messages()], 422);
        }
        $role = Role::findOrFail($request->id);
        try {
            $role->name = $request->name;
            $role->status = $request->status;
            $role->permission =  (isset($request->access)) ? $request->access : [];
            $role->save();
        }catch (\Exception $exception){
            return back()->with('error', $exception->getMessage());
        }

        session()->flash('success', 'Update Successfully');
        return redirect()->back();
    }

    public function roleDelete($id)
    {
        $role = Role::with(['roleUsers'])->find($id);
        if (count($role->roleUsers) > 0) {
            return back()->with('error','This role has many users');
        }
        $role->delete();
        return back()->with('success', 'Delete successfully');
    }
}
PK     :S\oN,)  )  -  Http/Controllers/AAdmin/ContentController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Content;
use App\Models\ContentDetails;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Traits\Upload;


class ContentController extends Controller
{
    use Upload;

    public function index($content)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $data['singleContent'] = config('contents.' . $content . '.single');
        $data['multipleContents'] = config('contents.' . $content . '.multiple');
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $defaultLanguage = $data['languages']->where('default_status', true)->first();

        $data['singleContentData'] = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
            })->get()->groupBy('language_id');


        $data['multipleContentData'] = ContentDetails::with('content')
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
                $query->where('type', 'multiple');
            })->where('language_id', $defaultLanguage->id)
            ->get();

        $contentImage = config('contents.' . $content . '.preview');

        return view('admin.frontend_management.content.index', $data, compact('content', 'contentImage'));

    }

    public function store(Request $request, $content, $language)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.single.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $singleContent = Content::updateOrCreate(['name' => $content], ['name' => $content, 'type' => 'single']);

        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $singleContent->media->{$key} ?? null;
            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.single.size.image');
                    $image = $this->fileUpload($request->$key, config('contents.path'), null, $size,'webp');
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('alert', 'Image could not be uploaded.');
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $singleContent->media = $mediaData;
            $singleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.single.field_name'), config("contents.content_media"));

        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::updateOrCreate(
                ['content_id' => $singleContent->id, 'language_id' => $language],
                ['content_id' => $singleContent->id, 'language_id' => $language, 'description' => $description ?: null]
            );
        }

        if (!$contentDetails) {
            return back()->with('Something went wrong, Please try again.');
        }
        return back()->with('success', 'Content Created Successfully');
    }

    public function manageContentMultiple($content)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['multipleContent'] = config('contents.' . $content . '.multiple');

        return view('admin.frontend_management.content.create', $data, compact('content'));
    }

    public function manageContentMultipleStore(Request $request, $content, $language)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.multiple.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $multipleContent = Content::create(['name' => $content, 'type' => 'multiple']);

        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $multipleContent->media->{$key} ?? null;

            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.multiple.size.image');

                    $image = $this->fileUpload($request->$key, config('contents.path'), null, $size, 'webp', 60);
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('error', $exp->getMessage());
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $multipleContent->media = $mediaData;
            $multipleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.multiple.field_name'), config("contents.content_media"));
        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::create([
                'content_id' => $multipleContent->id,
                'language_id' => $language,
                'description' => $description ?? null
            ]);
        }

        if (!$contentDetails) {
            throw new \Exception("Something went wrong, Please try again");
        }

        return back()->with('success', 'Created Successfully');
    }

    public function multipleContentItemEdit($content, $id)
    {
        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }
        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['multipleContent'] = config('contents.' . $content . '.multiple');

        $data['multipleContentData'] = ContentDetails::with('content')
            ->where('content_id', $id)
            ->whereHas('content', function ($query) use ($content) {
                $query->where('name', $content);
                $query->where('type', 'multiple');
            })
            ->get()->groupBy('language_id');
        return view('admin.frontend_management.content.edit', $data, compact('content', 'id'));
    }

    public function multipleContentItemUpdate(Request $request, $content, $id, $language)
    {

        if (!array_key_exists($content, config('contents'))) {
            abort(404);
        }

        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, config('contents.' . $content . '.multiple.validation'), config('contents.message'));

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        $multipleContent = Content::findOrFail($id);
        foreach (config('contents.content_media') as $key => $media) {
            $old_data = $multipleContent->media->{$key} ?? null;
            if ($request->hasFile($key)) {
                try {
                    $size = config('contents.' . $content . '.multiple.size.image');
                    $image = $this->fileUpload($request->$key, config('contents.path'), null, $size, 'webp', 60, @$multipleContent->media->image->path, @$multipleContent->media->image->driver);
                    $mediaData[$key] = $image;
                } catch (\Exception $exp) {
                    return back()->with('alert', 'Image could not be uploaded.');
                }
            } elseif ($request->has($key)) {
                $mediaData[$key] = $inputData[$key][$language];
            } elseif (isset($old_data)) {
                $mediaData[$key] = $old_data;
            }
        }

        if (isset($mediaData)) {
            $multipleContent->media = $mediaData;
            $multipleContent->save();
        }

        $field_name = array_diff_key(config('contents.' . $content . '.multiple.field_name'), config("contents.content_media"));

        foreach ($field_name as $name => $type) {
            $description[$name] = $inputData[$name][$language];
        }

        if ($language != 0) {
            $contentDetails = ContentDetails::updateOrCreate(
                ['content_id' => $id, 'language_id' => $language],
                ['content_id' => $id, 'language_id' => $language, 'description' => $description ?: null]
            );
        }

        if (!$contentDetails) {
            throw new \Exception("Something went wrong, Please try again");
        }

        return back()->with('success', 'Created Successfully');
    }


    public function ContentDelete($id)
    {
        try {
            $content = Content::findOrFail($id);
            $content->delete();

            $this->fileDelete(optional(optional($content->media)->image)->driver, optional(optional($content->media)->image)->path);

            $contentDetails = ContentDetails::where('content_id', $id)->get();
            foreach ($contentDetails as $detail) {
                $detail->delete();
            }
            return back()->with('success', 'Content has been deleted');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }


}
PK     :S\g  g  -  Http/Controllers/AAdmin/StorageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\FileStorage;
use Illuminate\Http\Request;
use App\Traits\Upload;

class StorageController extends Controller
{
    use Upload;

    public function index()
    {
        $data['fileStorageMethod'] = FileStorage::orderBy('id', 'asc')->get();
        return view('admin.storage.index', $data);
    }

    public function edit($id)
    {
        $fileStorageMethod = FileStorage::where('code', '!=', 'local')->findOrFail($id);
        return view('admin.storage.edit', compact('fileStorageMethod'));
    }

    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|min:2|max:20|string',
        ];

        $storage = FileStorage::where('code', '!=', 'local')->findOrFail($id);
        $parameters = [];
        foreach ($request->except('_token', '_method', 'image') as $k => $v) {
            foreach ($storage->parameters as $key => $cus) {
                if ($k != $key) {
                    continue;
                } else {
                    $rules[$key] = 'required|string|min:1|max:191';
                    $parameters[$key] = $v;
                }
            }
        }

        $request->validate($rules);

        try {
            $response = $storage->update([
                'name' => $request->name,
                'parameters' => $parameters,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please try again.");
            }
            $this->envWrite($storage->code, $storage->parameters);
        } catch (\Exception $e) {
            return back()->with("error", $e->getMessage());
        }
        return back()->with('success', 'File Storage System Updated Successfully.');
    }

    public function setDefault(Request $request, $id)
    {
        try {
            $activeStorage = FileStorage::findOrFail($id);
            $activeStorage->update([
                'status' => 1
            ]);

            $storages = FileStorage::where('id', '!=', $id)->get();
            foreach ($storages as $storage) {
                $storage->update([
                    'status' => 0
                ]);
            }

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('FILESYSTEM_DRIVER', $activeStorage->code, $env);
            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            return back()->with('success', 'File system Set As Default Updated Successfully');
        } catch (\Exception $e) {
            return back()->with("error", $e->getMessage());
        }
    }

    public function envWrite($storageType, $parameters)
    {
        $envPath = base_path('.env');
        $env = file($envPath);
        if ($storageType == 's3') {
            $env = $this->set('AWS_ACCESS_KEY_ID', $parameters['access_key_id'], $env);
            $env = $this->set('AWS_SECRET_ACCESS_KEY', $parameters['secret_access_key'], $env);
            $env = $this->set('AWS_DEFAULT_REGION', $parameters['default_region'], $env);
            $env = $this->set('AWS_BUCKET', $parameters['bucket'], $env);
            $env = $this->set('AWS_URL', $parameters['url'], $env);
            $env = $this->set('AWS_ENDPOINT', $parameters['endpoint'], $env);
        } elseif ($storageType == 'sftp') {
            $env = $this->set('SFTP_USERNAME', $parameters['sftp_username'], $env);
            $env = $this->set('SFTP_PASSWORD', $parameters['sftp_password'], $env);
        } elseif ($storageType == 'do') {
            $env = $this->set('DIGITALOCEAN_SPACES_KEY', $parameters['spaces_key'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_SECRET', $parameters['spaces_secret'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_ENDPOINT', $parameters['spaces_endpoint'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_REGION', $parameters['spaces_region'], $env);
            $env = $this->set('DIGITALOCEAN_SPACES_BUCKET', $parameters['spaces_bucket'], $env);
        } elseif ($storageType == 'ftp') {
            $env = $this->set('FTP_HOST', $parameters['ftp_host'], $env);
            $env = $this->set('FTP_USERNAME', $parameters['ftp_username'], $env);
            $env = $this->set('FTP_PASSWORD', $parameters['ftp_password'], $env);
        }
        $env = $this->set('FILESYSTEM_DRIVER', $storageType, $env);
        $fp = fopen($envPath, 'w');
        fwrite($fp, implode($env));
        fclose($fp);
        return 0;
    }


    private function set($key, $value, $env)
    {
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            if ($entry[0] == $key) {
                $env[$env_key] = $key . "=" . $value . "\n";
            } else {
                $env[$env_key] = $env_value;
            }
        }
        return $env;
    }
}
PK     :S\x#*  #*  .  Http/Controllers/AAdmin/CurrencyController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\CurrencyStoreRequest;
use App\Models\Currency;
use App\Traits\CurrencyRateUpdate;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Mockery\Exception;
use Yajra\DataTables\Facades\DataTables;

class CurrencyController extends Controller
{
    use CurrencyRateUpdate;

    public function currencyList()
    {
        return view('admin.currency.index');
    }

    public function currencyListSearch(Request $request)
    {
        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $currencies = Currency::orderBy('sort_by', 'ASC')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%")
                        ->orWhere('code', 'LIKE', "%$search%")
                        ->orWhere('rate', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($currencies)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                return '<span>' . $item->name . '(' . $item->symbol . ')' . '</span>';

            })
            ->addColumn('code', function ($item) {
                return '<span>' . $item->code . '</span>';

            })
            ->addColumn('rate', function ($item) use ($basicControl) {
                $rate = number_format($item->rate, 4);
                return "<span class='text-dark'> 1 $basicControl->base_currency = $rate $item->code </span>";

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.currencyStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.currencyStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.currencyDelete', $item->id);

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                       data-name="' . $item->name . '" data-code="' . $item->code . '" data-symbol="' . $item->symbol . '" data-rate="' . $item->rate . '"
                       data-route="' . route('admin.currencyEdit', $item->id) . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'code', 'rate', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function currencyCreate(CurrencyStoreRequest $request)
    {
        try {
            $currency = new Currency();
            $fillData = $request->except('_token');
            $currency->fill($fillData)->save();
            return back()->with('success', 'Currency Added Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyEdit(CurrencyStoreRequest $request, $id)
    {
        $currency = Currency::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $currency->fill($fillData)->save();
            return back()->with('success', 'Currency Updated Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyStatusChange(Request $request)
    {
        $currency = Currency::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $currency->status = 1;
            } else {
                $currency->status = 0;
            }
            $currency->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencySort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Currency::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function currencyDelete($id)
    {
        try {
            Currency::findOrFail($id)->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Currency::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Currency has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Currency::whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Currency status has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleRateUpdate(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            $currencies = Currency::select(['id', 'code', 'rate'])->whereIn('id', $request->strIds)->get();
            $currencyCodes = implode(',', $currencies->pluck('code')->toArray());

            $response = $this->fiatRateUpdate(basicControl()->base_currency, $currencyCodes);

            if ($response['status']) {
                foreach ($response['res'] as $key => $apiRes) {
                    $apiCode = substr($key, -3);
                    $matchingCurrencies = $currencies->where('code', $apiCode);

                    if ($matchingCurrencies->isNotEmpty()) {
                        $matchingCurrencies->each(function ($currency) use ($apiRes) {
                            $currency->update([
                                'rate' => $apiRes,
                            ]);
                        });
                    }
                }
            } else {
                session()->flash('error', $response['res']);
            }

            session()->flash('success', 'Rate Updated successfully');
            return response()->json(['success' => 1]);
        }
    }
}
PK     :S\uCA  CA  *  Http/Controllers/AAdmin/PageController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\ManageMenu;
use App\Models\Page;
use App\Rules\AlphaDashWithoutSlashes;
use App\Traits\Upload;
use Http\Client\Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use MatthiasMullie\Minify\JS;

class PageController extends Controller
{
    use Upload;

    public function index()
    {
        $theme = basicControl()->theme;
        $data['allTemplate'] = getThemesNames();
        abort_if(!in_array($theme, getThemesNames()), 404);
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->orderBy('default_status', 'desc')->get();
        $defaultLanguage = Language::where('default_status', true)->first();
        $data['allPages'] = Page::with(['details' => function ($query) use ($defaultLanguage) {
            $query->where('language_id', $defaultLanguage->id);
        }])->whereNull('custom_link')->where('template_name', $theme)->get();
        return view("admin.frontend_management.page.index", $data, compact("theme", 'defaultLanguage'));
    }

    public function create($theme)
    {
        abort_if(!in_array($theme, getThemesNames()), 404);
        $data['url'] = url('/') . "/";
        $data["sections"] = getPageSections();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        return view("admin.frontend_management.page.create", $data, compact('theme'));
    }

    public function store(Request $request, $theme)
    {

        $request->validate([
            'name' => 'required|string|min:3|max:100',
            'slug' => [
                'required',
                'min:1',
                'max:100',
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')->where(function ($query) use ($theme) {
                    return $query->where('template_name', $theme);
                }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
            'page_content' => 'required|string|min:3',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',

        ]);

        if ($request->hasFile('breadcrumb_image')) {
            $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pageImage.path'), null, null, 'webp', 60);
            if ($image) {
                $breadCrumbImage = $image['path'];
                $breadCrumbImageDriver = $image['driver'];
            }
        }

        $sections = preg_match_all('/\[\[([^\]]+)\]\]/', strtolower($request->page_content), $matches) ? $matches[1] : null;

        try {
            $response = Page::create([
                "name" => strtolower($request->name),
                "slug" => $request->slug,
                "template_name" => $theme,
                "breadcrumb_image" => $breadCrumbImage ?? null,
                "breadcrumb_image_driver" => $breadCrumbImageDriver ?? 'local',
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
                "type" => 0
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $response->details()->create([
                "name" => $request->name,
                'language_id' => $request->language_id,
                'content' => $request->page_content,
                'sections' => $sections,
            ]);

            return redirect()->route('admin.page.index', $theme)->with('success', 'Page Saved Successfully');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function edit($id, $theme, $language = null)
    {
        abort_if(!in_array($theme, getThemesNames()), 404);
        $page = Page::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])->where('template_name', $theme)->where('id', $id)->first();

        $data["sections"] = getPageSections();
        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view("admin.frontend_management.page.edit", $data, compact('page', 'language', 'theme'));
    }

    public function update(Request $request, $id, $theme)
    {
        if ($request->status == 0) {
            $menu = $request->name;
            $menuHeader = ManageMenu::where('menu_section', 'header')->first();
            $nestedArr = $menuHeader->menu_items;
            removeValue($nestedArr, strtolower($menu));
            $menuHeader->menu_items = $nestedArr;
            $menuHeader->save();


            $menuFooter = ManageMenu::where('menu_section', 'footer')->first();

            $nestedArr2 = $menuFooter->menu_items;
            removeValue($nestedArr2, strtolower($menu));
            $menuHeader->menu_items = $nestedArr2;
            $menuHeader->save();
        }
        $request->validate([
            'name' => ['required', 'string', 'min:1', 'max:100',
                Rule::unique('page_details', 'page_id')->ignore($id),
            ],
            'slug' => [
                'required',
                'min:1',
                'max:100',
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')
                    ->ignore($id)
                    ->where(function ($query) use ($theme) {
                        return $query->where('template_name', $theme);
                    }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
            'page_content' => 'required|string|min:3',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'sometimes|required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',
        ]);

        try {
            $page = Page::findOrFail($id);
            $sections = preg_match_all('/\[\[([^\]]+)\]\]/', strtolower($request->page_content), $matches) ? $matches[1] : null;

            if ($request->hasFile('breadcrumb_image')) {
                $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pagesImage.path'), null, null, 'webp', 80, $page->breadcrumb_image, $page->breadcrumb_image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
                $breadCrumbImage = $image['path'];
                $breadCrumbImageDriver = $image['driver'] ?? 'local';
            }

            $response = $page->update([
                "slug" => $request->slug,
                "template_name" => $theme,
                "breadcrumb_image" => $breadCrumbImage ?? $page->breadcrumb_image,
                "breadcrumb_image_driver" => $breadCrumbImageDriver ?? $page->breadcrumb_image_driver,
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $page->details()->updateOrCreate([
                'language_id' => $request->language_id,
            ],
                [
                    "name" => $request->name,
                    'content' => $request->page_content,
                    'sections' => $sections,
                ]
            );

            return redirect()->route('admin.page.index', $theme)->with('success', 'Page Updated Successfully');

        } catch (Exception $e) {
            if (isset($breadCrumbImage, $breadCrumbImageDriver))
                $this->fileDelete($breadCrumbImageDriver, $breadCrumbImage);
            return back()->with('error', $e->getMessage());
        }

    }

    public function delete(Request $request, $id)
    {
        try {
            $page = Page::where('id', $id)->firstOr(function () {
                throw new \Exception('Something went wrong, Please try again');
            });


            $headerMenu = ManageMenu::where('menu_section', 'header')->first();
            $footerMenu = ManageMenu::where('menu_section', 'footer')->first();
            $lookingKey = $page->name;
            $headerMenu->update([
                'menu_items' => filterCustomLinkRecursive($headerMenu->menu_items, $lookingKey)
            ]);
            $footerMenu->update([
                'menu_items' => filterCustomLinkRecursive($footerMenu->menu_items, $lookingKey)
            ]);
            $this->fileDelete($page->meta_image_driver, $page->meta_image);
            $page->delete();
            $page->details()->delete();

            return back()->with('success', 'Page deleted successfully');

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function editStaticPage($id, $theme, $language = null)
    {
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['page'] = Page::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])->where('id', $id)->first();

        return view("admin.frontend_management.page.edit_static", $data);
    }

    public function updateStaticPage(Request $request, $id, $theme)
    {

        $request->validate([
            'name' => ['required', 'string', 'min:1', 'max:100',
                Rule::unique('page_details', 'page_id')->ignore($id),
            ],
            'language_id' => 'required|integer|exists:languages,id',
            'breadcrumb_status' => 'nullable|integer|in:0,1',
            'breadcrumb_image' => ($request->input('breadcrumb_status') == 1) ? 'sometimes|required|mimes:jpg,png,jpeg|max:10240' : 'nullable|mimes:jpg,png,jpeg|max:10240',
            'status' => 'nullable|integer|in:0,1',
        ]);

        try {

            $page = Page::findOrFail($id);

            if ($request->hasFile('breadcrumb_image')) {
                $image = $this->fileUpload($request->breadcrumb_image, config('filelocation.pagesImage.path'), null, null, 'webp', 80, $page->breadcrumb_image, $page->breadcrumb_image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
            }

            $response = $page->update([
                "breadcrumb_image" => $image['path'] ?? $page->breadcrumb_image,
                "breadcrumb_image_driver" => $image['driver'] ?? $page->breadcrumb_image_driver,
                "breadcrumb_status" => $request->breadcrumb_status,
                "status" => $request->status,
            ]);

            if (!$response) {
                throw new \Exception("Something went wrong, Please Try again");
            }

            $page->details()->updateOrCreate([
                'language_id' => $request->language_id,
            ],
                [
                    "name" => $request->name,
                ]
            );
            return redirect()->route('admin.page.index', $theme)->with('success', 'Static Page Updated Successfully');
        } catch (Exception $e) {
            if (isset($image['path'], $image['driver']))
                $this->fileDelete($image['driver'], $image['path']);
            return back()->with('error', $e->getMessage());
        }
    }

    public function updateSlug(Request $request)
    {
        $theme = basicControl()->theme;
        $rules = [
            "pageId" => "required|exists:pages,id",
            "newSlug" => [
                "required",
                "min:1",
                "max:100",
                new AlphaDashWithoutSlashes(),
                Rule::unique('pages', 'slug')
                    ->ignore($request->pageId)
                    ->where(function ($query) use ($theme) {
                        return $query->where('template_name', $theme);
                    }),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up']),
            ],
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()]);
        }

        $pageId = $request->pageId;
        $newSlug = $request->newSlug;
        $page = Page::find($pageId);

        if (!$page) {
            return back()->with("error", "Page not found");
        }

        $page->update([
            'slug' => $newSlug
        ]);

        return response([
            'success' => true,
            'slug' => $page->slug
        ]);
    }

    public function pageSEO($id)
    {;
        try {
            $data['page'] = Page::where('id', $id)
                ->select('id', 'name', 'page_title', 'meta_title', 'meta_keywords', 'meta_description', 'og_description', 'meta_robots', 'meta_image', 'meta_image_driver')
                ->firstOr(function () {
                    throw new \Exception('Page is not available.');
                });
            return view("admin.frontend_management.page.seo", $data);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function pageSeoUpdate(Request $request, $id)
    {
        $request->validate([
            'page_title' => 'required|string|min:3|max:100',
            'meta_title' => 'nullable|string|min:3|max:191',
            'meta_keywords' => 'nullable|array',
            'meta_keywords.*' => 'nullable|string|min:1|max:255',
            'meta_description' => 'nullable|string|min:1|max:500',
            'og_description' => 'nullable|string|min:1|max:500',
            'meta_robots' => 'nullable|array',
            'meta_robots.*' => 'nullable|string|min:1|max:255',
            'meta_image' => 'nullable|mimes:jpeg,png,jpeg|max:10240'
        ]);

        try {
            $page = Page::where('id', $id)
                ->select('id', 'name', 'page_title', 'meta_title', 'meta_keywords', 'meta_description', 'og_description', 'meta_robots', 'meta_image', 'meta_image_driver')
                ->firstOr(function () {
                    throw new \Exception('Page is not available.');
                });

            if ($request->hasFile('meta_image')) {
                $metaImage = $this->fileUpload($request->meta_image, config('filelocation.seo.path'), null, null, 'webp', 60, $page->meta_image, $page->meta_image_driver);
                throw_if(empty($metaImage['path']), 'Image path not found');
            }

            if ($request->meta_robots) {
                $meta_robots = implode(",", $request->meta_robots);
            }
            $response = $page->update([
                'page_title' => $request->page_title,
                'meta_title' => $request->meta_title,
                'meta_keywords' => $request->meta_keywords,
                'meta_description' => $request->meta_description,
                'og_description' => $request->og_description,
                'meta_robots' => $meta_robots ?? null,
                'meta_image' => $metaImage['path'] ?? $page->meta_image,
                'meta_image_driver' => $metaImage['driver'] ?? $page->meta_image_driver,
            ]);
            throw_if(!$response, 'Something went wrong, While updating insert data.');
            return back()->with('success', 'Page Seo has been updated.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

}
PK     :S\k[=    0  Http/Controllers/AAdmin/ManageMenuController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\ManageMenu;
use App\Models\Page;
use App\Models\PageDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ManageMenuController extends Controller
{
    public function manageMenu()
    {
        $theme = basicControl()->theme ?? 'dark';
        $defaultLanguage = Language::where('default_status', true)->first();
        $data['pages'] = Page::with(['details' => function ($query) use ($defaultLanguage) {
            $query->where('language_id', $defaultLanguage->id);
        }])->where('template_name', $theme)->get();

        $data['languages'] = Language::orderBy('default_status', 'desc')->get();
        $data['headerMenus'] = ManageMenu::where('menu_section', 'header')->where('theme', $theme)->firstOrFail();
        $data['footerMenus'] = ManageMenu::where('menu_section', 'footer')->where('theme', $theme)->firstOrFail();
        return view('admin.frontend_management.manage-menu', $data);
    }

    public function headerMenuItemStore(Request $request)
    {
        $request->validate([
            'menu_item' => 'nullable|array',
        ]);

        try {
            $menu = ManageMenu::where('menu_section', 'header')->where('theme', basicControl()->theme)->firstOrFail();

            $response = $menu->update([
                'menu_items' => $request->menu_item
            ]);

            if (!$response) {
                throw new \Exception('Something went something, Please try again');
            }
            return back()->with('success', 'Header menu saved successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function footerMenuItemStore(Request $request)
    {
        $request->validate([
            'menu_item' => 'nullable|array',
        ]);
        try {
            $menu = ManageMenu::where('menu_section', 'footer')->where('theme', basicControl()->theme)->firstOrFail();

            $response = $menu->update([
                'menu_items' => $request->menu_item
            ]);

            if (!$response) {
                throw new \Exception('Something went something, Please try again');
            }
            return back()->with('success', 'Footer menu saved successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function addCustomLink(Request $request)
    {
        $rules = [
            'link_text' => 'required|string|min:2|max:100',
            'link' => 'required|url',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            $addError = $validator->getMessageBag();
            $addError->add('errorMessage', 1);
            return redirect()->back()->withErrors($validator)->withInput();
        }

        try {
            $pageForMenu = Page::create([
                'name' => strtolower($request->link_text),
                'slug' => null,
                'template_name' => basicControl()->theme,
                'home_name' => slug($request->link_text),
                'custom_link' => $request->link,
                'type' => 3
            ]);

            if (!$pageForMenu) {
                return back()->with('error', 'Something went wrong, when storing custom link data');
            }

            $defaultLanguage = Language::where('default_status', true)->first();
            $pageForMenu->details()->create([
                'language_id' => $defaultLanguage->id,
                'name' => $request->link_text,
            ]);

            return back()->with('success', 'Custom link added to the menu.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


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

        $rules = [
            'language_id' => 'required',
            'link_text.*' => 'required|max:100',
            'link.*' => 'required|max:100',
        ];

        $message = [
            'link_text.*.required' => 'This link text field is required.',
            'link.*.required' => 'This link field is required.',
        ];

        $language = $request->language_id;
        $inputData = $request->except('_token', '_method');
        $validate = Validator::make($inputData, $rules, $message);

        if ($validate->fails()) {
            $validate->errors()->add('errActive', $language);
            return back()->withInput()->withErrors($validate);
        }

        try {
            $customPage = Page::where('template_name', basicControl()->theme)->findOrFail($id);
            $response = $customPage->update([
                'custom_link' => $request->link[$language]
            ]);

            throw_if(!$response, 'Something went wrong while updating custom menu data.');

            if ($language != 0) {
                $pageDetails = PageDetail::updateOrCreate(
                    ['page_id' => $id, 'language_id' => $language],
                    ['page_id' => $id, 'language_id' => $language, 'name' => $request->link_text[$language]]
                );
            }
            throw_if(!$pageDetails, 'Something went wrong while updating custom menu data.');

            return back()->with('success', 'Custom menu updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function deleteCustomLink(Request $request, $pageId)
    {
        $customPage = Page::where('template_name', basicControl()->theme)->findOrFail($pageId);

        $headerMenu = ManageMenu::where('menu_section', 'header')->where('theme', basicControl()->theme)->first();
        $footerMenu = ManageMenu::where('menu_section', 'footer')->where('theme', basicControl()->theme)->first();

        $lookingKey = $customPage->name;

        $headerMenu->update([
            'menu_items' => filterCustomLinkRecursive($headerMenu->menu_items, $lookingKey)
        ]);

        $footerMenu->update([
            'menu_items' => filterCustomLinkRecursive($footerMenu->menu_items, $lookingKey)
        ]);

        $customPage->delete();
        return back()->with('success', 'Custom link deleted from the menu.');
    }

    public function getCustomLinkData(Request $request)
    {
        $pageId = $request->pageId;
        $languageId = $request->languageId;

        $customPage = PageDetail::with('page:id,name,custom_link')
            ->where('page_id', $pageId)
            ->where('language_id', $languageId)
            ->first();

        return response()->json([
            'name' => $customPage ? $customPage->name : '',
            'custom_link' => $customPage ? optional($customPage->page)->custom_link : ''
        ]);
    }
}
PK     :S\c     5  Http/Controllers/AAdmin/MaintenanceModeController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\MaintenanceMode;
use Illuminate\Http\Request;
use App\Traits\Upload;


class MaintenanceModeController extends Controller
{
    use Upload;

    public function index()
    {
        $data['basicControl'] = basicControl();
        $data['maintenanceMode'] = MaintenanceMode::firstOrFail();
        return view("admin.control_panel.maintenance_mode", $data);
    }

    public function maintenanceModeUpdate(Request $request)
    {

        $request->validate([
            "heading" => "required|string|min:3",
            "description" => "required|string|min:3",
            "is_maintenance_mode" => "nullable|integer|in:0,1",
            "image" => "sometimes|required|mimes:jpg,png,jpeg,gif,svg",
        ]);

        try {
            $maintenanceMode = MaintenanceMode::firstOrCreate();

            if ($request->hasFile('image')) {
                $image = $this->fileUpload($request->image, config('filelocation.maintenanceMode.path'), null, null,'webp', 60,$maintenanceMode->image,$maintenanceMode->image_driver);
                throw_if(empty($image['path']), 'Image could not be uploaded.');
                $image = $image['path'];
                $imageDriver = $image['driver'] ?? 'local';
            }

            $maintenanceMode->update([
                'heading' => $request->heading,
                'description' => $request->description,
                'image' => $image ?? $maintenanceMode->image,
                'image_driver' => $imageDriver ?? $maintenanceMode->image_driver,
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                'is_maintenance_mode' => $request->is_maintenance_mode
            ]);

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', "Maintenance Mode updated successfully");

    }
}
PK     :S\Y1  1  /  Http/Controllers/AAdmin/PayoutLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Transaction;
use App\Traits\Notify;
use Carbon\Carbon;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Yajra\DataTables\Facades\DataTables;

class PayoutLogController extends Controller
{
    use Notify;

    public function index()
    {
        $payoutRecord = \Cache::get('payoutRecord');
        if (!$payoutRecord) {
            $payoutRecord = Payout::selectRaw('COUNT(id) AS totalWithdrawLog')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS pendingWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS pendingWithdrawPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS successWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS successWithdrawPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS cancelWithdraw')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS cancelWithdrawPercentage')
                ->get()
                ->toArray();
            \Cache::put('payoutRecord', $payoutRecord);
        }

        $data['methods'] = PayoutMethod::where('is_active', 1)->orderBy('id', 'asc')->get();
        return view('admin.payout.logs', $data, compact('payoutRecord'));
    }

    public function search(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'];

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $payout = Payout::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'method:id,name,logo,driver'])
            ->whereHas('user')
            ->whereHas('method')
            ->orderBy('id', 'desc')
            ->where('status', '!=', 0)
            ->orderBy('id', 'desc')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('trx_id', 'LIKE', $search)
                    ->orWhereHas('user', function ($q) use ($search) {
                        $q->where('email', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('method', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });

        return DataTables::of($payout)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route("admin.user.edit", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {

                return '<a class="d-flex align-items-center me-2 cursor-unset" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->method)->name . '</h5>
                                </div>
                              </a>';
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payout_currency_code . "</h6>";

            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . getAmount($item->charge) . ' ' . $item->payout_currency_code . "</span>";
            })
            ->addColumn('net amount', function ($item) {
                return "<h6>" . currencyPosition(getAmount($item->amount_in_base_currency)) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), @$v->field_value ?? $v->field_name),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                $icon = $item->status == 1 ? 'pencil' : 'eye';

                $statusColor = '';
                $statusText = '';
                if ($item->status == 0) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 1) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 2) {
                    $statusColor = 'badge bg-soft-success text-success';
                    $statusText = 'Success';
                } else if ($item->status == 3) {
                    $statusColor = 'badge bg-soft-danger text-danger';
                    $statusText = 'Cancel';
                }

                return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-id='$item->id'
                data-info='" . json_encode($details) . "'
                data-userid='" . optional($item->user)->id . "'
                data-sendername='" . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . "'
                data-transactionid='$item->trx_id'
                data-feedback='$item->feedback'
                data-amount=' " . getAmount($item->amount) . ' ' . $item->payout_currency_code . "'
                data-method='" . optional($item->method)->name . "'
                data-gatewayimage='" . getFile(optional($item->method)->driver, optional($item->method)->logo) . "'
                data-datepaid='" . dateTime($item->created_at, 'd M Y') . "'
                data-status='$item->status'
                data-status_color='$statusColor'
                data-status_text='$statusText'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payout.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
            })
            ->rawColumns(['name', 'amount', 'charge', 'method', 'net amount', 'status', 'action'])
            ->make(true);

    }


    public function action(Request $request)
    {
        $this->validate($request, [
            'id' => 'required',
            'status' => ['required', Rule::in(['2', '3'])],
        ]);
        $payout = Payout::where('id', $request->id)->whereIn('status', [1])->with('user', 'method')->firstOrFail();


        if ($request->status == 3) {
            $payout->feedback = $request->feedback;
            $payout->save();
            BasicService::preparePayoutFail($payout);
            return back()->with('success', "Payment Rejected.");
        }

        if (optional($payout->payoutMethod)->is_automatic == 1) {
            $methodObj = 'App\\Services\\Payout\\' . optional($payout->payoutMethod)->code . '\\Card';
            $data = $methodObj::payouts($payout);

            if (!$data) {
                return back()->with('error', 'Method not available or unknown errors occur');
            }

            if ($data['status'] == 'error') {
                BasicService::preparePayoutFail($payout);
                return back()->with('error', $data['data']);
            }
        }

        if (optional($payout->payoutMethod)->is_automatic == 0) {
            $payout->feedback = $request->feedback;
            $payout->save();
            BasicService::preparePayoutComplete($payout);

        } else {
            if (optional($payout->payoutMethod)->code == 'coinbase' || optional($payout->payoutMethod)->code == 'perfectmoney') {
                $payout->feedback = $request->feedback;
                $payout->save();
                BasicService::preparePayoutComplete($payout);
            } else {
                $payout->feedback = $request->feedback;
                $payout->response_id = $data['response_id'];
                $payout->save();
            }
        }

        return back()->with('success', 'Payment Confirmed');
    }
}
PK     :S\>:  :  /  Http/Controllers/AAdmin/DashboardController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\SupportTicket;
use App\Models\Transaction;
use App\Models\User;
use App\Models\UserKyc;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Traits\Upload;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class DashboardController extends Controller
{
    use Upload, Notify;

    public function index()
    {
        $data['firebaseNotify'] = config('firebase');
        $data['latestUser'] = User::latest()->limit(5)->get();
        $statistics['schedule'] = $this->dayList();
        return view('admin.dashboard-alternative', $data, compact("statistics"));
    }

    public function monthlyDepositWithdraw(Request $request)
    {
        $keyDataset = $request->keyDataset;

        $dailyTransaction = $this->dayList();

        Transaction::when($keyDataset == '0', function ($query) {
            $query->whereMonth('created_at', Carbon::now()->month);
        })
            ->when($keyDataset == '1', function ($query) {
                $lastMonth = Carbon::now()->subMonth();
                $query->whereMonth('created_at', $lastMonth->month);
            })
            ->select(
                DB::raw('SUM(amount_in_base) as totalTransaction'),
                DB::raw('DATE_FORMAT(created_at,"Day %d") as date')
            )
            ->groupBy(DB::raw("DATE(created_at)"))
            ->get()->map(function ($item) use ($dailyTransaction) {
                $dailyTransaction->put($item['date'], $item['totalTransaction']);
            });

        return response()->json([
            "totalTransaction" => currencyPosition($dailyTransaction->sum()),
            "dailyTransaction" => $dailyTransaction,
        ]);
    }

    public function saveToken(Request $request)
    {
        $admin = Auth::guard('admin')->user()
            ->fireBaseToken()
            ->create([
                'token' => $request->token,
            ]);
        return response()->json([
            'msg' => 'token saved successfully.',
        ]);
    }


    public function dayList()
    {
        $totalDays = Carbon::now()->endOfMonth()->format('d');
        $daysByMonth = [];
        for ($i = 1; $i <= $totalDays; $i++) {
            array_push($daysByMonth, ['Day ' . sprintf("%02d", $i) => 0]);
        }

        return collect($daysByMonth)->collapse();
    }

    protected function followupGrap($todaysRecords, $lastDayRecords = 0)
    {

        if (0 < $lastDayRecords) {
            $percentageIncrease = (($todaysRecords - $lastDayRecords) / $lastDayRecords) * 100;
        } else {
            $percentageIncrease = 0;
        }
        if ($percentageIncrease > 0) {
            $class = "bg-soft-success text-success";
        } elseif ($percentageIncrease < 0) {
            $class = "bg-soft-danger text-danger";
        } else {
            $class = "bg-soft-secondary text-body";
        }

        return [
            'class' => $class,
            'percentage' => round($percentageIncrease, 2)
        ];
    }


    public function chartUserRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $userRecord = collect(User::selectRaw('COUNT(id) AS totalUsers')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateUserCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateUserCount')
            ->get()->makeHidden(['last-seen-activity', 'fullname'])
            ->toArray())->collapse();
        $followupGrap = $this->followupGrap($userRecord['currentDateUserCount'], $userRecord['previousDateUserCount']);

        $userRecord->put('followupGrapClass', $followupGrap['class']);
        $userRecord->put('followupGrap', $followupGrap['percentage']);

        $current_month_data = DB::table('users')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $userRecord['chartPercentageIncDec'] = fractionNumber($userRecord['totalUsers'] - $userRecord['currentDateUserCount'], false);
        return response()->json(['userRecord' => $userRecord, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartTicketRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $ticketRecord = collect(SupportTicket::selectRaw('COUNT(id) AS totalTickets')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateTicketsCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateTicketsCount')
            ->selectRaw('count(CASE WHEN status = 2  THEN status END) AS replied')
            ->selectRaw('count(CASE WHEN status = 1  THEN status END) AS answered')
            ->selectRaw('count(CASE WHEN status = 0  THEN status END) AS pending')
            ->get()
            ->toArray())->collapse();

        $followupGrap = $this->followupGrap($ticketRecord['currentDateTicketsCount'], $ticketRecord['previousDateTicketsCount']);
        $ticketRecord->put('followupGrapClass', $followupGrap['class']);
        $ticketRecord->put('followupGrap', $followupGrap['percentage']);

        $current_month_data = DB::table('support_tickets')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $ticketRecord['chartPercentageIncDec'] = fractionNumber($ticketRecord['totalTickets'] - $ticketRecord['currentDateTicketsCount'], false);
        return response()->json(['ticketRecord' => $ticketRecord, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartOrderRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');
        $orderRecords = collect(Order::payment()->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateOrderCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateOrderCount')
            ->get()
            ->toArray())->collapse();
        $followupGrap = $this->followupGrap($orderRecords['currentDateOrderCount'], $orderRecords['previousDateOrderCount']);
        $orderRecords->put('followupGrapClass', $followupGrap['class']);
        $orderRecords->put('followupGrap', $followupGrap['percentage']);


        $current_month_data = DB::table('orders')->where('payment_status', 1)
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $orderRecords['chartPercentageIncDec'] = fractionNumber($orderRecords['totalOrder'] - $orderRecords['currentDateOrderCount'], false);
        return response()->json(['orderRecord' => $orderRecords, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }

    public function chartTransactionRecords()
    {
        $currentMonth = Carbon::now()->format('Y-m');

        $transaction = collect(Transaction::selectRaw('COUNT(id) AS totalTransaction')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS currentDateTransactionCount')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = DATE(DATE_SUB(NOW(), INTERVAL 1 DAY)) THEN id END) AS previousDateTransactionCount')
            ->whereRaw('YEAR(created_at) = YEAR(NOW()) AND MONTH(created_at) = MONTH(NOW())')
            ->get()
            ->toArray())
            ->collapse();

        $followupGrap = $this->followupGrap($transaction['currentDateTransactionCount'], $transaction['previousDateTransactionCount']);
        $transaction->put('followupGrapClass', $followupGrap['class']);
        $transaction->put('followupGrap', $followupGrap['percentage']);


        $current_month_data = DB::table('transactions')
            ->select(DB::raw('DATE_FORMAT(created_at,"%e %b") as date'), DB::raw('count(*) as count'))
            ->where(DB::raw('DATE_FORMAT(created_at, "%Y-%m")'), $currentMonth)
            ->orderBy('created_at', 'asc')
            ->groupBy('date')
            ->get();

        $current_month_data_dates = $current_month_data->pluck('date');
        $current_month_datas = $current_month_data->pluck('count');
        $transaction['chartPercentageIncDec'] = fractionNumber($transaction['totalTransaction'] - $transaction['currentDateTransactionCount'], false);
        return response()->json(['transactionRecord' => $transaction, 'current_month_data_dates' => $current_month_data_dates, 'current_month_datas' => $current_month_datas]);
    }


    public function chartLoginHistory()
    {
        $userLoginsData = DB::table('user_logins')
            ->whereDate('created_at', '>=', now()->subDays(30))
            ->select('browser', 'os', 'get_device')
            ->get();

        $userLoginsBrowserData = $userLoginsData->groupBy('browser')->map->count();
        $data['browserKeys'] = $userLoginsBrowserData->keys();
        $data['browserValue'] = $userLoginsBrowserData->values();

        $userLoginsOSData = $userLoginsData->groupBy('os')->map->count();
        $data['osKeys'] = $userLoginsOSData->keys();
        $data['osValue'] = $userLoginsOSData->values();

        $userLoginsDeviceData = $userLoginsData->groupBy('get_device')->map->count();
        $data['deviceKeys'] = $userLoginsDeviceData->keys();
        $data['deviceValue'] = $userLoginsDeviceData->values();

        return response()->json(['loginPerformance' => $data]);
    }

    public function chartTopUpOrderRecords()
    {
        $currentTime = Carbon::now();
        $data['topUpOrderToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'topup')[0] ?? null;
        $data['topUpOrderYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'topup')[0] ?? null;
        $data['totalTopUpOrder'] = Order::payment()->type('topup')->count();
        return response()->json(['topUpOrderRecord' => $data]);
    }

    public function chartCardOrderRecords()
    {
        $currentTime = Carbon::now();
        $data['cardOrderToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'card')[0] ?? null;
        $data['cardOrderYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'card')[0] ?? null;
        $data['totalCardOrder'] = Order::payment()->type('card')->count();
        return response()->json(['cardOrderRecord' => $data]);
    }

    public function chartAddFundRecords()
    {
        $currentTime = Carbon::now();
        $data['cardAddFundToday'] = $this->getDataForTimeRange($currentTime, $currentTime->copy()->subHours(24), 'fund')[0] ?? null;
        $data['cardAddFundYesterday'] = $this->getDataForTimeRange($currentTime->copy()->subHours(24), $currentTime->copy()->subHours(24), 'fund')[0] ?? null;
        $data['totalAddFund'] = Deposit::where('status', 1)->where('payment_method_id', '!=', '-1')->sum('amount_in_base');
        $data['currencySymbol'] = basicControl()->currency_symbol;
        return response()->json(['addFundRecord' => $data]);
    }

    public function chartOrderMovement()
    {
        $orderRecords = DB::table('orders')
            ->where('payment_status', 1)
            ->selectRaw('
        MONTH(created_at) as month,
        COUNT(CASE WHEN order_for = "topup" THEN 1 END) AS topUpOrder,
        COUNT(CASE WHEN order_for = "card" THEN 1 END) AS cardOrder
    ')
            ->whereYear('created_at', date('Y'))  // Optional: Filter by current year
            ->groupBy(DB::raw('MONTH(created_at)'))
            ->orderBy(DB::raw('MONTH(created_at)'))
            ->get();


        // Initialize monthly data arrays with zeros
        $monthlyData = [
            'topUp' => array_fill(0, 12, 0),
            'card' => array_fill(0, 12, 0),
        ];

        foreach ($orderRecords as $record) {
            $monthIndex = $record->month - 1; // Adjust month to zero-based index for JavaScript
            $monthlyData['topUp'][$monthIndex] = $record->topUpOrder;
            $monthlyData['card'][$monthIndex] = $record->cardOrder;
        }

        return response()->json([
            'orderFigures' => [
                'horizontalBarChatInbox' => $monthlyData
            ]
        ]);
    }

    function getDataForTimeRange($start, $end, $type)
    {
        $hours = [];
        $counts = [];

        for ($i = 0; $i < 24; $i++) {
            if ($i % 2 == 0) {
                $hour = $start->copy()->subHours($i + 1);
                $formattedHour = $hour->format('hA');
                $hours[] = $formattedHour;

                if ($type == 'topup' || $type == 'card') {
                    $count = DB::table('orders')
                        ->where('payment_status', 1)
                        ->where('order_for', $type)
                        ->where('updated_at', '>=', $hour)
                        ->where('updated_at', '<', $hour->copy()->addHours(2))
                        ->count();
                } elseif ($type == 'fund') {
                    $count = DB::table('deposits')
                        ->where('status', 1)
                        ->where('payment_method_id', '!=', '-1')
                        ->where('updated_at', '>=', $hour)
                        ->where('updated_at', '<', $hour->copy()->addHours(2))
                        ->count();
                }
                $counts[] = $count;
            }
        }
        $hours = array_reverse($hours);
        $counts = array_reverse($counts);

        $data[] = [
            'hours' => $hours,
            'counts' => $counts,
        ];
        return $data;
    }

}
PK     :S\db[H+  H+  3  Http/Controllers/AAdmin/ManualGatewayController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Gateway;
use App\Traits\Upload;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Exception;

class ManualGatewayController extends Controller
{
    use Upload;

    public function index()
    {
        $data['methods'] = Gateway::manual()->orderBy('sort_by', 'asc')->get();
        return view('admin.payment_methods.manual.list', $data);
    }

    public function create()
    {
        $data['basicControl'] = basicControl();
        return view('admin.payment_methods.manual.create', $data);
    }

    public function store(Request $request)
    {

        $rules = [
            'name' => "required|min:3",
            'description' => 'required|string|min:3',
            'note' => 'required|string|min:3',
            'manual_gateway_status' => "nullable|integer|in:0,1",
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.currency' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'required|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'note.required' => 'The payment description field is required.',
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'receivable_currencies.*.currency.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $input_form = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $input_form[$arr['field_name']] = $arr;
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 60);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('alert', 'Image could not be uploaded.');
            }
        }

        $request->validate($rules, $customMessages);

        $collection = collect($request->receivable_currencies);
        $supportedCurrency = $collection->pluck('currency')->all();
        $response = Gateway::create([
            'name' => $request->name,
            'code' => Str::slug($request->name),
            'supported_currency' => $supportedCurrency,
            'receivable_currencies' => $request->receivable_currencies,
            'parameters' => $input_form,
            'image' => $gatewayImage ?? null,
            'driver' => $driver ?? null,
            'status' => $request->status,
            'note' => $request->note,
            'description' => $request->description
        ]);

        if (!$response) {
            throw new \Exception('Unexpected error! Please try again.');
        }

        return back()->with('success', 'Gateway data has been add successfully.');

    }

    public function edit($id)
    {
        $data['basicControl'] = basicControl();
        $data['method'] = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception("Invalid Gateways Request");
        });
        return view('admin.payment_methods.manual.edit', $data);
    }


    public function update(Request $request, $id)
    {
        $rules = [
            'name' => "required|min:3|unique:gateways,name," . $id,
            'description' => 'required|string|min:3',
            'note' => 'required|string|min:3',
            'manual_gateway_status' => "nullable|integer|in:0,1",
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'receivable_currencies' => 'required|array',
            'receivable_currencies.*.currency' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'receivable_currencies.*.conversion_rate' => 'required|numeric',
            'receivable_currencies.*.min_limit' => 'required|numeric',
            'receivable_currencies.*.max_limit' => 'required|numeric',
            'receivable_currencies.*.percentage_charge' => 'required|numeric',
            'receivable_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
        ];

        $customMessages = [
            'note.required' => 'The payment description field is required.',
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'receivable_currencies.*.currency.required' => 'The receivable currency currency symbol field is required.',
            'receivable_currencies.*.conversion_rate.required' => 'The receivable currency convention rate field is required.',
            'receivable_currencies.*.conversion_rate.numeric' => 'The convention rate for receivable currency must be a number.',
            'receivable_currencies.*.min_limit.required' => 'The receivable currency min limit field is required.',
            'receivable_currencies.*.min_limit.numeric' => 'The min limit for receivable currency must be a number.',
            'receivable_currencies.*.max_limit.required' => 'The receivable currency max limit field is required.',
            'receivable_currencies.*.max_limit.numeric' => 'The max limit for receivable currency must be a number.',
            'receivable_currencies.*.percentage_charge.required' => 'The receivable currency percentage charge field is required.',
            'receivable_currencies.*.percentage_charge.numeric' => 'The percentage charge for receivable currency must be a number.',
            'receivable_currencies.*.fixed_charge.required' => 'The receivable currency fixed charge name is required.',
            'receivable_currencies.*.fixed_charge.numeric' => 'The fixed charge for receivable currency must be a number.',
        ];


        $gateway = Gateway::where('id', $id)->firstOr(function () {
            throw new Exception("Invalid Gateways Request");
        });

        if (1000 > $gateway->id) {
            return back()->with('error', 'Invalid Gateways Request');
        }


        $input_form = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $input_form[$arr['field_name']] = $arr;
            }
        }

        $request->validate($rules, $customMessages);

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.gateway.path'), null, null, 'webp', 60, $gateway->image, $gateway->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('alert', 'Image could not be uploaded.');
            }
        }

        $collection = collect($request->receivable_currencies);
        $supportedCurrency = $collection->pluck('currency')->all();

        $response = $gateway->update([
            'name' => $request->name,
            'supported_currency' => $supportedCurrency,
            'receivable_currencies' => $request->receivable_currencies,
            'parameters' => $input_form,
            'image' => $gatewayImage ?? $gateway->image,
            'driver' => $driver ?? $gateway->driver,
            'status' => $request->manual_gateway_status,
            'note' => $request->note,
            'description' => $request->description
        ]);

        if (!$response) {
            throw new Exception('Unexpected error! Please try again.');
        }

        return back()->with('success', 'Gateway data has been updated.');

    }

}
PK     :S\N    2  Http/Controllers/AAdmin/BlogCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BlogCategory;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class BlogCategoryController extends Controller
{
    public function index()
    {
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->paginate(10);
        return view('admin.blog_category.list', $data);
    }

    public function create()
    {
        return view('admin.blog_category.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required',
        ]);
        try {
            $response = BlogCategory::create([
                'name' => $request->name,
                'slug' => Str::slug($request->name)
            ]);
            throw_if(!$response, 'Something went wrong while storing blog category data. Please try again later.');
            return back()->with('success', 'Blog category save successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit(string $id)
    {
        try {
            $data['blogCategory'] = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });
            return view('admin.blog_category.edit', $data);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $request->validate([
            'name' => 'required',
        ]);
        try {
            $blogCategory = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });

            $response = $blogCategory->update([
                'name' => $request->name,
                'slug' => Str::slug($request->name)
            ]);
            throw_if(!$response, 'Something went wrong while storing blog category data. Please try again later.');
            return back()->with('success', 'Blog category save successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        try {
            $blogCategory = BlogCategory::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog category data found.');
            });
            $blogCategory->delete();
            return redirect()->back()->with('success', 'Blog category deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
    public function status($id){

        try {
            $blogCategory = BlogCategory::select('id', 'status')
                ->where('id', $id)
                ->firstOr(function () {
                    throw new \Exception('Blog Category not found.');
                });

            $blogCategory->status = ($blogCategory->status == 1) ? 0 : 1;
            $blogCategory->save();

            return back()->with('success','Blog Category Status Changed Successfully.');
        }catch (\Exception $e){
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     :S\pUk<  k<  :  Http/Controllers/AAdmin/NotificationTemplateController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use App\Models\NotificationTemplate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Facades\App\Services\BasicService;

class NotificationTemplateController extends Controller
{

    public function defaultTemplate(Request $request)
    {
        $basicControl = basicControl();
        if ($request->isMethod('get')) {
            return view('admin.notification_templates.email_template.default', ['basicControl' => $basicControl]);
        } elseif ($request->isMethod('post')) {

            $request->validate([
                'sender_email' => 'required|email:rfc,dns',
                'sender_email_name' => 'required|string|max:100',
                'email_description' => 'required|string',
            ]);

            try {
                $basicControl->update([
                    'sender_email' => $request->sender_email,
                    'sender_email_name' => $request->sender_email_name,
                    'email_description' => $request->email_description
                ]);

                $env = [
                    'MAIL_FROM_ADDRESS' => $request->sender_email,
                    'MAIL_FROM_NAME' => '"' . $request->sender_email_name . '"'
                ];

                BasicService::setEnv($env);
                return back()->with('success', 'Default email template updated successfully.');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function emailTemplates()
    {
        $emailTemplates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');
        return view('admin.notification_templates.email_template.index', ['emailTemplates' => $emailTemplates]);
    }

    public function editEmailTemplate($id)
    {
        try {
            $data['languages'] = Language::select('id', 'name')->get();
            $data["template"] = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Email template is not available.');
            });

            $templateKey = $data["template"]->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.email_template.edit', $data, compact('templates'));

        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function updateEmailTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'subject.*' => 'required|string|max:200',
            'email_from.*' => 'required|string|max:100',
            'email_template.*' => 'required|string',
            'mail_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'subject.*.required' => 'The subject field is required.',
            'email_from.*.required' => 'The email from field is required.',
            'email_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Email template is not available.');
            });

            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'mail') {
                        $status[$key] = $request->mail_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
                'template_key' => $template->template_key,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'subject' => $request->subject[$language->id] ?? null,
                'email_from' => $request->email_from[$language->id] ?? null,
                'short_keys' => $template->short_keys,
                'email' => strip_tags($request->email_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name ?? null
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'Email template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }


    public function smsTemplates()
    {
        $smsTemplates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');
        return view('admin.notification_templates.sms_template.index', compact('smsTemplates'));
    }

    public function editSmsTemplate($id)
    {
        try {
            $data['languages'] = Language::select('id', 'name')->get();
            $data['template'] = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('SMS template is not available.');
            });

            $templateKey = $data['template']->template_key;
            $data['templates'] = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.sms_template.edit', $data);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updateSmsTemplate(Request $request, $id, $language_id)
    {

        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'sms_template.*' => 'required|string',
            'sms_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'sms_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });

            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'sms') {
                        $status[$key] = $request->sms_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'sms' => strip_tags($request->sms_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'SMS template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage())->withInput($request->all());
        }
    }


    public function inAppNotificationTemplates()
    {
        $templates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');;
        return view('admin.notification_templates.in_app_notification_template.index', compact('templates'));
    }

    public function editInAppNotificationTemplate($id)
    {
        try {
            $languages = Language::select('id', 'name')->get();
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('In-app template is not available.');
            });

            $templateKey = $template->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.in_app_notification_template.edit', compact('template', 'languages', 'templates'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updateInAppNotificationTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'in_app_notification_template.*' => 'required|string',
            'in_app_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'in_app_notification_template.*.required' => 'The message field is required.',
        ]);


        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });

            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'in_app') {
                        $status[$key] = $request->in_app_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'in_app' => strip_tags($request->in_app_notification_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name
            ]);

            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'In App Notification template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }

    public function pushNotificationTemplates()
    {
        $templates = NotificationTemplate::select('id', 'language_id', 'name', 'template_key', 'status')->get()->unique('template_key');;
        return view('admin.notification_templates.push_notification_template.index', compact('templates'));
    }

    public function editPushNotificationTemplate($id)
    {
        try {
            $languages = Language::select('id', 'name')->get();
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('Push template is not available.');
            });
            $templateKey = $template->template_key;
            $templates = NotificationTemplate::where('template_key', $templateKey)->get();
            return view('admin.notification_templates.push_notification_template.edit', compact('template', 'languages', 'templates'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function updatePushNotificationTemplate(Request $request, $id, $language_id)
    {
        $validator = Validator::make($request->all(), [
            'name.*' => 'required|string|max:255',
            'push_notification_template.*' => 'required|string',
            'push_status' => 'nullable|integer|in:0,1'
        ], [
            'name.*.required' => 'The name field is required.',
            'name.*.string' => 'The name must be a string.',
            'name.*.max' => 'The name may not be greater than 255.',
            'push_notification_template.*.required' => 'The message field is required.',
        ]);

        if ($validator->fails()) {
            return back()->withInput($request->all())->withErrors($validator->getMessageBag());
        }

        try {
            $template = NotificationTemplate::where('id', $id)->firstOr(function () {
                throw new \Exception('No template found.');
            });


            $status = [];
            if ($template->status) {
                foreach ($template->status as $key => $oldStatus) {
                    if ($key == 'push') {
                        $status[$key] = $request->push_status;
                    }
                }
            }

            $newStatus = array_replace($template->status, $status);
            $language = Language::where('id', $request['language_id'])->firstOr(function () {
                throw new \Exception('language is not available.');
            });
            $response = $template->updateOrCreate([
                'language_id' => $language_id,
            ], [
                'name' => $request->name[$language->id] ?? null,
                'template_key' => $template->template_key,
                'short_keys' => $template->short_keys,
                'push' => strip_tags($request->push_notification_template[$language->id]) ?? null,
                'status' => $newStatus,
                'lang_code' => $language->short_name

            ]);
            throw_if(!$response, 'Something went wrong, Please try again later.');
            return back()->with('success', 'Push Notification template has been updated successfully.')->withInput($request->all());
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage())->withInput($request->all());
        }
    }
}
PK     :S\qγn    ,  Http/Controllers/AAdmin/PluginController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Validation\ValidationException;
use Vonage\Client\Exception\Validation;
use function GuzzleHttp\Promise\all;

class PluginController extends Controller
{
    public function pluginConfig()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.plugin_config', compact('basicControl'));
    }

    public function tawkConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.tawk_control', compact('basicControl'));
    }

    public function tawkConfigurationUpdate(Request $request)
    {
        try {
            $request->validate([
                'tawk_id' => 'required|string|min:3',
                'status' => 'required|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "tawk_id" => $request->tawk_id,
                "tawk_status" => $request->status
            ]);

            return back()->with('success', 'Successfully Updated');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function fbMessengerConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.fb_messenger_control', compact('basicControl'));
    }

    public function fbMessengerConfigurationUpdate(Request $request)
    {
        try {
            $request->validate([
                'fb_app_id' => 'required|string|min:3',
                'fb_page_id' => 'required|string|min:3',
                'fb_messenger_status' => 'required|integer|min:0|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "fb_app_id" => $request->fb_app_id,
                "fb_page_id" => $request->fb_page_id,
                "fb_messenger_status" => $request->fb_messenger_status
            ]);

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function googleRecaptchaConfiguration()
    {
        $data['googleRecaptchaSiteKey'] = env('GOOGLE_RECAPTCHA_SITE_KEY');
        $data['googleRecaptchaSecretKey'] = env('GOOGLE_RECAPTCHA_SECRET_KEY');
        $data['googleRecaptchaSiteVerifyUrl'] = env('GOOGLE_RECAPTCHA_SITE_VERIFY_URL');
        $data['basicControl'] = basicControl();
        return view('admin.plugin_controls.google_recaptcha_control', $data);
    }

    public function googleRecaptchaConfigurationUpdate(Request $request)
    {

        try {
            $request->validate([
                'google_recaptcha_site_key' => 'required|string|min:3',
                'google_recaptcha_secret_key' => 'required|string|min:3',
                'google_recaptcha_site_verify_url' => 'required|string|min:3',
                'google_reCapture_admin_login' => 'integer|in:0,1',
                'google_reCaptcha_status_login' => 'integer|in:0,1',
                'google_reCaptcha_status_registration' => 'integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                'google_reCapture_admin_login' => $request->google_reCapture_admin_login,
                'google_reCaptcha_status_login' => $request->google_reCaptcha_status_login,
                'google_reCaptcha_status_registration' => $request->google_reCaptcha_status_registration
            ]);


            $env = [
                'GOOGLE_RECAPTCHA_SITE_KEY' => $request->google_recaptcha_site_key,
                'GOOGLE_RECAPTCHA_SECRET_KEY' => $request->google_recaptcha_secret_key,
                'GOOGLE_RECAPTCHA_SITE_VERIFY_URL' => $request->google_recaptcha_site_verify_url,
            ];

            BasicService::setEnv($env);

            Artisan::call('config:clear');
            Artisan::call('cache:clear');

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function googleAnalyticsConfiguration()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.analytic_control', compact('basicControl'));
    }

    public function googleAnalyticsConfigurationUpdate(Request $request)
    {

        try {
            $request->validate([
                'MEASUREMENT_ID' => 'required|min:3',
                'analytic_status' => 'required|integer|in:0,1',
            ], [
                'MEASUREMENT_ID.required' => " The MEASUREMENT ID field is required.
"
            ]);

            $basicControl = basicControl();
            $basicControl->update([
                "measurement_id" => $request->MEASUREMENT_ID,
                "analytic_status" => $request->analytic_status,
            ]);

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->withErrors($e->getMessage());
        }
    }

    public function manualRecaptcha()
    {
        $basicControl = basicControl();
        return view('admin.plugin_controls.manual_recaptcha', compact('basicControl'));
    }

    public function manualRecaptchaUpdate(Request $request)
    {
        try {
            $request->validate([
                'admin_login_recaptcha' => 'required|integer|in:0,1',
                'user_login_recaptcha' => 'required|integer|in:0,1',
                'user_registration_recaptcha' => 'required|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->recaptcha_admin_login = $request->admin_login_recaptcha;
            $basicControl->reCaptcha_status_login = $request->user_login_recaptcha;
            $basicControl->reCaptcha_status_registration = $request->user_registration_recaptcha;
            $basicControl->save();

            return back()->with('success', 'Successfully Updated');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    public function activeRecaptcha(Request $request)
    {

        try {
            $request->validate([
                'googleRecaptcha' => 'nullable|integer|in:0,1',
                'manualRecaptcha' => 'nullable|integer|in:0,1',
            ]);

            $basicControl = basicControl();
            $basicControl->google_recaptcha = $request->googleRecaptcha;
            $basicControl->manual_recaptcha = $request->manualRecaptcha;
            $basicControl->save();

            return response([
                'success' => true,
                'message' => "Recaptcha Updated Successfully"
            ]);
        } catch (\Exception $e) {
            return response([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }
}
PK     :S\ۖQ  Q  2  Http/Controllers/AAdmin/BasicControlController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BasicControl;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Facades\App\Services\BasicService;
use Facades\App\Services\CurrencyLayerService;
use Exception;

class BasicControlController extends Controller
{
    public function index($settings = null)
    {
        $settings = $settings ?? 'settings';
        abort_if(!in_array($settings, array_keys(config('generalsettings'))), 404);
        $settingsDetails = config("generalsettings.{$settings}");
        return view('admin.control_panel.settings', compact('settings', 'settingsDetails'));
    }

    public function basicControl()
    {
        $data['basicControl'] = basicControl();
        $data['timeZones'] = timezone_identifiers_list();
        $data['dateFormat'] = config('dateformat');
        return view('admin.control_panel.basic_control', $data);
    }

    public function basicControlUpdate(Request $request)
    {
        $request->validate([
            'site_title' => 'required|string|min:1|max:100',
            'time_zone' => 'required|string',
            'base_currency' => 'required|string|min:1|max:100',
            'currency_symbol' => 'required|string|min:1|max:100',
            'fraction_number' => 'required|integer|not_in:0',
            'paginate' => 'required|integer|not_in:0',
            'date_format' => 'required|string',
            'contact_number' => 'required|max:20',
            'payment_released' => 'required|max:20',
            'payment_expired' => 'required|max:20',
            'admin_prefix' => 'required|string|min:3|max:100',
            'light_primary_color' => 'required|string',
            'dark_primary_color' => 'required|string',
        ]);

        try {
            $basic = BasicControl();
            $response = BasicControl::updateOrCreate([
                'id' => $basic->id ?? ''
            ], [
                'site_title' => $request->site_title,
                'time_zone' => $request->time_zone,
                'base_currency' => $request->base_currency,
                'currency_symbol' => $request->currency_symbol,
                'fraction_number' => $request->fraction_number,
                'date_time_format' => $request->date_format,
                'contact_number' => $request->contact_number,
                'payment_released' => $request->payment_released,
                'payment_expired' => $request->payment_expired,
                'paginate' => $request->paginate,
                'admin_prefix' => $request->admin_prefix,
                'light_primary_color' => $request->light_primary_color,
                'dark_primary_color' => $request->dark_primary_color,
            ]);

            if (!$response)
                throw new Exception('Something went wrong, when updating data');

            $env = [
                'APP_TIMEZONE' => $response->time_zone,
                'APP_DEBUG' => $response->error_log == 0 ? 'true' : 'false'
            ];

            BasicService::setEnv($env);
            session()->flash('success', 'Basic control has been successfully configured');
            Artisan::call('optimize:clear');
            return back();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function basicControlActivityUpdate(Request $request)
    {
        $request->validate([
            'strong_password' => 'nullable|numeric|in:0,1',
            'registration' => 'nullable|numeric|in:0,1',
            'error_log' => 'nullable|numeric|in:0,1',
            'card' => 'nullable|numeric|in:0,1',
            'top_up' => 'nullable|numeric|in:0,1',
            'sell_post' => 'nullable|numeric|in:0,1',
            'is_active_cron_notification' => 'nullable|numeric|in:0,1',
            'has_space_between_currency_and_amount' => 'nullable|numeric|in:0,1',
            'is_force_ssl' => 'nullable|numeric|in:0,1',
            'is_currency_position' => 'nullable|string|in:left,right'
        ]);

        try {
            $basic = BasicControl();
            $response = BasicControl::updateOrCreate([
                'id' => $basic->id ?? ''
            ], [
                'error_log' => $request->error_log,
                'strong_password' => $request->strong_password,
                'registration' => $request->registration,
                'card' => $request->card,
                'top_up' => $request->top_up,
                'sell_post' => $request->sell_post,
                'is_active_cron_notification' => $request->is_active_cron_notification,
                'has_space_between_currency_and_amount' => $request->has_space_between_currency_and_amount,
                'is_currency_position' => $request->is_currency_position,
                'is_force_ssl' => $request->is_force_ssl
            ]);

            if (!$response)
                throw new Exception('Something went wrong, when updating the data.');

            session()->flash('success', 'Basic control has been successfully configured.');
            Artisan::call('optimize:clear');
            return back();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function currencyExchangeApiConfig()
    {
        $data['scheduleList'] = config('schedulelist.schedule_list');
        $data['basicControl'] = basicControl();
        return view('admin.control_panel.exchange_api_setting', $data);
    }

    public function currencyExchangeApiConfigUpdate(Request $request)
    {
        try {
            $basicControl = basicControl();
            $basicControl->update([
                'currency_layer_access_key' => $request->currency_layer_access_key,
                'currency_layer_auto_update' => $request->currency_layer_auto_update,
                'currency_layer_auto_update_at' => $request->currency_layer_auto_update_at,
                'coin_market_cap_app_key' => $request->coin_market_cap_app_key,
                'coin_market_cap_auto_update' => $request->coin_market_cap_auto_update,
                'coin_market_cap_auto_update_at' => $request->coin_market_cap_auto_update_at,
            ]);
            return back()->with('success', 'Configuration changes successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
    public function basicControlTableViewUpdate(Request $request)
    {
        $this->validate($request, [
            'table_view' => 'required|in:flex,scrolling',
        ]);

        $basic = BasicControl();
        BasicControl::updateOrCreate([
            'id' => $basic->id ?? ''
        ], [
            'table_view' => $request->table_view,
        ]);

        return back()->with('success', ucfirst($request->table_view) . ' Version Applied Successfully');
    }
    public function appControl(Request $request)
    {
        $basicControl = basicControl();
        if ($request->method() == 'GET') {
            return view('admin.control_panel.app_control', compact('basicControl'));
        } elseif ($request->method() == 'POST') {
            try {
                $response = BasicControl::updateOrCreate([
                    'id' => $basicControl->id ?? ''
                ], [
                    'app_color' => $request->app_color,
                    'app_version' => $request->app_version,
                    'app_build' => $request->app_build,
                    'is_major' => $request->is_major,
                ]);

                if (!$response)
                    throw new Exception('Something went wrong, when updating the data.');

                session()->flash('success', 'App control has been successfully configured.');
                Artisan::call('optimize:clear');
                return back();
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }
}
PK     :S\t0XM  M  /  Http/Controllers/AAdmin/SubscribeController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Subscriber;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class SubscribeController extends Controller
{
    public function index(Request $request)
    {
        $data['subscribeRecord'] = collect(Subscriber::selectRaw('COUNT(id) AS totalSubscribe')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todaySubscribe')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todaySubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN WEEK(created_at, 1) = WEEK(CURDATE(), 1) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisWeekSubscribe')
            ->selectRaw('(COUNT(CASE WHEN WEEK(created_at, 1) = WEEK(CURDATE(), 1) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisWeekSubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthSubscribe')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthSubscribePercentage')
            ->selectRaw('COUNT(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisYearSubscribe')
            ->selectRaw('(COUNT(CASE WHEN YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisYearSubscribePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.subscribe.list', $data);
    }

    public function subscribeSearch(Request $request)
    {
        $filterName = $request->name;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $subscribes = Subscriber::orderBy('id', 'DESC')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('email', 'LIKE', '%' . $filterName . '%');
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($request->search['value']), function ($query) use ($request) {
                $query->where(function ($subquery) use ($request) {
                    $subquery->where('email', 'LIKE', '%' . $request->search['value'] . '%');
                });
            });


        return DataTables::of($subscribes)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })

            ->addColumn('email', function ($item) {
                return $item->email;
            })

            ->addColumn('subscribe_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })

            ->rawColumns(['no','email', 'subscribe_at'])
            ->make(true);
    }
}
PK     :S\AA      9  Http/Controllers/AAdmin/AdminProfileSettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationTemplate;
use Illuminate\Support\Facades\Hash;
use App\Traits\Upload;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Exception;

class AdminProfileSettingController extends Controller
{
    use Upload;

    public function profile()
    {
        $basicControl = basicControl();
        $admin = Auth::guard('admin')->user();
        $templates = NotificationTemplate::where('notify_for', 1)->get()->unique('template_key');
        return view('admin.profile', compact('admin', 'basicControl', 'templates'));
    }

    public function profileUpdate(Request $request)
    {
        $request->validate([
            'name' => 'required|string|min:3',
            'username' => 'required|string|min:3',
            'email' => 'required|email|min:3|email:rfc,dns',
            'phone' => 'required|string|min:3',
            'addressLine' => 'required|string|min:3',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif'
        ]);

        try {
            $admin = Auth::guard('admin')->user();

            if ($request->file('image')) {
                $image = $this->fileUpload($request->image, config('filelocation.adminProfileImage.path'), null,null, 'webp', 60, $admin->image, $admin->image_driver);
                if ($image) {
                    $adminImage = $image['path'];
                    $adminImageDriver = $image['driver'] ?? 'local';
                }
            }

            $response = $admin->update([
                'name' => $request->name,
                'username' => $request->username,
                'email' => $request->email,
                'phone' => $request->phone,
                'address' => $request->addressLine,
                'image' => $adminImage ?? $admin->image,
                'image_driver' => $adminImageDriver ?? $admin->image_driver,
            ]);

            if (!$response) {
                throw new Exception("Something went wrong");
            }

            return back()->with("success", "Admin Profile Updated Successfully.");

        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function passwordUpdate(Request $request)
    {

        $request->validate([
            'current_password' => 'required',
            'password' => 'required|min:5|confirmed',
        ]);

        $admin = Auth::guard('admin')->user();

        if (!Hash::check($request->current_password, $admin->password)) {
            return back()->with('error', "Password didn't match");
        }
        $admin->update([
            'password' => bcrypt($request->password)
        ]);
        return back()->with('success', 'Password has been Changed');
    }

    public function notificationPermission(Request $request)
    {
        $templates = $request->input('templates', []);
        foreach ($templates as $templateId => $templateData) {
            $template = NotificationTemplate::findOrFail($templateId);
            $template->update([
                'status' => $templateData
            ]);
        }
        return back()->with('success', 'Permissions updated successfully.');
    }


}
PK     :S\PM  M  0  Http/Controllers/AAdmin/PaymentLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Gateway;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Facades\App\Services\BasicService;
use Yajra\DataTables\Facades\DataTables;

class PaymentLogController extends Controller
{
    use Notify;

    public function index()
    {
        $paymentRecord = \Cache::get('paymentRecord');
        if (!$paymentRecord) {
            $paymentRecord = Deposit::selectRaw('COUNT(id) AS totalPaymentLog')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS paymentSuccess')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS paymentSuccessPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS pendingPayment')
                ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS pendingPaymentPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS cancelPayment')
                ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS cancelPaymentPercentage')
                ->get()
                ->toArray();
            \Cache::put('paymentRecord', $paymentRecord);
        }

        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.payment.logs', $data, compact('paymentRecord'));
    }


    public function search(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $deposit = Deposit::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'gateway:id,name,image,driver'])
            ->whereHas('user')
            ->whereHas('gateway')
            ->orderBy('id', 'desc')
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($deposit)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';


            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                if (optional($item->gateway)->id > 999) {
                    $icon = $item->status == 2 ? 'pencil' : 'eye';
                    return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                 data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
                } else {
                    return '-';
                }
            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);

    }

    public function pending()
    {
        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.payment.request', $data);
    }

    public function paymentRequest(Request $request)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;


        $funds = Deposit::with('user', 'gateway')
            ->where('status', 2)->where('payment_method_id', '>', 999)->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->get();

        return DataTables::of($funds)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2 cursor-unset" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                $icon = $item->status == 2 ? 'pencil' : 'eye';
                return "<button type='button' class='btn btn-white btn-sm edit_btn'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";

            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);
    }

    public function action(Request $request, $id)
    {
        $this->validate($request, [
            'id' => 'required',
            'status' => ['required', Rule::in(['1', '3'])],
            'feedback' => 'required|string|min:3|max:300'
        ]);
        $data = Deposit::where('id', $id)->whereIn('status', [2])->with('user', 'gateway')->firstOrFail();

        if ($request->status == '1') {
            $data->update([
                'note' => $request->feedback
            ]);
            BasicService::preparePaymentUpgradation($data);
            session()->flash('success', 'Payment approved successfully.');
            return back();

        } elseif ($request->status == '3') {

            $data->update([
                'status' => 3,
                'note' => $request->feedback
            ]);

            $msg = [
                'username' => optional($data->user)->username,
                'amount' => currencyPosition($data->amount_in_base),
                'gateway' => optional($data->gateway)->name,
            ];
            $action = [
                "link" => '#',
                "icon" => "fas fa-money-bill-alt text-white"
            ];

            $this->userPushNotification($data->user, 'PAYMENT_REJECTED', $msg, $action);
            $this->userFirebasePushNotification('PAYMENT_REJECTED', $msg, $action);
            $this->sendMailSms($data->user, 'PAYMENT_REJECTED', [
                'gateway_name' => optional($data->gateway)->name,
                'amount' => currencyPosition($data->amount),
                'charge' => currencyPosition($data->charge),
                'transaction' => $data->trx_id,
                'feedback' => $data->note,
            ]);

            session()->flash('success', 'Payment rejected successfully.');
            return back();
        }
        return back();
    }
}


PK     :S\>,  ,  *  Http/Controllers/AAdmin/BlogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Blog;
use App\Models\BlogCategory;
use App\Models\BlogDetails;
use App\Models\Language;
use App\Traits\Upload;
use Illuminate\Http\Request;
use App\Rules\AlphaDashWithoutSlashes;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class BlogController extends Controller
{
    use Upload;

    public function index()
    {
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        $data['blogs'] = Blog::with('category', 'details')->orderBy('id', 'desc')->paginate(10);
        return view('admin.blogs.list', $data);
    }


    public function create()
    {
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->get();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view('admin.blogs.create', $data);
    }

    public function store(Request $request)
    {

        $request->validate([
            'category_id' => 'required|numeric|not_in:0|exists:blog_categories,id',
            'title' => 'required|string|min:3|max:200',
            'slug' => 'required|string|min:3|max:200|alpha_dash|unique:blogs,slug',
            'description' => 'required|string|min:3',
            'description_image' => 'required|mimes:png,jpg,jpeg|max:50000',
        ]);
        try {
            if ($request->hasFile('description_image')) {
                $descriptionImage = $this->fileUpload($request->description_image, config('filelocation.blog.path'), null, config('filelocation.blog.preview_img'), 'webp', null);
                throw_if(empty($descriptionImage['path']), 'Description image could not be uploaded.');
            }
            if ($request->hasFile('banner_image')) {
                $bannerImage = $this->fileUpload($request->banner_image, config('filelocation.blog.path'), null, config('filelocation.blog.banner_img'), 'webp', null);
                throw_if(empty($bannerImage['path']), 'Banner image could not be uploaded.');
            }

            $response = Blog::create([
                'category_id' => $request->category_id,
                'slug' => $request->slug,
                'blog_image' => $descriptionImage['path'] ?? null,
                'blog_image_driver' => $descriptionImage['driver'] ?? null,
                'banner_image' => $bannerImage['path'] ?? null,
                'banner_image_driver' => $bannerImage['driver'] ?? null,
            ]);

            throw_if(!$response, 'Something went wrong while storing blog data. Please try again later.');


            $response->details()->create([
                "title" => $request->title,
                'language_id' => $request->language_id,
                'description' => $request->description,
            ]);

            return back()->with('success', 'Blog saved successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }


    /**
     * Show the form for editing the specified resource.
     */
    public function blogEdit($id, $language = null)
    {
        $blog = Blog::with(['details' => function ($query) use ($language) {
            $query->where('language_id', $language);
        }])
            ->where('id', $id)
            ->firstOr(function () {
                throw new \Exception('Blog not found');
            });

        $data['pageEditableLanguage'] = Language::where('id', $language)->select('id', 'name', 'short_name')->first();
        $data['defaultLanguage'] = Language::where('default_status', true)->first();
        $data['blogCategory'] = BlogCategory::orderBy('id', 'desc')->get();
        $data['allLanguage'] = Language::select('id', 'name', 'short_name', 'flag', 'flag_driver')->where('status', 1)->get();
        return view('admin.blogs.edit', $data, compact('blog', 'language'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function blogUpdate(Request $request, $id, $language)
    {
        $request->validate([
            'category_id' => 'required|numeric|not_in:0|exists:blog_categories,id',
            'title' => 'required|string|min:3|max:1000',
            'description' => 'nullable|string|min:3',
            'description_image' => 'nullable|mimes:png,jpg,jpeg|max:50000',
            'banner_image' => 'nullable|mimes:png,jpg,jpeg|max:50000',
        ]);

        try {
            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });

            if ($request->hasFile('description_image')) {
                $descriptionImage = $this->fileUpload($request->description_image, config('filelocation.blog.path'), null, config('filelocation.blog.preview_img'), 'webp', null, $blog->blog_image, $blog->blog_image_driver);
                throw_if(empty($descriptionImage['path']), 'Description image could not be uploaded.');
            }

            if ($request->hasFile('banner_image')) {
                $bannerImage = $this->fileUpload($request->banner_image, config('filelocation.blog.path'), null, config('filelocation.blog.banner_img'), 'webp', null, $blog->banner_image, $blog->banner_image_driver);
                throw_if(empty($bannerImage['path']), 'Banner image could not be uploaded.');
            }

            $response = $blog->update([
                'category_id' => $request->category_id,
                'slug' => $request->slug ?? $blog->slug,
                'blog_image' => $descriptionImage['path'] ?? $blog->blog_image,
                'blog_image_driver' => $descriptionImage['driver'] ?? $blog->blog_image_driver,
                'banner_image' => $bannerImage['path'] ?? $blog->banner_image,
                'banner_image_driver' => $bannerImage['driver'] ?? $blog->banner_image_driver,
            ]);

            throw_if(!$response, 'Something went wrong while storing blog data. Please try again later.');

            $blog->details()->updateOrCreate([
                'language_id' => $language,
            ],
                [
                    "title" => $request->title,
                    'description' => $request->description,
                ]
            );

            return back()->with('success', 'Blog saved successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function destroy(string $id)
    {
        try {
            $blog = Blog::where('id', $id)->firstOr(function () {
                throw new \Exception('No blog data found.');
            });

            $blogDetails = BlogDetails::where('blog_id', $id)->get();
            if ($blogDetails->count() > 0) {
                foreach ($blogDetails as $blogDetail) {
                    $blogDetail->delete();
                }
            }

            $blog->delete();
            return redirect()->back()->with('success', 'Blog deleted successfully.');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function slugUpdate(Request $request)
    {

        $rules = [
            "blogId" => "required|exists:blogs,id",
            "newSlug" => ["required", "min:1", "max:100",
                new AlphaDashWithoutSlashes(),
                Rule::unique('blogs', 'slug')->ignore($request->blogId),
                Rule::notIn(['login', 'register', 'signin', 'signup', 'sign-in', 'sign-up'])
            ],
        ];
        $validator = Validator::make($request->all(), $rules);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()]);
        }
        $blogId = $request->blogId;

        $newSlug = $request->newSlug;
        $blog = Blog::find($blogId);

        if (!$blog) {
            return back()->with("error", "Blog not found");
        }

        $blog->slug = $newSlug;
        $blog->save();

        return response([
            'success' => true,
            'slug' => $blog->slug
        ]);
    }

    public function blogSeo(Request $request, $id)
    {
        try {
            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });
            return view('admin.blogs.seo', compact('blog'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function blogSeoUpdate(Request $request, $id)
    {
        $request->validate([
            'page_title' => 'required|string|min:3|max:100',
            'meta_title' => 'required|string|min:3|max:100',
            'meta_keywords' => 'required|array',
            'meta_keywords.*' => 'required|string|min:1|max:300',
            'meta_description' => 'required|string|min:1|max:300',
            'seo_meta_image' => 'sometimes|required|mimes:jpeg,png,jpeg|max:10240'
        ]);

        try {

            $blog = Blog::with("details")->where('id', $id)->firstOr(function () {
                throw new \Exception('Blog not found');
            });

            if ($request->hasFile('meta_image')) {
                try {
                    $image = $this->fileUpload($request->meta_image, config('filelocation.pageSeo.path'), null, null, 'webp', 80,$blog->meta_image, $blog->meta_image_driver);
                    if ($image) {
                        $pageSEOImage = $image['path'];
                        $pageSEODriver = $image['driver'] ?? 'local';
                    }
                } catch (\Exception $exp) {
                    return back()->with('error', 'Meta image could not be uploaded.');
                }
            }

            $blog->update([
                'page_title' => $request->page_title,
                'meta_title' => $request->meta_title,
                'meta_keywords' => $request->meta_keywords,
                'meta_description' => $request->meta_description,
                'meta_image' => $pageSEOImage ?? $blog->meta_image,
                'meta_image_driver' => $pageSEODriver ?? $blog->meta_image_driver,
            ]);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
        return back()->with('success', 'Seo has been updated.');
    }
    public function status($id){

        try {
            $blog = Blog::select('id', 'status')
                ->where('id', $id)
                ->firstOr(function () {
                    throw new \Exception('Blog not found.');
                });

            $blog->status = ($blog->status == 1) ? 0 : 1;
            $blog->save();

            return back()->with('success','Blog Status Changed Successfully.');
        }catch (\Exception $e){
            return back()->with('error', $e->getMessage());
        }

    }

}
PK     :S\J  J  4  Http/Controllers/AAdmin/TransactionLogController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Deposit;
use App\Models\Order;
use App\Models\Payout;
use App\Models\Transaction;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TransactionLogController extends Controller
{
    public function transaction()
    {
        return view('admin.transaction.index');
    }

    public function transactionSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterTransactionId = $request->filterTransactionID;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = Transaction::query()->with(['user:id,username,firstname,lastname,image,image_driver'])
            ->whereHas('user')
            ->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('trx_id', 'LIKE', "%$search%")
                        ->orWhere('remarks', 'LIKE', "%{$search}%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            });

        return DataTables::of($transaction)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('base_amount', function ($item) {
                $statusClass = $item->trx_type == '+' ? 'text-success' : 'text-danger';
                return "<h6 class='mb-0 $statusClass '>" . $item->trx_type . ' ' . currencyPosition(getAmount($item->amount_in_base)) . "</h6>";
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.view.profile", optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                    ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username ?? 'Unknown' . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('type', function ($item) {
                if ($item->transactional_type == Deposit::class) {
                    return 'Deposit';
                } elseif ($item->transactional_type == Order::class) {
                    return 'Order';
                }elseif ($item->transactional_type == Payout::class) {
                    return 'Payout';
                } else {
                    return '-';
                }
            })
            ->addColumn('remarks', function ($item) {
                return $item->remarks;
            })
            ->addColumn('date-time', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->rawColumns(['trx', 'base_amount', 'user', 'type', 'remarks', 'date-time'])
            ->make(true);
    }
}
PK     :S\KI	  	  9  Http/Controllers/AAdmin/TranslateAPISettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Facades\App\Services\BasicService;
use App\Traits\Upload;

class TranslateAPISettingController extends Controller
{

    use Upload;

    public function translateAPISetting()
    {
        $translateMethod = Config('translateconfig.translate_method');
        $activeMethod = Config('translateconfig.default');
        return view('admin.translate_controls.index', compact('translateMethod', 'activeMethod'));
    }

    public function translateAPISettingEdit($method)
    {
        try {
            $data['basicControl'] = basicControl();
            $translateControlMethod = config('translateconfig.translate_method');
            $translateMethodParameters = $translateControlMethod[$method] ?? null;

            return view('admin.translate_controls.translate_api_config', $data, compact('translateMethodParameters', 'method'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function translateAPISettingUpdate(Request $request, $method)
    {
        $rules = [];
        $translateControlMethod = config('translateconfig.translate_method');
        $translateMethodParameters = $translateControlMethod[$method] ?? null;

        foreach ($request->except('_token', '_method') as $key => $value) {
            if (array_key_exists($key, $translateMethodParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }

        $request->validate($rules);

        try {
            $env = [
                'END_POINT_URL' => $request->end_point_url ?? $translateControlMethod['azure']['end_point_url']['value'],
                'SUBSCRIPTION_KEY' => $request->subscription_key ?? $translateControlMethod['azure']['subscription_key']['value'],
                'SUBSCRIPTION_REGION' => $request->subscription_region ?? $translateControlMethod['azure']['subscription_region']['value'],
            ];

            BasicService::setEnv($env);

            return back()->with('success', 'Translate Configuration has been updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function translateSetAsDefault($method)
    {
        $env = [
            'TRANSLATE_METHOD' => $method
        ];

        BasicService::setEnv($env);

        return back()->with('success', 'Translate method set as default successfully.');
    }


}
PK     :S\O5  5  .  Http/Controllers/AAdmin/TempleteController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\BasicControl;
use App\Models\Page;
use Illuminate\Http\Request;

class TempleteController extends Controller
{
    public function index()
    {

        return view('admin.templete.home');
    }

    public function selectTemplete(Request $request)
    {
        $theme = $request->input('theme');
        if (!in_array($theme, array_keys(config('themes')))) {
            return response()->json(['error' => "Invalid Request"], 422);
        }

        $basic = BasicControl::firstOrCreate();
        $basic->theme = $theme;
        $basic->save();

        session()->forget('theme');

        $message = request()->theme_name . ' theme selected.';
        return response()->json(['message' => $message], 200);
    }
}
PK     :S\Ol[n  n  2  Http/Controllers/AAdmin/PusherConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;

class PusherConfigController extends Controller
{
    public function pusherConfig()
    {
        $basicControl = basicControl();
        $data['pusherAppId'] = env('pusher_app_id');
        $data['pusherAppKey'] = env('pusher_app_key');
        $data['pusherAppSecret'] = env('pusher_app_secret');
        $data['pusherAppCluster'] = env('pusher_app_cluster');
        return view('admin.control_panel.pusher_config', $data, compact('basicControl'));
    }

    public function pusherConfigUpdate(Request $request)
    {
        $request->validate([
            'pusher_app_id' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_key' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_secret' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'pusher_app_cluster' => 'required|string|regex:/^[A-Za-z0-9_.-]+$/',
            'push_notification' => 'nullable|integer|min:0|in:0,1',
        ]);

        $env = [
            'PUSHER_APP_ID' => $request->pusher_app_id,
            'PUSHER_APP_KEY' => $request->pusher_app_key,
            'PUSHER_APP_SECRET' => $request->pusher_app_secret,
            'PUSHER_APP_CLUSTER' => $request->pusher_app_cluster,
        ];

        BasicService::setEnv($env);

        $basicControl = basicControl();
        $basicControl->update([
           'in_app_notification' => $request->in_app_notification
        ]);

        return back()->with('success', 'Pusher Configuration Successfully');

    }
}
PK     :S\]    3  Http/Controllers/AAdmin/Module/CouponController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Coupon;
use App\Models\TopUp;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CouponController extends Controller
{
    public function couponList()
    {
        $data['coupons'] = Coupon::latest()->get();
        return view('admin.coupon.list', $data);
    }

    public function couponStore(Request $request)
    {
        if ($request->method() == 'GET') {
            return view('admin.coupon.create');
        } elseif ($request->method() == 'POST') {
            $this->validate($request, [
                'title' => 'required',
                'code' => 'required|min:6|unique:coupons,code',
                'discount' => 'required|min:0',
                'discount_type' => 'required|in:percent,flat',
                'start_date' => 'required',
            ]);


            $coupon = Coupon::create([
                'title' => $request->title,
                'code' => $request->code,
                'discount' => $request->discount,
                'discount_type' => $request->discount_type,
                'used_limit' => $request->used_limit??0,
                'is_unlimited' => $request->is_unlimited == 'yes' ? 1 : 0,
                'start_date' => Carbon::createFromFormat('d M Y H:i', $request->start_date)->format('Y-m-d H:i:s'),
                'end_date' => $request->is_expired == 'no' ? null : Carbon::createFromFormat('d M Y H:i', $request->end_date)->format('Y-m-d H:i:s'),
            ]);

            return redirect()->route('admin.couponEdit', $coupon->id)->with('success', 'Coupon generated successfully');
        }
    }

    public function couponEdit(Request $request, $id)
    {
        $coupon = Coupon::findOrFail($id);
        if ($request->method() == 'GET') {
            $data['topups'] = TopUp::latest()->get();
            $data['cards'] = Card::latest()->get();
            return view('admin.coupon.edit', $data, compact('coupon'));
        } elseif ($request->method() == 'POST') {
            $this->validate($request, [
                'title' => 'required',
                'code' => 'required|min:6|unique:coupons,code,' . $coupon->id,
                'discount' => 'required|min:0',
                'discount_type' => 'required|in:percent,flat',
                'start_date' => 'required',
            ]);


            $coupon->update([
                'title' => $request->title,
                'code' => $request->code,
                'apply_module' => $request->apply_module ?? [],
                'discount' => $request->discount,
                'discount_type' => $request->discount_type,
                'used_limit' => $request->used_limit,
                'is_unlimited' => $request->is_unlimited == 'yes' ? 1 : 0,
                'start_date' => Carbon::createFromFormat('d M Y H:i', $request->start_date)->format('Y-m-d H:i:s'),
                'end_date' => $request->is_expired == 'no' ? null : Carbon::createFromFormat('d M Y H:i', $request->end_date)->format('Y-m-d H:i:s'),
            ]);

            return back()->with('success', 'Updated Successfully');
        }
    }

    public function couponDelete($id)
    {
        $coupon = Coupon::findOrFail($id);
        $coupon->delete();
        return back()->with('success', 'Deleted Successfully');
    }

    public function couponMultipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Coupon.');
            return response()->json(['error' => 1]);
        } else {
            Coupon::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been change');
            return response()->json(['success' => 1]);
        }
    }

    public function couponMultipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Coupon.');
            return response()->json(['error' => 1]);
        } else {
            Coupon::whereIn('id', $request->strIds)->get()->delete();
            session()->flash('success', 'Deleted Successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function topUpTypeChange(Request $request, $type)
    {
        if ($type == 'permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->top_up_list??[];
                    $mergeData = array_merge($existingLists, $request->strIds);
                    $coupon->top_up_list = array_unique($mergeData);
                    $coupon->save();

                    session()->flash('success', 'Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }

        if ($type == 'not_permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->top_up_list??[];
                    $coupon->top_up_list = array_diff($existingLists, $request->strIds);;
                    $coupon->save();

                    session()->flash('success', 'Not Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }
    }

    public function cardTypeChange(Request $request, $type)
    {
        if ($type == 'permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->card_list??[];
                    $mergeData = array_merge($existingLists, $request->strIds);
                    $coupon->card_list = array_unique($mergeData);
                    $coupon->save();

                    session()->flash('success', 'Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }

        if ($type == 'not_permitted') {
            if ($request->strIds == null) {
                session()->flash('error', 'You do not select Coupon.');
                return response()->json(['error' => 1]);
            } else {
                $coupon = Coupon::find($request->couponId);
                if ($coupon) {
                    $existingLists = $coupon->card_list??[];
                    $coupon->card_list = array_diff($existingLists, $request->strIds);;
                    $coupon->save();

                    session()->flash('success', 'Not Permitted Successfully');
                    return response()->json(['success' => 1]);
                }
            }
        }
    }
}
PK     :S\G!-H  H  1  Http/Controllers/AAdmin/Module/CardController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\CardStoreRequest;
use App\Models\Card;
use App\Models\Category;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CardController extends Controller
{
    use Upload;

    public function list(Request $request)
    {
        $data['cards'] = collect(Card::with(['category'])
            ->when(isset($request->category_id), function ($query) use ($request) {
                $query->where('category_id', $request->category_id);
            })
            ->selectRaw('COUNT(id) AS totalCard')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCard')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCardPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCard')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCardPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCard')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCardPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCard')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCardPercentage')
            ->get()
            ->toArray())->collapse();

        $data['category_id'] = $request->category_id ?? null;
        return view('admin.card.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $categoryId = $request->category_id;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $cards = Card::with(['category'])->orderBy('sort_by', 'ASC')
            ->withCount([
                'activeServices',
            ])
            ->when(isset($categoryId), function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('region', 'LIKE', "%{$search}%")
                        ->orWhereHas('category', function ($categoryQuery) use ($search) {
                            $categoryQuery->where('name', 'LIKE', "%{$search}%");
                        });
                });
            })->get();

        return DataTables::of($cards)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image->preview_driver ?? null, $item->image->preview ?? null);
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                              <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                              </div>
                            <div class="flex-shrink-0">
                                <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="/' . $url . '" alt="Image Description">
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                <p class="text-hover-primary mb-0">' . $item->region . '</p>
                            </div>
                        </a>
                    ';

            })
            ->addColumn('active_service', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_services_count) . '</span>';
            })
            ->addColumn('active_code', function ($item) {
                return '<span class="badge bg-soft-secondary text-dark">' . number_format($item->activeCodeCount()) . '</span>';
            })
            ->addColumn('instant_delivery', function ($item) {
                if ($item->instant_delivery == 1) {
                    return '<span class="badge bg-soft-primary text-primary">' . trans('Yes') . '</span>';

                } else {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('No') . '</span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="'.$item->category?->icon.'"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('trending', function ($item) {
                if ($item->trending == 1) {
                    return '<span class="badge bg-soft-primary text-primary">
                    <span class="legend-indicator bg-primary"></span>' . trans('Yes') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('No') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="'.$item->category?->icon.'"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.card.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.card.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.card.delete', $item->id);
                $trending = route('admin.card.trending', $item->id);
                $edit = route('admin.card.edit', $item->id);
                $service = route('admin.cardService.list') . '?card_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $service . '" class="dropdown-item">
                            <i class="fas fa-dice dropdown-item-icon"></i> ' . trans("Service List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item trending_btn" href="javascript:void(0)" data-bs-target="#trending"
                           data-bs-toggle="modal" data-route="' . $trending . '">
                          <i class="fal fa-chart-line-up dropdown-item-icon"></i> ' . trans("Manage Trending") . '
                       </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_service', 'active_code','trending', 'instant_delivery', 'status', 'category', 'created_at', 'action'])
            ->make(true);
    }

    public function store(CardStoreRequest $request)
    {
        if ($request->method() == 'GET') {
            $data['categories'] = Category::active()->type('card')->sort()->get();
            return view('admin.card.create', $data);
        } elseif ($request->method() == 'POST') {
            try {
                $card = new Card();
                $fillData = $request->except('_token');
                $fillData['image'] = $this->processImages($fillData);

                $card->fill($fillData)->save();

                return back()->with('success', 'Card Created Successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function statusChange(Request $request)
    {
        $card = Card::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $card->status = 1;
            } else {
                $card->status = 0;
            }
            $card->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function sort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Card::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function trending($id){
        try {
            $card = Card::select(['id', 'trending'])->findOrFail($id);

            $card->trending = ($card->trending == 0) ? 1 : 0;
            $card->save();

            $message = ($card->trending == 0) ? 'Removed From Trending List.' : 'Added To Trending List.';

            return back()->with('success', $message);
        }catch (\Exception $exception){
            return back()->with('error', $exception->getMessage());
        }

    }
    public function delete($id)
    {
        try {
            $card = Card::findOrFail($id);
            $images = [
                ['driver' => $card->image->image_driver ?? null, 'path' => $card->image->image ?? null],
                ['driver' => $card->image->preview_driver ?? null, 'path' => $card->image->preview ?? null],
                ['driver' => $card->image->banner_driver ?? null, 'path' => $card->image->banner ?? null],
            ];
            foreach ($images as $image) {
                $this->fileDelete($image['driver'], $image['path']);
            }
            $card->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function edit(CardStoreRequest $request, $id)
    {
        $card = Card::FindOrFail($id);
        if ($request->method() == 'GET') {
            $categories = Category::active()->type('card')->sort()->get();
            return view('admin.card.edit', compact('card', 'categories'));
        } elseif ($request->method() == 'POST') {
            try {
                $fillData = $request->except('_token');
                $fillData['image'] = $this->processImages($fillData, $card);

                $card->fill($fillData)->save();

                return back()->with('success', 'Card has been updated successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Card::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $images = [
                    ['driver' => $query->image->image_driver ?? null, 'path' => $query->image->image ?? null],
                    ['driver' => $query->image->preview_driver ?? null, 'path' => $query->image->preview ?? null],
                    ['driver' => $query->image->banner_driver ?? null, 'path' => $query->image->banner ?? null],
                ];
                foreach ($images as $image) {
                    $this->fileDelete($image['driver'], $image['path']);
                }
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Card has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }
    public function multipleTrending(Request $request)
    {
        if (empty($request->strIds)) {
            session()->flash('error', 'No rows were selected.');
            return response()->json(['error' => 1]);
        }

        Card::whereIn('id', $request->strIds)->each(function ($card) {
            $card->trending = !$card->trending;
            $card->save();
        });

        session()->flash('success', 'Trending status has been updated successfully.');
        return response()->json(['success' => 1]);
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Card::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Card has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    private function processImages($fillData, $topUP = null)
    {
        $images = [
            'image' => $fillData['image'] ?? null,
            'preview' => $fillData['preview_image'] ?? null,
        ];

        $imageData = [];
        foreach ($images as $key => $image) {
            if ($image) {
                $uploadedImage = $this->uploadImage($image, $key, $topUP);
                if ($uploadedImage) {
                    $imageData[$key] = $uploadedImage['path'];
                    $imageData[$key . '_driver'] = $uploadedImage['driver'];
                }
            } else {
                $imageData[$key] = $topUP->image->{$key} ?? null;
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null;
            }
        }

        return $imageData;
    }

    private function uploadImage($image, $key, $topUP = null)
    {
        try {
            return $this->fileUpload(
                $image,
                config('filelocation.card.path'),
                null,
                config('filelocation.card.' . $key . '_size'),
                'webp',
                60,
                $topUP->image->{$key} ?? null,
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null,

            );
        } catch (\Exception $e) {
            return null;
        }
    }
}
PK     :S\yk5  5  9  Http/Controllers/AAdmin/Module/TopUpServiceController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\TopUpServiceExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\TopUpServiceRequest;
use App\Imports\TopUpServiceImport;
use App\Models\TopUp;
use App\Models\TopUpService;
use App\Traits\Sample;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class TopUpServiceController extends Controller
{
    use Upload, Sample;

    public function serviceList(Request $request)
    {
        $data['topUp'] = TopUp::select(['id', 'name'])->findOrFail($request->top_up_id);
        $data['services'] = collect(TopUpService::with(['topUp'])->where('top_up_id', $request->top_up_id)->selectRaw('COUNT(id) AS totalService')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeService')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeServicePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveService')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveServicePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayService')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayServicePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthService')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthServicePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.topUp.service.index', $data);
    }

    public function serviceSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $services = TopUpService::orderBy('sort_by', 'ASC')->where('top_up_id', $request->top_up_id)
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%");
                    $subquery->orWhere('price', 'LIKE', "%$search%");
                    $subquery->orWhere('discount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($services)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image_driver ?? null, $item->image ?? null);
                $offerContent = $item->is_offered ? '<div class="trending-content"><i class="fa-light fa-badge-percent"></i>' . trans('Campaign') . '</div>' : '';
                return '<a class="d-flex align-items-center me-2">
                                <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                 </div>
                                <div class="flex-shrink-0 trending-notification">
                                ' . $offerContent . '
                                  <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                  </div>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('price', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . basicControl()->currency_symbol . formatAmount($item->price - $item->getDiscount()) . '</span> <sup class="badge bg-soft-dark text-dark ms-1">' . basicControl()->currency_symbol . formatAmount($item->getDiscount()) . ' off</sup>';
            })
            ->addColumn('discount', function ($item) {
                $showType = "%";
                if ($item->discount_type == 'flat') {
                    $showType = basicControl()->base_currency;
                }
                return '<span class="badge bg-soft-danger text-danger">' . $item->discount . ' ' . $showType . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.topUpService.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.topUpService.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.topUpService.delete', $item->id);
                $edit = route('admin.topUpService.update', $item->id);
                $image = getFile($item->image_driver ?? null, $item->image ?? null);
                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                      data-route="' . $edit . '" data-name="' . $item->name . '" data-price="' . $item->price . '" data-discount="' . $item->discount . '"
                      data-discount_type="' . $item->discount_type . '" data-image="' . $image . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $statusChange . '" class="dropdown-item">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'price', 'discount', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function serviceStore(TopUpServiceRequest $request)
    {
        TopUp::select(['id'])->findOrFail($request->top_up_id);
        try {
            $service = new TopUpService();
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceUpdate(TopUpServiceRequest $request, $id)
    {
        $service = TopUpService::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Updated Successfully');
        } catch (\Exception $e) {
            return back() > with('error', $e->getMessage());
        }
    }

    public function serviceStatusChange(Request $request)
    {
        $service = TopUpService::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $service->status = 1;
            } else {
                $service->status = 0;
            }
            $service->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            TopUpService::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function serviceDelete($id)
    {
        $service = TopUpService::findOrFail($id);
        try {
            $this->fileDelete($service->image_driver, $service->image);
            $service->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUpService::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $this->fileDelete($query->image_driver, $query->image);
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Service has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUpService::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Service has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function serviceExport(Request $request)
    {
        try {
            return Excel::download(new TopUpServiceExport($request), 'services.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSample()
    {
        try {
            return $this->csvSampleDownload('topUp-service-sample.csv', 'topUp-service-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceImport(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        $topUp = TopUp::select(['id'])->findOrFail($request->topUp);
        try {
            Excel::import(new TopUpServiceImport($topUp->id), $request->file('importFile'));
            return back()->with('success', 'Services Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     :S\Wz	D8  D8  8  Http/Controllers/AAdmin/Module/CardServiceController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\CardServiceExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\CardServiceRequest;
use App\Imports\CardServiceImport;
use App\Models\Card;
use App\Models\CardService;
use App\Traits\Sample;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class CardServiceController extends Controller
{
    use Upload, Sample;

    public function serviceList(Request $request)
    {
        $data['card'] = Card::select(['id', 'name'])->findOrFail($request->card_id);
        $data['services'] = collect(CardService::with(['card'])->where('card_id', $request->card_id)->selectRaw('COUNT(id) AS totalService')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeService')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeServicePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveService')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveServicePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayService')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayServicePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthService')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthServicePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.card.service.index', $data);
    }

    public function serviceSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $services = CardService::orderBy('sort_by', 'ASC')->where('card_id', $request->card_id)->withCount(['codes' => function ($query) {
            $query->where('status', 1);
        }])
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%")
                        ->orWhere('price', 'LIKE', "%$search%")
                        ->orWhere('discount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($services)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image_driver ?? null, $item->image ?? null);
                $offerContent = $item->is_offered ? '<div class="trending-content"><i class="fa-light fa-badge-percent"></i>' . trans('Campaign') . '</div>' : '';
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="list-group-item">
                                  <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                </div>
                                <div class="flex-shrink-0 trending-notification">
                                ' . $offerContent . '
                                  <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                  </div>
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('active_code', function ($item) {
                return '<span class="badge bg-soft-secondary text-dark">' . number_format($item->codes_count) . '</span>';
            })
            ->addColumn('price', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . basicControl()->currency_symbol . formatAmount($item->price - $item->getDiscount()) . '</span> <sup class="badge bg-soft-dark text-dark ms-1">' . basicControl()->currency_symbol . formatAmount($item->getDiscount()) . ' off</sup>';
            })
            ->addColumn('discount', function ($item) {
                $showType = "%";
                if ($item->discount_type == 'flat') {
                    $showType = basicControl()->base_currency;
                }
                return '<span class="badge bg-soft-danger text-danger">' . $item->discount . ' ' . $showType . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.cardService.statusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.cardService.statusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.cardService.delete', $item->id);
                $edit = route('admin.cardService.update', $item->id);
                $image = getFile($item->image_driver ?? null, $item->image ?? null);
                $code = route('admin.cardServiceCode.list') . '?service_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                      data-route="' . $edit . '" data-name="' . $item->name . '" data-price="' . $item->price . '" data-discount="' . $item->discount . '"
                      data-discount_type="' . $item->discount_type . '" data-image="' . $image . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $code . '" class="dropdown-item">
                            <i class="fal fa-dice-d20 dropdown-item-icon"></i> ' . trans("Code List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_code', 'price', 'discount', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function serviceStore(CardServiceRequest $request)
    {
        Card::select(['id'])->findOrFail($request->card_id);
        try {
            $service = new CardService();
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceUpdate(CardServiceRequest $request, $id)
    {
        $service = CardService::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $service->fill($fillData)->save();
            return back()->with('success', 'Service Updated Successfully');
        } catch (\Exception $e) {
            return back() > with('error', $e->getMessage());
        }
    }

    public function serviceStatusChange(Request $request)
    {
        $service = CardService::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $service->status = 1;
            } else {
                $service->status = 0;
            }
            $service->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            CardService::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function serviceDelete($id)
    {
        $service = CardService::findOrFail($id);
        try {
            $this->fileDelete($service->image_driver, $service->image);
            $service->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            CardService::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $this->fileDelete($query->image_driver, $query->image);
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Service has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            CardService::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Service has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function serviceExport(Request $request)
    {
        try {
            return Excel::download(new CardServiceExport($request), 'services.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceSample()
    {
        try {
            return $this->csvSampleDownload('card-service-sample.csv', 'card-service-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function serviceImport(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        $card = Card::select(['id','category_id'])->findOrFail($request->card_id);

        try {
            Excel::import(new CardServiceImport($card->id), $request->file('importFile'));
            return back()->with('success', 'Services Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     :S\Ͼ)  )  8  Http/Controllers/AAdmin/Module/SellSummaryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\GiftCardSell;
use App\Models\SellPostPayment;
use App\Models\TopUpSell;
use App\Models\VoucherSell;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class SellSummaryController extends Controller
{
    use Notify;

    public function postSellTran()
    {
        $data['sell'] = collect(SellPostPayment::selectRaw('COUNT(id) AS totalSell')
            ->selectRaw('COUNT(CASE WHEN payment_release = 1 THEN id END) AS releaseSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 1 THEN id END) / COUNT(id)) * 100 AS releaseSellPercentage')
            ->selectRaw('COUNT(CASE WHEN payment_release = 0 THEN id END) AS upcomingSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 0 THEN id END) / COUNT(id)) * 100 AS upcomingSellPercentage')
            ->selectRaw('COUNT(CASE WHEN payment_release = 2 THEN id END) AS holdSell')
            ->selectRaw('(COUNT(CASE WHEN payment_release = 2 THEN id END) / COUNT(id)) * 100 AS holdSellPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todaySell')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todaySellPercentage')
            ->wherePayment_status(1)
            ->get()
            ->toArray())->collapse();

        return view('admin.sell_summary.postSell', $data);
    }

    public function postSellSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $sells = SellPostPayment::with(['user', 'sellPost', 'sellPost.user'])->wherePayment_status(1)->latest()
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where(function ($subquery) use ($filterName) {
                    $subquery->where('transaction', 'LIKE', '%' . $filterName . '%')
                        ->orWhereHas('sellPost', function ($qq) use ($filterName) {
                            $qq->where('title', 'LIKE', '%' . $filterName . '%');
                        })
                        ->orWhereHas('user', function ($qq) use ($filterName) {
                            $qq->where('firstname', 'LIKE', '%' . $filterName . '%')
                                ->orWhere('lastname', 'LIKE', '%' . $filterName . '%')
                                ->orWhere('username', 'LIKE', '%' . $filterName . '%');
                        });
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', '%' . $search . '%')
                        ->orWhere('price', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('sellPost', function ($qq) use ($search) {
                            $qq->where('title', 'LIKE', '%' . $search . '%');
                        })
                        ->orWhereHas('user', function ($qq) use ($search) {
                            $qq->where('firstname', 'LIKE', '%' . $search . '%')
                                ->orWhere('lastname', 'LIKE', '%' . $search . '%')
                                ->orWhere('username', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($sells)
            ->addColumn('trx', function ($item) {
                return $item->transaction;
            })
            ->addColumn('title', function ($item) {
                $route = route('sellPost.details', [slug(optional(@$item->sellPost)->title), optional(@$item->sellPost)->id]);
                return '<a href="' . $route . '">' . optional($item->sellPost)->title . '</a>';
            })
            ->addColumn('payment', function ($item) {
                return currencyPosition($item->price);
            })
            ->addColumn('seller_get', function ($item) {
                $extra = null;
                if (0 < $item->admin_amount) {
                    $extra = '<span class="badge bg-soft-danger text-danger ms-1">
                     ' . currencyPosition($item->admin_amount) . ' Charges</span>';
                }
                return currencyPosition($item->seller_amount) . $extra;
            })
            ->addColumn('seller', function ($item) {
                $url = route('admin.user.edit', optional($item->sellPost)->user_id);

                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                            <div class="flex-shrink-0">
                                ' . optional(optional($item->sellPost)->user)->profilePicture() . '
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->user?->fullname . '</h5>
                                <span class="fs-6 text-body">' . $item->user?->username . '</span>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('buyer', function ($item) {
                $url = route('admin.user.edit', $item->user_id);

                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                            <div class="flex-shrink-0">
                                ' . optional($item->user)->profilePicture() . '
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->user?->fullname . '</h5>
                                <span class="fs-6 text-body">' . $item->user?->username . '</span>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('status', function ($item) {
                if ($item->payment_release == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Released') . '
                  </span>';

                } elseif ($item->payment_release == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Upcoming') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Hold') . '
                  </span>';
                }
            })
            ->addColumn('payment_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {

                $resourceJson = htmlspecialchars(json_encode($item->sellPost->credential), ENT_QUOTES, 'UTF-8');

                if ($item->payment_release == 0) {
                    $btnName = 'Hold Payment';
                    $icon = 'fa-light fa-lock dropdown-item-icon';
                    $modalTarget = '#hold-modal';
                    $class = 'holdBtn';
                } elseif ($item->payment_release == 2) {
                    $btnName = 'Unhold Payment';
                    $icon = 'fa-light fa-unlock dropdown-item-icon';
                    $modalTarget = '#unhold-modal';
                    $class = 'unholdBtn';
                }


                $html = '<div class="btn-group" role="group">
                      <a href="#" class="btn btn-white btn-sm edit_button" data-bs-toggle="modal" data-bs-target="#myModal"
                                        data-info=\'' . $resourceJson . '\'>
                        <i class="fal fa-eye me-1"></i> ' . trans('Credentials') . '
                      </a>';
                if (in_array($item->payment_release, [0, 2])) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="javascript:void(0)" class="dropdown-item ' . $class . '" data-resource="' . $item->id . '"
                            data-bs-target="' . $modalTarget . '" data-bs-toggle="modal">
                            <i class="' . $icon . '"></i> ' . trans($btnName) . '
                        </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['trx', 'title', 'payment', 'seller_get', 'seller', 'buyer', 'status', 'payment_at', 'action'])
            ->make(true);
    }

    public function paymentHold(Request $request)
    {
        $hold = SellPostPayment::findOrFail($request->id);
        $hold->payment_release = 2;
        $hold->save();

        return back()->with('success', 'Update Successfully');
    }

    public function paymentUnhold(Request $request)
    {
        $hold = SellPostPayment::findOrFail($request->id);
        $hold->payment_release = 0;
        $hold->save();

        return back()->with('success', 'Update Successfully');
    }

}
PK     :S\F  F  2  Http/Controllers/AAdmin/Module/TopUpController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\TopUpStoreRequest;
use App\Models\Category;
use App\Models\TopUp;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TopUpController extends Controller
{
    use Upload;

    public function topUpList(Request $request)
    {
        $data['topUps'] = collect(TopUp::when(isset($request->category_id), function ($query) use ($request) {
            $query->where('category_id', $request->category_id);
        })
            ->selectRaw('COUNT(id) AS totalTopUp')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeTopUp')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveTopUp')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayTopUp')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayTopUpPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthTopUp')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthTopUpPercentage')
            ->get()
            ->toArray())->collapse();

        $data['category_id'] = $request->category_id ?? null;
        return view('admin.topUp.index', $data);
    }

    public function topUpListSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $categoryId = $request->category_id;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $topUps = TopUp::with(['category'])->orderBy('sort_by', 'ASC')
            ->withCount('activeServices')
            ->when(isset($categoryId), function ($query) use ($categoryId) {
                return $query->where('category_id', $categoryId);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%{$search}%")
                        ->orWhere('region', 'LIKE', "%{$search}%")
                        ->orWhereHas('category', function ($categoryQuery) use ($search) {
                            $categoryQuery->where('name', 'LIKE', "%{$search}%");
                        });
                });
            });
        return DataTables::of($topUps)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('name', function ($item) {
                $url = getFile($item->image->preview_driver ?? null, $item->image->preview ?? null);
                return '<a class="d-flex align-items-center me-2">
                            <div class="list-group-item">
                                <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                              </div>
                            <div class="flex-shrink-0">
                                <div class="avatar avatar-sm avatar-circle">
                                    <img class="avatar-img" src="' . $url . '" alt="Image Description">
                                </div>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                <p class="text-hover-primary mb-0">' . $item->region . '</p>
                            </div>
                        </a>
                    ';
            })
            ->addColumn('active_service', function ($item) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_services_count) . '</span>';
            })
            ->addColumn('instant_delivery', function ($item) {
                if ($item->instant_delivery == 1) {
                    return '<span class="badge bg-soft-primary text-primary">' . trans('Yes') . '</span>';

                } else {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('No') . '</span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('category', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <i class="' . $item->category?->icon . '"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->category?->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.topUpStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.topUpStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.topUpDelete', $item->id);
                $edit = route('admin.topUpEdit', $item->id);
                $service = route('admin.topUpService.list') . '?top_up_id=' . $item->id;

                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $service . '" class="dropdown-item">
                            <i class="fas fa-dice dropdown-item-icon"></i> ' . trans("Service List") . '
                        </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['checkbox', 'name', 'active_service', 'instant_delivery', 'status', 'category', 'created_at', 'action'])
            ->make(true);
    }

    public function topUpStore(TopUpStoreRequest $request)
    {
        if ($request->method() == 'GET') {
            $data['categories'] = Category::active()->type('top_up')->sort()->get();
            return view('admin.topUp.create', $data);
        } elseif ($request->method() == 'POST') {
            try {
                $topUp = new TopUp();
                $fillData = $request->except('_token');
                $orderFields = [
                    'field_value', 'field_placeholder', 'field_note',
                    'field_type', 'field_option_name', 'field_option_value'
                ];

                $fillData = $this->processOrderFields($fillData, $orderFields);
                $fillData['image'] = $this->processImages($fillData);

                $topUp->fill($fillData)->save();

                return back()->with('success', 'Top Up Created Successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function topUpStatusChange(Request $request)
    {
        $topUp = TopUp::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $topUp->status = 1;
            } else {
                $topUp->status = 0;
            }
            $topUp->save();
            return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function topUpSort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            TopUp::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function topUpDelete($id)
    {
        try {
            $topUp = TopUp::findOrFail($id);
            $images = [
                ['driver' => $topUp->image->image_driver ?? null, 'path' => $topUp->image->image ?? null],
                ['driver' => $topUp->image->preview_driver ?? null, 'path' => $topUp->image->preview ?? null],
                ['driver' => $topUp->image->banner_driver ?? null, 'path' => $topUp->image->banner ?? null],
            ];
            foreach ($images as $image) {
                $this->fileDelete($image['driver'], $image['path']);
            }
            $topUp->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function topUpEdit(TopUpStoreRequest $request, $id)
    {
        $topUp = TopUp::FindOrFail($id);
        if ($request->method() == 'GET') {
            $categories = Category::active()->type('top_up')->sort()->get();
            return view('admin.topUp.edit', compact('topUp', 'categories'));
        } elseif ($request->method() == 'POST') {
            try {
                $fillData = $request->except('_token');
                $orderFields = [
                    'field_value', 'field_placeholder', 'field_note',
                    'field_type', 'field_option_name', 'field_option_value'
                ];

                $fillData = $this->processOrderFields($fillData, $orderFields);
                $fillData['image'] = $this->processImages($fillData, $topUp);

                $topUp->fill($fillData)->save();

                return back()->with('success', 'Top Up has been updated successfully');
            } catch (\Exception $e) {
                return back()->with('error', $e->getMessage());
            }
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUp::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $images = [
                    ['driver' => $query->image->image_driver ?? null, 'path' => $query->image->image ?? null],
                    ['driver' => $query->image->preview_driver ?? null, 'path' => $query->image->preview ?? null],
                    ['driver' => $query->image->banner_driver ?? null, 'path' => $query->image->banner ?? null],
                ];
                foreach ($images as $image) {
                    $this->fileDelete($image['driver'], $image['path']);
                }
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Top Up has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            TopUp::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Top Up has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    private function processOrderFields($fillData, $orderFields)
    {
        foreach ($orderFields as $field) {
            if (!empty($fillData[$field])) {
                foreach ($fillData[$field] as $key => $fieldNames) {
                    if ($field === 'field_option_name' || $field === 'field_option_value') {
                        $fillData = $this->processOptionFields($fillData, $field, $fieldNames, $key);
                    } else {
                        foreach ($fieldNames as $fieldValue) {
                            $fillData['order_information'][$key][$field] = $fieldValue;
                            if ($field == 'field_value') {
                                $fillData['order_information'][$key]['field_name'] = title2snake($fieldValue);
                            }
                        }
                    }
                }
            }
        }

        return $fillData;
    }

    private function processOptionFields($fillData, $field, $fieldNames, $key)
    {
        if (!empty($fieldNames[0])) {
            if ($field === 'field_option_name') {
                $fillData['optionNames'][$key] = $fieldNames;
            } else {
                $optionNames = isset($fillData['optionNames'][$key]) ? $fillData['optionNames'][$key] : [];
                foreach ($fieldNames as $i => $fieldValue) {
                    if (isset($optionNames[$i])) {
                        $fillData['order_information'][$key]['option'][$optionNames[$i]] = $fieldValue;
                    }
                }
            }
        }

        return $fillData;
    }

    private function processImages($fillData, $topUP = null)
    {

        $images = [
            'image' => $fillData['image'] ?? null,
            'preview' => $fillData['preview_image'] ?? null,
        ];

        $imageData = [];
        foreach ($images as $key => $image) {
            if ($image) {
                $uploadedImage = $this->uploadImage($image, $key, $topUP);
                if ($uploadedImage) {
                    $imageData[$key] = $uploadedImage['path'];
                    $imageData[$key . '_driver'] = $uploadedImage['driver'];
                }
            } else {
                $imageData[$key] = $topUP->image->{$key} ?? null;
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null;
            }
        }

        return $imageData;
    }

    private function uploadImage($image, $key, $topUP = null)
    {
        try {
            return $this->fileUpload(
                $image,
                config('filelocation.topUp.path'),
                null,
                config('filelocation.topUp.' . $key . '_size'),
                'webp',
                60,
                $topUP->image->{$key} ?? null,
                $imageData[$key . '_driver'] = $topUP->image->{$key . '_driver'} ?? null,

            );
        } catch (\Exception $e) {
            return null;
        }
    }
}
PK     :S\b9z<  z<  6  Http/Controllers/AAdmin/Module/CardOrderController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\OrderDetail;
use App\Traits\MakeOrder;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CardOrderController extends Controller
{
    use Notify, MakeOrder;

    public function list(Request $request)
    {
        $status = -1;
        if ($request->type == 'pending') {
            $status = 3;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = collect(Order::payment()->type('card')->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS completeOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS completeOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS refundOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS refundOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayOrder')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayOrderPercentage')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->get()
            ->toArray())->collapse();

        $data['status'] = $status;
        return view('admin.card.order.index', $data);
    }

    public function listSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterService = $request->service;
        $status = $request->type;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::with(['user:id,firstname,lastname,username,image,image_driver', 'gateway:id,name',
         'orderDetails','orderDetails.detailable.card:id,name'])
            ->payment()->type('card')->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterService), function ($query) use ($filterService) {
                $query->whereHas('orderDetails', function ($qq) use ($filterService) {
                    $qq->where('name', 'LIKE', '%' . $filterService . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                })
                    ->orWhereHas('user', function ($query) use ($search) {
                        $query->where('firstname', 'LIKE', "%$search%")
                            ->orWhere('lastname', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('card', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 3) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending (stock-short)') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderCard.complete');
                $cancel = route('admin.orderCard.cancel');
                $view = route('admin.orderCard.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 3) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date','card', 'total_amount', 'payment_method', 'user', 'status', 'action'])
            ->make(true);
    }

    public function view(Request $request)
    {
        $data['order'] = Order::with(['orderDetails',
            'user:id,firstname,lastname,email,phone_code,phone,image_driver,image,balance', 'gateway:id,name'])
            ->where('utr', $request->orderId)->firstOrFail();

        $data['userTotalOrderCount'] = Order::type('card')->where('user_id', $data['order']->user_id)->count();
        return view('admin.card.order.view', $data);
    }

    public function complete(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('card')
            ->where('status', 3)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 1;
            $order->save();

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 1;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=complete',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'CARD_ORDER_COMPLETE', $params);
            $this->userPushNotification($order->user, 'CARD_ORDER_COMPLETE', $params, $action);
            $this->userFirebasePushNotification($order->user, 'CARD_ORDER_COMPLETE', $params);

            return back()->with('success', 'Order has been completed');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('card')
            ->where('status', 3)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 2;
            $order->save();

            $order->user->balance += $order->amount;
            $order->user->save();

            $this->newTransaction($order->user_id, $order->amount, 'Order Refund For Card', '+', $order->id, Order::class);

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 2;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=refund',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'CARD_ORDER_CANCEL', $params);
            $this->userPushNotification($order->user, 'CARD_ORDER_CANCEL', $params, $action);
            $this->userFirebasePushNotification($order->user, 'CARD_ORDER_CANCEL', $params);

            return back()->with('success', 'Order has been canceled');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function codeSend(Request $request)
    {
        if (!$request->orderDetailsId) {
            return back()->with('error', 'Something went wrong. Please try again');
        }

        if (!$request->passcode) {
            return back()->with('error', 'Passcode is required');
        }

        $passcodes = array_filter($request->passcode);

        $orderDetail = OrderDetail::select(['id', 'user_id', 'order_id', 'name', 'qty', 'stock_short', 'status', 'card_codes'])
            ->with(['order:id,status,utr', 'user'])->findOrFail($request->orderDetailsId);

        try {
            $stock_short = max(0, $orderDetail->qty - count($passcodes));

            $orderDetail->card_codes = $passcodes;
            $orderDetail->stock_short = $stock_short;
            $orderDetail->status = ($stock_short == 0) ? 1 : 3;
            $orderDetail->save();

            $isStockShortExits = OrderDetail::where('order_id', $orderDetail->order_id)->where('status', 3)->exists();

            if (!$isStockShortExits) {
                $orderDetail->order->status = 1;
                $orderDetail->order->save();
            }

            $params = [
                'order_id' => $orderDetail->order?->utr,
                'service_name' => $orderDetail->name ?? null,
            ];

            $action = [
                "link" => route('user.cardOrder') . '?type=all',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($orderDetail->user, 'CARD_CODE_SEND', $params);
            $this->userPushNotification($orderDetail->user, 'CARD_CODE_SEND', $params, $action);
            $this->userFirebasePushNotification($orderDetail->user, 'CARD_CODE_SEND', $params);

            return back()->with('success', 'Code has been send');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     :S\@5]    5  Http/Controllers/AAdmin/Module/CampaignController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Campaign;
use App\Models\CardService;
use App\Models\TopUpService;
use Carbon\Carbon;
use Illuminate\Http\Request;

class CampaignController extends Controller
{
    public function view()
    {
        $data['campaign'] = Campaign::firstOrNew();

        $data['topUpServices'] = TopUpService::select(['id', 'name', 'image', 'image_driver', 'status', 'sort_by', 'is_offered'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get();

        $data['cardServices'] = CardService::select(['id', 'name', 'image', 'image_driver', 'status', 'sort_by', 'is_offered'])
            ->where('status', 1)->orderBy('sort_by', 'ASC')->get();

        return view('admin.campaign.view', $data);
    }

    public function getTopUpService(Request $request)
    {
        $offeredTopUpServices = TopUpService::whereIn('id', $request->selectedIds)->where('status', 1)
            ->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->price = $query->campaign_data->price ?? $query->price;
                $query->discount = $query->campaign_data->discount ?? $query->discount;
                $query->discount_type = $query->campaign_data->discount_type ?? $query->discount_type;
                $query->max_sell = $query->campaign_data->max_sell ?? $query->max_sell;

                return $query;
            });
        return response()->json(['status' => true, 'offerServices' => $offeredTopUpServices]);
    }

    public function getCardService(Request $request)
    {
        $offeredCardServices = CardService::whereIn('id', $request->selectedIds)->where('status', 1)
            ->orderBy('sort_by', 'ASC')->get()->map(function ($query) {
                $query->price = $query->campaign_data->price ?? $query->price;
                $query->discount = $query->campaign_data->discount ?? $query->discount;
                $query->discount_type = $query->campaign_data->discount_type ?? $query->discount_type;
                $query->max_sell = $query->campaign_data->max_sell ?? $query->max_sell;

                return $query;
            });
        return response()->json(['status' => true, 'offerServices' => $offeredCardServices]);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'date' => 'required',
        ]);

        $filterDate = explode('to', $request->date);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $campaign = Campaign::firstOrNew();
        $campaign->name = $request->name;
        $campaign->start_date = Carbon::parse($startDate);
        $campaign->end_date = Carbon::parse($endDate);
        $campaign->status = $request->status;
        $campaign->save();

        //Top Up
        $allTopUpServices = TopUpService::where('status', 1)->get();

        $topUpServicesToOffer = $allTopUpServices->whereIn('id', $request->topups);
        $topUpServicesNotOffered = $allTopUpServices->whereNotIn('id', $request->topups);

        TopUpService::whereIn('id', $topUpServicesNotOffered->pluck('id'))->update(['is_offered' => 0]);

        foreach ($topUpServicesToOffer as $service) {
            $this->campaignDataStore($service, $request->topup_price[$service->id], $request->topup_discount[$service->id],
                $request->topup_discount_type[$service->id], $request->topup_max_sell[$service->id]);

            $service->is_offered = 1;
            $service->save();
        }

        //Card
        $allCardServices = CardService::where('status', 1)->get();

        $cardServicesToOffer = $allCardServices->whereIn('id', $request->cards);
        $cardServicesNotOffered = $allCardServices->whereNotIn('id', $request->cards);

        CardService::whereIn('id', $cardServicesNotOffered->pluck('id'))->update(['is_offered' => 0]);

        foreach ($cardServicesToOffer as $service) {
            $this->campaignDataStore($service, $request->card_price[$service->id], $request->card_discount[$service->id],
                $request->card_discount_type[$service->id], $request->card_max_sell[$service->id]);

            $service->is_offered = 1;
            $service->save();
        }

        return back()->with('success', 'Campaign Updated Successfully');
    }


    protected function campaignDataStore($service, $price, $discount, $discount_type, $max_sell): void
    {
        $campaignData = [
            'price' => $price,
            'discount' => $discount,
            'discount_type' => $discount_type,
            'max_sell' => $max_sell,
        ];

        $service->campaign_data = $campaignData;
        $service->save();
    }
}
PK     :S\И"  "  3  Http/Controllers/AAdmin/Module/ReviewController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Card;
use App\Models\Review;
use App\Models\TopUp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class ReviewController extends Controller
{
    public function list()
    {
        $data['reviews'] = collect(Review::selectRaw('COUNT(id) AS totalReview')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeReview')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveReview')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayReview')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayReviewPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthReview')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthReviewPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.review.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterRating = $request->filterRating;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $cards = Review::with(['user:id,firstname,lastname,username,image,image_driver','reviewable'])->latest()
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->whereHas('reviewable', function ($reviewQuery) use ($filterName) {
                    $reviewQuery->where('name', 'LIKE', '%' . $filterName . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(isset($filterRating), function ($query) use ($filterRating) {
                if ($filterRating != "all") {
                    return $query->where('rating', $filterRating);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('comment', 'LIKE', "%{$search}%")
                        ->orWhereHas('reviewable', function ($reviewQuery) use ($search) {
                            $reviewQuery->where('name', 'LIKE', "%{$search}%");
                        })
                        ->orWhereHas('user', function ($reviewerQuery) use ($search) {
                            $reviewerQuery->where('firstname', 'LIKE', "%{$search}%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%");
                        });
                });
            });
        return DataTables::of($cards)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('game', function ($item) {
                if ($item->reviewable_type == TopUp::class) {
                    $url = route('admin.topUpEdit', $item->reviewable_id);
                } elseif ($item->reviewable_type == Card::class) {
                    $url = route('admin.card.edit', $item->reviewable_id);
                }
                $img = getFile($item->reviewable->image->preview_driver ?? null, $item->reviewable->image->preview ?? null);
                return '<a class="d-flex align-items-center" href="' . $url . '">
                    <div class="avatar">
                      <img class="avatar-img" src="' . $img . '" alt="Image Description">
                    </div>
                    <div class="flex-grow-1 ms-3">
                      <span class="card-title h5 text-dark text-inherit">' . $item->reviewable?->name . '</span>
                    </div>
                  </a>
                 ';

            })
            ->addColumn('reviewer', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('review', function ($item) {
                $star = asset('assets/admin/img/star.svg');
                $starRating = '';
                for ($i = 0; $i < $item->rating; $i++) {
                    $starRating .= '<img src="' . $star . '" alt="Review rating" width="14">';
                }
                return '<div class="text-wrap" style="width: 18rem;">
                          <div class="d-flex gap-1 mb-2">
                            ' . $starRating . '
                          </div>
                         <p>' . $item->comment . '</p>
                        </div>';
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Publish') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Hold') . '
                  </span>';
                }
            })
            ->rawColumns(['checkbox', 'game', 'reviewer', 'review', 'date', 'status'])
            ->make(true);
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Review::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Review has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Review::whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Review has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }
}
PK     :S\?"  "  <  Http/Controllers/AAdmin/Module/CardServiceCodeController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Exports\CodeExport;
use App\Http\Controllers\Controller;
use App\Imports\CodeImport;
use App\Models\CardService;
use App\Models\Code;
use App\Traits\Sample;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Yajra\DataTables\Facades\DataTables;

class CardServiceCodeController extends Controller
{
    use Sample;

    public function list(Request $request)
    {
        $data['service'] = CardService::with('card')->select(['id', 'name', 'card_id'])->findOrFail($request->service_id);
        $data['services'] = CardService::select(['id', 'name', 'card_id', 'sort_by', 'created_at'])
            ->where('card_id', $data['service']->card_id)->orderBy('sort_by', 'ASC')->get();
        $data['codes'] = collect(Code::serviceWise(CardService::class, $request->service_id)
            ->selectRaw('COUNT(id) AS totalCode')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCode')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCodePercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCode')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCodePercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCode')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCodePercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCode')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCodePercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.card.code.index', $data);
    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $codes = Code::serviceWise(CardService::class, $request->service_id)->orderBy('id', 'desc')->when(isset($filterName), function ($query) use ($filterName) {
            return $query->where('passcode', 'LIKE', '%' . $filterName . '%');
        })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('passcode', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($codes)
            ->addColumn('checkbox', function ($item) {
                return '<input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';

            })
            ->addColumn('passcode', function ($item) {
                $element = "referralsKeyCode" . $item->id;
                return '<div class="input-group input-group-sm input-group-merge table-input-group">
                        <input id="' . $element . '" type="text" class="form-control" readonly value="' . $item->passcode . '">
                        <a class="js-clipboard input-group-append input-group-text" onclick="copyFunction(\'' . $element . '\')" href="javascript:void(0)" title="Copy to clipboard">
                            <i id="referralsKeyCodeIcon' . $item->id . '" class="bi-clipboard"></i>
                        </a>
                    </div>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->rawColumns(['checkbox', 'passcode', 'status', 'created_at'])
            ->make(true);
    }

    public function store(Request $request)
    {
        $service = CardService::select(['id'])->findOrFail($request->service_id);
        try {
            if ($request->passcode && 0 < count($request->passcode)) {
                foreach ($request->passcode as $code) {
                    Code::firstOrCreate([
                        'codeable_type' => CardService::class,
                        'codeable_id' => $service->id,
                        'passcode' => $code
                    ]);
                }
            }
            return back()->with('success', 'Code Added Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function multipleDelete(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Code::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->delete();
                return $query;
            });
            session()->flash('success', 'Code has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function multipleStatusChange(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select row.');
            return response()->json(['error' => 1]);
        } else {
            Code::select(['id', 'status'])->whereIn('id', $request->strIds)->get()->map(function ($query) {
                if ($query->status) {
                    $query->status = 0;
                } else {
                    $query->status = 1;
                }
                $query->save();
                return $query;
            });
            session()->flash('success', 'Code Status has been changed successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function export(Request $request)
    {
        try {
            $data = collect([
                'codeable_id' => $request->service_id,
                'codeable_type' => CardService::class,
            ])->all();
            return Excel::download(new CodeExport($data), 'codes.csv');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function sample()
    {
        try {
            return $this->csvSampleDownload('code.csv', 'code-sample');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function import(Request $request)
    {
        $this->validate($request, [
            'importFile' => 'required|file|mimes:csv',
        ]);

        CardService::select(['id'])->findOrFail($request->service_id);

        try {
            $data = collect([
                'codeable_id' => $request->service_id,
                'codeable_type' => CardService::class,
            ])->all();
            Excel::import(new CodeImport($data), $request->file('importFile'));
            return back()->with('success', 'Codes Imported Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     :S\Ǝ5  5  7  Http/Controllers/AAdmin/Module/TopUpOrderController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Traits\MakeOrder;
use App\Traits\Notify;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class TopUpOrderController extends Controller
{
    use Notify, MakeOrder;

    public function list(Request $request)
    {
        $status = -1;
        if ($request->type == 'pending') {
            $status = 0;
        } elseif ($request->type == 'complete') {
            $status = 1;
        } elseif ($request->type == 'refund') {
            $status = 2;
        }

        $data['orders'] = collect(Order::payment()->type('topup')->selectRaw('COUNT(id) AS totalOrder')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS completeOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS completeOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 2 THEN id END) AS refundOrder')
            ->selectRaw('(COUNT(CASE WHEN status = 2 THEN id END) / COUNT(id)) * 100 AS refundOrderPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayOrder')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayOrderPercentage')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->get()
            ->toArray())->collapse();

        $data['status'] = $status;
        return view('admin.topUp.order.index', $data);
    }

    public function listSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterService = $request->service;
        $status = $request->type;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::with(['user:id,firstname,lastname,username,image,image_driver',
            'gateway:id,name', 'orderDetails', 'orderDetails.detailable.topUp:id,name'])
            ->payment()->type('topup')->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterService), function ($query) use ($filterService) {
                $query->whereHas('orderDetails', function ($qq) use ($filterService) {
                    $qq->where('name', 'LIKE', '%' . $filterService . '%');
                });
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                })
                    ->orWhereHas('user', function ($query) use ($search) {
                        $query->where('firstname', 'LIKE', "%$search%")
                            ->orWhere('lastname', 'LIKE', "%$search%")
                            ->orWhere('username', 'LIKE', "%$search%");
                    });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('top_up', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user?->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user?->firstname . ' ' . $item->user?->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user?->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderTopUp.complete');
                $cancel = route('admin.orderTopUp.cancel');
                $view = route('admin.orderTopUp.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 0) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'top_up', 'total_amount', 'payment_method', 'user', 'status', 'action'])
            ->make(true);
    }

    public function view(Request $request)
    {
        $data['order'] = Order::with(['orderDetails',
            'user:id,firstname,lastname,email,phone_code,phone,image_driver,image,balance', 'gateway:id,name'])
            ->where('utr', $request->orderId)->firstOrFail();

        $data['userTotalOrderCount'] = Order::type('topup')->where('user_id', $data['order']->user_id)->count();
        return view('admin.topUp.order.view', $data);
    }

    public function complete(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('topup')
            ->where('status', 0)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 1;
            $order->save();

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 1;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
                'service_name' => $order->orderDetails[0]->name ?? null,
            ];

            $action = [
                "link" => route('user.topUpOrder') . '?type=complete',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'TOP_UP_ORDER_COMPLETE', $params);
            $this->userPushNotification($order->user, 'TOP_UP_ORDER_COMPLETE', $params, $action);
            $this->userFirebasePushNotification($order->user, 'TOP_UP_ORDER_COMPLETE', $params);

            return back()->with('success', 'Order has been completed');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function cancel(Request $request)
    {
        $order = Order::with(['orderDetails:id,order_id,status,name', 'user'])->payment()->type('topup')
            ->where('status', 0)->where('utr', $request->orderId)->firstOrFail();

        try {
            $order->status = 2;
            $order->save();

            $order->user->balance += $order->amount;
            $order->user->save();

            $this->newTransaction($order->user_id, $order->amount, 'Order Refund For TopUp', '+', $order->id, Order::class);

            if (!empty($order->orderDetails)) {
                foreach ($order->orderDetails as $detail) {
                    $detail->status = 2;
                    $detail->save();
                }
            }

            $params = [
                'order_id' => $order->utr,
                'service_name' => $order->orderDetails[0]->name ?? null,
            ];

            $action = [
                "link" => route('user.topUpOrder') . '?type=refund',
                "icon" => "fa fa-money-bill-alt text-white"
            ];

            $this->sendMailSms($order->user, 'TOP_UP_ORDER_CANCEL', $params);
            $this->userPushNotification($order->user, 'TOP_UP_ORDER_CANCEL', $params, $action);
            $this->userFirebasePushNotification($order->user, 'TOP_UP_ORDER_CANCEL', $params);

            return back()->with('success', 'Order has been canceled');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }
}
PK     :S\W,'  '  5  Http/Controllers/AAdmin/Module/CategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Http\Requests\CategoryStoreRequest;
use App\Http\Requests\CategoryUpdateRequest;
use App\Models\Category;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

class CategoryController extends Controller
{
    use Upload;

    public function categoryList(Request $request)
    {
        if (!in_array($request->type, ['top_up', 'card'])) {
            return back()->with('error', 'Something went wrong');
        }
        $data['categories'] = collect(Category::selectRaw('COUNT(id) AS totalCategory')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeCategory')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS inActiveCategory')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS inActiveCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) AS todayCategory')
            ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURRENT_DATE THEN id END) / COUNT(id)) * 100 AS todayCategoryPercentage')
            ->selectRaw('COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) AS thisMonthCategory')
            ->selectRaw('(COUNT(CASE WHEN MONTH(created_at) = MONTH(CURDATE()) AND YEAR(created_at) = YEAR(CURDATE()) THEN id END) / COUNT(id)) * 100 AS thisMonthCategoryPercentage')
            ->where('type', $request->type)
            ->get()
            ->toArray())->collapse();
        $data['pageTitle'] = snake2Title($request->type) . ' Category';
        $data['type'] = $request->type;
        return view('admin.category.index', $data);
    }


    public function categoryListSearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $categories = Category::orderBy('sort_by', 'ASC')->where('type', $request->type)
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('name', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('name', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($categories)
            ->addColumn('name', function ($item) {
                return '<a class="d-flex align-items-center me-2">
                                <div class="list-group-item">
                                    <i class="sortablejs-custom-handle bi-grip-horizontal list-group-icon"></i>
                                  </div>
                                <i class="' . $item->icon . '"></i>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->name . '</h5>
                                </div>
                              </a>';

            })
            ->addColumn('active_service', function ($item) use ($request) {
                return '<span class="badge bg-soft-primary text-primary">' . number_format($item->active_children) . '</span>';
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('In Active') . '
                  </span>';
                }
            })
            ->addColumn('created_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                if ($item->status) {
                    $statusBtn = "In-Active";
                    $statusChange = route('admin.categoryStatusChange') . '?id=' . $item->id . '&status=in-active';
                } else {
                    $statusBtn = "Active";
                    $statusChange = route('admin.categoryStatusChange') . '?id=' . $item->id . '&status=active';
                }
                $delete = route('admin.categoryDelete', $item->id);
                if ($item->type == 'top_up') {
                    $childRoute = route('admin.topUpList') . '?category_id=' . $item->id;
                } elseif ($item->type == 'card') {
                    $childRoute = route('admin.card.list') . '?category_id=' . $item->id;
                } elseif ($item->type == 'game') {
                    $childRoute = route('admin.game.list') . '?category_id=' . $item->id;
                }
                $html = '<div class="btn-group sortable" role="group" data-id ="' . $item->id . '">
                      <a href="javascript:void(0)" class="btn btn-white btn-sm edit_btn" data-bs-target="#editModal" data-bs-toggle="modal"
                       data-name="' . $item->name . '" data-icon="' . $item->icon . '"
                       data-route="' . route('admin.categoryEdit', $item->id) . '">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item" href="' . $childRoute . '">
                          <i class="fal fa-eye dropdown-item-icon"></i> ' . trans("Child") . '
                       </a>
                        <a href="' . $statusChange . '" class="dropdown-item edit_user_btn">
                            <i class="fal fa-badge dropdown-item-icon"></i> ' . trans($statusBtn) . '
                        </a>
                        <a class="dropdown-item delete_btn" href="javascript:void(0)" data-bs-target="#delete"
                           data-bs-toggle="modal" data-route="' . $delete . '">
                          <i class="fal fa-trash dropdown-item-icon"></i> ' . trans("Delete") . '
                       </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['name', 'active_service', 'status', 'created_at', 'action'])
            ->make(true);
    }

    public function categoryCreate(CategoryStoreRequest $request)
    {
        if (!in_array($request->type, ['top_up', 'card'])) {
            return back()->with('error', 'Something went wrong');
        }
        try {
            $category = new Category();
            $fillData = $request->except('_token');
            $category->fill($fillData)->save();
            return back()->with('success', 'Category Created Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit(CategoryUpdateRequest $request, $id)
    {
        $category = Category::findOrFail($id);
        try {
            $fillData = $request->except('_token');
            $category->fill($fillData)->save();
            return back()->with('success', 'Category Updated Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryStatusChange(Request $request)
    {
        $category = Category::select(['id', 'status'])->findOrFail($request->id);
        try {
            if ($request->status == 'active') {
                $category->status = 1;
            } else {
                $category->status = 0;
            }
            $category->save();
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
        return back()->with('success', 'Status ' . ucfirst($request->status) . ' Successfully');
    }

    public function categorySort(Request $request)
    {
        $sortItems = $request->sort;
        foreach ($sortItems as $key => $value) {
            Category::where('id', $value)->update(['sort_by' => $key + 1]);
        }
    }

    public function categoryDelete($id)
    {
        try {
            Category::findOrFail($id)->delete();
            return back()->with('success', 'Deleted Successfully');
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     :S\SY6g  g  =  Http/Controllers/AAdmin/Module/SellPostCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Module;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\SellPost;
use App\Models\Language;
use App\Models\SellPostCategory;
use App\Models\SellPostCategoryDetail;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Traits\Notify;
use App\Traits\SellPostTrait;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SellPostCategoryController extends Controller
{
    use Upload, Notify, SellPostTrait;

    public function category()
    {
        $manageCategory = SellPostCategory::with(['details'])->withCount('activePost')->latest()->get();
        return view('admin.sellPostCategory.categoryList', compact('manageCategory'));
    }

    public function categoryCreate()
    {
        $languages = Language::all();
        return view('admin.sellPostCategory.categoryCreate', compact('languages'));
    }

    public function categoryStore(Request $request, $language)
    {

        $purifiedData = $request->all();
        DB::beginTransaction();
        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
                'image' => 'required|mimes:jpg,jpeg,png',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'image.required' => 'Image is required',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $category = new SellPostCategory();

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if ($request->has('status')) {
                $category->status = $request->status;
            }

            if ($request->has('sell_charge')) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->hasFile('image')) {
                try {
                    $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp');
                    $category->image = $imageUp['path'];
                    $category->image_driver = $imageUp['driver'];
                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            $category->save();

            $category->details()->create([
                'language_id' => $language,
                'name' => $purifiedData["name"][$language],
            ]);

            DB::commit();

            return back()->with('success', 'Category Successfully Saved');
        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit($id)
    {
        $languages = Language::all();
        $categoryDetails = SellPostCategoryDetail::with('sellPostCategory')->where('sell_post_category_id', $id)->get()->groupBy('language_id');
        return view('admin.sellPostCategory.categoryEdit', compact('languages', 'categoryDetails', 'id'));
    }


    public function categoryUpdate(Request $request, $id, $language_id)
    {
        $purifiedData = $request->all();
        DB::beginTransaction();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            $category = SellPostCategory::findOrFail($id);

            if ($request->hasFile('image')) {
                $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp', null, $category->image, $category->image_driver);
                $category->image = $imageUp['path'];
                $category->image_driver = $imageUp['driver'];
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if (isset($purifiedData['sell_charge'])) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->has('status')) {
                $category->status = $request->status;
            }
            $category->save();

            $category->details()->updateOrCreate([
                'language_id' => $language_id
            ],
                [
                    'name' => $purifiedData["name"][$language_id],
                ]
            );
            DB::commit();

            return back()->with('success', 'Category Successfully Updated');

        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function statusSellMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Category.');
            return response()->json(['error' => 1]);
        } else {
            SellPostCategory::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been active');
            return response()->json(['success' => 1]);
        }
    }

    public function categoryDelete($id)
    {
        $categoryData = SellPostCategory::findOrFail($id);
        if (0 < $categoryData->post->count()) {
            session()->flash('warning', 'This Category has a lot of post');
            return back();
        }

        $this->fileDelete($categoryData->image_driver, $categoryData->image);

        $categoryData->delete();
        return back()->with('success', 'Category has been deleted');
    }

    public function sellList($status = null)
    {
        $data['value'] = $this->getValueByStatus($status);
        abort_if(!isset($data['value']), 404);

        $data['sellPost'] = collect(SellPost::selectRaw('COUNT(id) AS totalPost')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvalPost')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvalPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingPost')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS holdPost')
            ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS holdPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 5 THEN id END) AS hardPost')
            ->selectRaw('(COUNT(CASE WHEN status = 5 THEN id END) / COUNT(id)) * 100 AS hardPostPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.sellPostList.index', $data);
    }

    public function sellListSearch(Request $request, $status = null)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterUser = $request->user;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $posts = SellPost::status($status)->latest()
            ->has('user')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('title', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterUser), function ($query) use ($filterUser) {
                $query->whereHas('user', function ($qq) use ($filterUser) {
                    $qq->where('firstname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('lastname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('username', 'LIKE', '%' . $filterUser . '%');
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('title', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('category.details', function ($qq) use ($search) {
                            $qq->where('name', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($posts)
            ->addColumn('title', function ($item) {
                $extra = null;
                if ($item->payment_status) {
                    $extra = '<span class="badge bg-success">' . trans('Sold') . '</span>
                             <span class="badge bg-secondary">' . $item->sellPostPayment?->transaction . '</span>';
                }
                return $item->title . ' ' . $extra;

            })
            ->addColumn('category', function ($item) {
                return optional($item->category)->details->name??null;
            })
            ->addColumn('price', function ($item) {
                return '<h5>' . currencyPosition($item->price) . '</h5>';
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.edit", $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('status', function ($item) {
                return $item->statusMessage;
            })
            ->addColumn('date_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                $conversion = route('admin.sellPost.offer', [$item->id]);
                $edit = route('admin.sell.details', $item->id);

                $html = '<div class="btn-group sortable" role="group">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $conversion . '" class="dropdown-item">
                            <i class="fas fa-comments dropdown-item-icon"></i> ' . trans("Conversation") . '
                        </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['title', 'category', 'price', 'user', 'status', 'date_at', 'action'])
            ->make(true);
    }

    public function sellDetails($id)
    {
        $data['activity'] = ActivityLog::whereSell_post_id($id)->with('activityable:id,username,image,image_driver')->orderBy('id', 'desc')->get();

        $data['category'] = SellPostCategory::with('details')->whereStatus(1)->get();
        $data['sellPost'] = SellPost::findOrFail($id);

        return view('admin.sellPostList.edit', $data);
    }

    public function SellUpdate(Request $request, $id)
    {
        $purifiedData = $request->all();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'title' => 'required|max:40',
                'price' => 'required',
                'details' => 'required',
            ];
            $message = [
                'title.required' => 'Title field is required',
                'price.required' => 'Price field is required',
                'details.required' => 'Details field is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }


            $gameSell = SellPost::findOrFail($id);
            $gameSell->category_id = $request->category;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }

            $collection = collect($request);
            $reqField = [];
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }


            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqFieldSpecification[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }


            $images = array();
            if ($request->hasFile('image')) {

                try {
                    $gameImage = $purifiedData['image'];
                    $gamesellDriver = $gameSell->image_driver ?? 'local';
                    $oldImages = $request->oldImage ?? [];
                    $images = [];
                    $imagesDriver = [];

                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver[] = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $key => $imageOld) {
                            if ($imageOld == 'changed') {
                                $this->fileDelete($gamesellDriver, $oldImages[$key]);
                                unset($oldImages[$key]);
                            }
                        }
                    }

                    $mergedImages = array_merge($oldImages, $images);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver['0'];

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            if (isset($purifiedData['title'])) {
                $gameSell->title = $request->title;
            }
            if (isset($purifiedData['price'])) {
                $gameSell->price = $request->price;
            }

            if (isset($purifiedData['credential'])) {
                $gameSell->credential = $request->credential;
            }

            if (isset($purifiedData['details'])) {
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['status'])) {
                $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
            }


            $gameSell->save();


            return back()->with('success', 'Successfully Updated');
        } catch (\Exception$e) {

            return back();
        }
    }

    public function sellAction(Request $request)
    {
        DB::beginTransaction();
        try {
            $gameSell = SellPost::findOrFail($request->sell_post_id);
            $gameSell->status = $request->status;
            $gameSell->save();


            $title = $gameSell->activityTitle;
            $admin = Auth::user();

            $activity = new ActivityLog();
            $activity->title = $title;
            $activity->sell_post_id = $request->sell_post_id;
            $activity->description = $request->comments;

            $admin->activities()->save($activity);
            DB::commit();

            $user = $gameSell->user;
            $msg = [
                'title' => $gameSell->title,
                'status' => $title,
                'comments' => $request->comments

            ];
            $action = [
                "link" => route('sellPost.details', [@$gameSell->title, $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_APPROVE', $msg, $action);

            $this->sendMailSms($user, 'SELL_APPROVE', [
                'title' => $gameSell->title,
                'status' => $title,
                'short_comment' => $request->comments
            ]);

            return back()->with('success', 'Update Successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function SellDelete($id, $imgDelete)
    {
        $images = [];
        $galleryImage = SellPost::findOrFail($id);
        $old_images = $galleryImage->image;

        if (!empty($old_images)) {
            foreach ($old_images as $file) {
                $newString = Str::replaceFirst('sellingPost/', '', $file);
                if ($newString == $imgDelete) {
                    $this->fileDelete($galleryImage->image_driver, $file);
                } else {
                    $images[] = $file;
                }
            }
        }
        $galleryImage->image = $images;
        $galleryImage->save();
        return back()->with('success', 'Image has been deleted');
    }

    public function sellPostOffer($sellPostId)
    {
        $sellPostOffer = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($sellPostId)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $offer = null;
        if (0 < count($sellPostOffer)) {
            $offer = $sellPostOffer->first();

            if (!$offer->uuid) {
                $offer->uuid = Str::uuid();
                $offer->save();
            }

            return redirect()->route('admin.sellPost.conversation', $offer->uuid);
        } else {
            $offer = null;
        }


        $data['sellPostOffer'] = $sellPostOffer;
        $data['offer'] = $offer;
        return view('admin.sellPostList.offerList', $data);
    }

    public function conversation($uuid)
    {
        $offer = SellPostOffer::with(['user', 'lastMessage'])->where('uuid', $uuid)
            ->firstOrFail();

        $data['sellPostOffer'] = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($offer->sell_post_id)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $data['persons'] = SellPostChat::where([
            'offer_id' => $offer->id,
            'sell_post_id' => $offer->sell_post_id
        ])
            ->with('chatable')
            ->get()->pluck('chatable')->unique('chatable');

        $data['offer'] = $offer;

        return view('admin.sellPostList.offerList', $data);
    }

}
PK     :S\Fև    6  Http/Controllers/AAdmin/GoogleApiSettingController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\GoogleSheetApi;
use Illuminate\Http\Request;
use App\Traits\Upload;

class GoogleApiSettingController extends Controller
{
    use Upload;
    public function googleAPISetting()
    {
        return view('admin.control_panel.google_api_setting');
    }

    public function googleAPICredentialUpload(Request $request)
    {

        $googleSheetCredential = GoogleSheetApi::firstOrFail();

        $request->validate([
              'credential' => 'nullable',
        ]);

        if ($request->hasFile('credential')) {
            try {
                $file = $this->fileUpload($request->credential, config('filelocation.googleTranslateCredential.path'), config('filesystems.default'));
                if ($file) {
                    $file_credential = $file['path'];
                    $file_driver = 'local';
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'File could not be uploaded.');
            }
        }

        $response = $googleSheetCredential->update([
            'api_credential_file' => $file_credential,
            'file_driver' => $file_driver,
        ]);

        if (!$response){
            throw  new \Exception('Something went wrong');
        }


        return back()->with('success', 'File uploaded successfully.');

    }
}
PK     :S\X=% =% +  Http/Controllers/AAdmin/UsersController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Jobs\UserAllRecordDeleteJob;
use App\Models\Deposit;
use App\Models\Fund;
use App\Models\Gateway;
use App\Models\Investment;
use App\Models\Language;
use App\Models\Order;
use App\Models\Payout;
use App\Models\PayoutMethod;
use App\Models\Referral;
use App\Models\ReferralBonus;
use App\Models\Transaction;
use App\Models\User;
use App\Models\UserKyc;
use App\Models\UserLogin;
use App\Models\UserTracking;
use App\Models\UserWallet;
use App\Rules\PhoneLength;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Stevebauman\Purify\Facades\Purify;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Validation\Rule;
use App\Traits\Upload;
use App\Traits\Notify;
use Exception;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;

class UsersController extends Controller
{
    use Upload, Notify;

    public function index(Request $request)
    {
        $data['reqVal'] = $request->status;
        $data['basic'] = basicControl();
        $userRecord = \Cache::get('userRecord');
        if (!$userRecord) {
            $userRecord = User::withTrashed()->selectRaw('COUNT(id) AS totalUserWithTrashed')
                ->selectRaw('COUNT(CASE WHEN deleted_at IS NULL THEN id END) AS totalUser')
                ->selectRaw('(COUNT(CASE WHEN deleted_at IS NULL THEN id END) / COUNT(id)) * 100 AS totalUserPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS activeUser')
                ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS activeUserPercentage')
                ->selectRaw('COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) AS todayJoin')
                ->selectRaw('(COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN id END) / COUNT(id)) * 100 AS todayJoinPercentage')
                ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS deactivateUser')
                ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS deactivateUserPercentage')
                ->get()
                ->toArray();
            \Cache::put('userRecord', $userRecord);
        }
        $data['languages'] = Language::all();
        $data['allCountry'] = config('country');
        return view('admin.user_management.list', $data, compact('userRecord'));

    }

    public function search(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterStatus = $request->filterStatus;
        $filterName = $request->filterName;
        $filterEmailVerification = $request->filterEmailVerification;
        $filterSMSVerification = $request->filterSMSVerification;
        $filterTwoFaSecurity = $request->filterTwoFaVerification;
        $reqVal = $request->reqVal;

        $users = User::query()->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('email', 'LIKE', "%{$search}%")
                    ->orWhere('username', 'LIKE', "%{$search}%")
                    ->orWhere('firstname', 'LIKE', "%{$search}%")
                    ->orWhere('lastname', 'LIKE', "%{$search}%")
                    ->orWhere('phone', 'LIKE', "%{$search}%");
            })
            ->when(isset($filterName) && !empty($filterName), function ($query) use ($filterName) {
                return $query->where('username', 'LIKE', "%{$filterName}%")
                    ->orWhere('firstname', 'LIKE', "%{$filterName}%")
                    ->orWhere('lastname', 'LIKE', "%{$filterName}%");
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == 'all') {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterEmailVerification) && !empty($filterEmailVerification), function ($query) use ($filterEmailVerification) {
                return $query->where('email_verification', $filterEmailVerification);
            })
            ->when(isset($filterSMSVerification) && !empty($filterSMSVerification), function ($query) use ($filterSMSVerification) {
                return $query->where('sms_verification', $filterSMSVerification);
            })
            ->when(isset($filterTwoFaSecurity) && !empty($filterTwoFaSecurity), function ($query) use ($filterTwoFaSecurity) {
                return $query->where('two_fa_verify', $filterTwoFaSecurity);
            })
            ->when(isset($reqVal) && !empty($reqVal), function ($query) use ($reqVal) {
                if ($reqVal == 'activeUser') {
                    return $query->where('status', 1);
                } elseif ($reqVal == 'blocked') {
                    return $query->where('status', 0);
                } elseif ($reqVal == 'emailUnVerify') {
                    return $query->where('email_verification', 0);
                } elseif ($reqVal == 'smsUnVerify') {
                    return $query->where('sms_verification', 0);
                } elseif ($reqVal == 'all') {
                    return $query->where('status', '!=', null);
                }
            });

        return DataTables::of($users)
            ->addColumn('checkbox', function ($item) {
                return ' <input type="checkbox" id="chk-' . $item->id . '"
                                       class="form-check-input row-tic tic-check" name="check" value="' . $item->id . '"
                                       data-id="' . $item->id . '">';
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', $item->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->firstname . ' ' . $item->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . $item->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('email-phone', function ($item) {
                return '<span class="d-block h5 mb-0">' . $item->email . '</span>
                            <span class="d-block fs-5">' . $item->phone . '</span>';
            })
            ->addColumn('balance', function ($item) {
                return currencyPosition($item->balance);
            })
            ->addColumn('country', function ($item) {
                return $item->country ?? 'N/A';
            })
            ->addColumn('email_v', function ($item) {
                if ($item->email_verification == 1) {
                    return '<span class="badge bg-soft-primary text-primary">
                    <span class="legend-indicator bg-primary"></span>' . trans('Verified') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Unverified') . '
                  </span>';
                }
            })
            ->addColumn('sms_v', function ($item) {
                if ($item->sms_verification == 1) {
                    return '<span class="badge bg-soft-info text-info">
                    <span class="legend-indicator bg-info"></span>' . trans('Verified') . '
                  </span>';
                } else {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg--warning"></span>' . trans('Unverified') . '
                  </span>';
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Active') . '
                  </span>';

                } else {
                    return '<span class="badge bg-soft-danger text-danger">
                    <span class="legend-indicator bg-danger"></span>' . trans('Inactive') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $editUrl = route('admin.user.edit', $item->id);
                $viewProfile = route('admin.user.view.profile', $item->id);
                return '<div class="btn-group" role="group">
                      <a href="' . $editUrl . '" class="btn btn-white btn-sm edit_user_btn">
                        <i class="bi-pencil-fill me-1"></i> ' . trans("Edit") . '
                      </a>
                    <div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                       <a class="dropdown-item" href="' . $viewProfile . '">
                          <i class="bi-eye-fill dropdown-item-icon"></i> ' . trans("View Profile") . '
                        </a>
                          <a class="dropdown-item" href="' . route('admin.send.email', $item->id) . '"> <i
                                class="bi-envelope dropdown-item-icon"></i> ' . trans("Send Mail") . ' </a>
                          <a class="dropdown-item loginAccount" href="javascript:void(0)"
                           data-route="' . route('admin.login.as.user', $item->id) . '"
                           data-bs-toggle="modal" data-bs-target="#loginAsUserModal">
                            <i class="bi bi-box-arrow-in-right dropdown-item-icon"></i>
                           ' . trans("Login As User") . '
                        </a>
                         <a class="dropdown-item addBalance" href="javascript:void(0)"
                           data-route="' . route('admin.user.update.balance', $item->id) . '"
                           data-balance="' . currencyPosition($item->balance) . '"
                           data-bs-toggle="modal" data-bs-target="#addBalanceModal">
                            <i class="bi bi-cash-coin dropdown-item-icon"></i>
                            ' . trans("Manage Balance") . '
                        </a>
                      </div>
                    </div>
                  </div>';
            })->rawColumns(['action', 'checkbox', 'name', 'email_v', 'sms_v', 'balance', 'email-phone', 'status'])
            ->make(true);
    }


    public function deleteMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select User.');
            return response()->json(['error' => 1]);
        } else {
            User::whereIn('id', $request->strIds)->get()->map(function ($user) {
                UserAllRecordDeleteJob::dispatch($user);
                $user->forceDelete();
            });
            session()->flash('success', 'User has been deleted successfully');
            return response()->json(['success' => 1]);
        }
    }

    public function userEdit($id)
    {
        $data['languages'] = Language::all();
        $data['basicControl'] = basicControl();
        $data['allCountry'] = config('country');
        $data['userLoginInfo'] = UserLogin::where('user_id', $id)->orderBy('id', 'desc')->limit(5)->get();

        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.edit_user', $data);
    }

    public function userUpdate(Request $request, $id)
    {
        $languages = Language::all()->map(function ($item) {
            return $item->id;
        });

        $request->validate([
            'firstName' => 'required|string|min:2|max:100',
            'lastName' => 'required|string|min:2|max:100',
            'phone' => 'required|unique:users,phone,' . $id,
            'country' => 'required|string|min:2|max:100',
            'city' => 'required|string|min:2|max:100',
            'state' => 'required|string|min:2|max:100',
            'addressOne' => 'required|string|min:2|max:100',
            'addressTwo' => 'nullable|string|min:2',
            'zipCode' => 'required|string|min:2|max:100',
            'status' => 'nullable|integer|in:0,1',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif',
            'language_id' => Rule::in($languages),
        ]);


        $user = User::where('id', $id)->firstOr(function () {
            throw new \Exception('User not found!');
        });
        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.profileImage.path'), null, null, 'webp', 70, $user->image, $user->image_driver);
                if ($image) {
                    $profileImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $user->update([
                'firstname' => $request->firstName,
                'lastname' => $request->lastName,
                'phone' => $request->phone,
                'language_id' => $request->language_id,
                'address_one' => $request->addressOne,
                'address_two' => $request->addressTwo,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zipCode,
                'country' => $request->country,
                'image' => $profileImage ?? $user->image,
                'image_driver' => $driver ?? $user->image_driver,
                'status' => $request->status
            ]);

            return back()->with('success', 'Basic Information Updated Successfully.');
        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }


    public function passwordUpdate(Request $request, $id)
    {
        $request->validate([
            'newPassword' => 'required|min:5|same:confirmNewPassword',
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'password' => bcrypt($request->newPassword)
            ]);

            return back()->with('success', 'Password Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function EmailUpdate(Request $request, $id)
    {
        $request->validate([
            'new_email' => 'required|email:rfc,dns|unique:users,email,' . $id
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'email' => $request->new_email,
            ]);

            return back()->with('success', 'Email Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }

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


        $request->validate([
            'username' => 'required|unique:users,username,' . $id
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'username' => $request->username,
            ]);

            return back()->with('success', 'Username Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }

    public function updateBalanceUpdate(Request $request, $id)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1'
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });
            $basic = basicControl();

            if ($request->balance_operation == 1) {

                $user->balance += $request->amount;
                $user->save();

                $fund = new Deposit();
                $fund->user_id = $user->id;
                $fund->percentage_charge = 0;
                $fund->fixed_charge = 0;
                $fund->charge = 0;
                $fund->amount = $request->amount;
                $fund->status = 1;
                $fund->save();

                $transaction = new Transaction();
                $transaction->user_id = $user->id;
                $transaction->amount_in_base = $request->amount;
                $transaction->trx_type = '+';
                $transaction->remarks = 'Add Balance to wallet';
                $transaction->trx_id = $fund->trx_id;
                $fund->transactional()->save($transaction);

                $msg = [
                    'amount' => currencyPosition($fund->amount),
                    'main_balance' => currencyPosition($user->balance),
                    'transaction' => $transaction->trx_id
                ];

                $action = [
                    "link" => '#',
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $firebaseAction = '#';
                $this->userFirebasePushNotification($user, 'ADD_BALANCE', $msg, $firebaseAction);
                $this->userPushNotification($user, 'ADD_BALANCE', $msg, $action);
                $this->sendMailSms($user, 'ADD_BALANCE', $msg);

                return redirect()->route('admin.user.transaction', $user->id)->with('success', 'Balance Updated Successfully.');

            } else {

                if ($request->amount > $user->balance) {
                    return back()->with('error', 'Insufficient Balance to deducted.');
                }
                $user->balance -= $request->amount;
                $user->save();

                $transaction = new Transaction();
                $transaction->user_id = $user->id;
                $transaction->amount_in_base = $request->amount;
                $transaction->trx_type = '-';
                $transaction->trx_id = Str::random(12);
                $transaction->remarks = 'Deduction Balance from wallet';
                $transaction->save();

                $msg = [
                    'amount' => currencyPosition($request->amount),
                    'main_balance' => currencyPosition($user->balance),
                    'transaction' => $transaction->trx_id
                ];
                $action = [
                    "link" => route('user.transaction'),
                    "icon" => "fa fa-money-bill-alt text-white"
                ];
                $firebaseAction = route('user.transaction');
                $this->userFirebasePushNotification($user, 'DEDUCTED_BALANCE', $msg, $firebaseAction);
                $this->userPushNotification($user, 'DEDUCTED_BALANCE', $msg, $action);
                $this->sendMailSms($user, 'DEDUCTED_BALANCE', $msg);

                return redirect()->route('admin.user.transaction', $user->id)->with('success', 'Balance Updated Successfully.');

            }

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }

    }


    public function preferencesUpdate(Request $request, $id)
    {
        $languages = Language::all()->map(function ($item) {
            return $item->id;
        });

        $request->validate([
            'language_id' => Rule::in($languages),
            'time_zone' => 'required|string|min:1|max:100',
            'email_verification' => 'nullable|integer|in:0,1',
            'sms_verification' => 'nullable|integer|in:0,1',
        ]);

        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            $user->update([
                'language_id' => $request->language_id,
                'time_zone' => $request->time_zone,
                'email_verification' => $request->email_verification,
                'sms_verification' => $request->sms_verification,
            ]);

            return back()->with('success', 'Preferences Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }


    }

    public function userTwoFaUpdate(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });
            $user->update([
                'two_fa_verify' => ($request->two_fa_security == 1) ? 0 : 1
            ]);

            return back()->with('success', 'Two Fa Security Updated Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userDelete(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('User not found!');
            });

            UserAllRecordDeleteJob::dispatch($user);
            $user->forceDelete();
            return redirect()->route('admin.users')->with('success', 'User Account Deleted Successfully.');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userAdd()
    {
        $data['allCountry'] = config('country');
        return view('admin.user_management.add_user', $data);
    }

    public function userStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstName' => 'required|string|min:2|max:255',
            'lastName' => 'required|string|min:2|max:255',
            'username' => 'required|string|unique:users,username|min:2|max:255',
            'password' => 'required|min:2|max:255',
            'email' => 'required|email:rfc,dns|unique:users,email|min:2|max:255',
            'phone' => ['required', 'string', 'unique:users,phone'],
            'phone_code' => 'required|max:15',
            'country_code' => 'nullable|string|max:80',
            'country' => 'required|string|max:80',
            'city' => 'required|string|min:2|max:255',
            'state' => 'nullable|string|min:2|max:255',
            'zipCode' => 'nullable|string|min:2|max:20',
            'addressOne' => 'required|string|min:2',
            'addressTwo' => 'nullable|string|min:2',
            'status' => 'nullable|integer|in:0,1',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif',
        ]);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.profileImage.path'), null, null, 'webp', 60);
                if ($image) {
                    $profileImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        try {
            $response = User::create([
                'firstname' => $request->firstName,
                'lastname' => $request->lastName,
                'username' => $request->username,
                'password' => Hash::make($request->password),
                'email' => $request->email,
                'phone' => $request->phone,
                'phone_code' => $request->phone_code,
                'country' => $request->country,
                'country_code' => $request->country_code,
                'language_id' => $request->language_id,
                'address_one' => $request->addressOne,
                'address_two' => $request->addressTwo,
                'city' => $request->city,
                'state' => $request->state,
                'zip_code' => $request->zipCode,
                'image' => $profileImage ?? null,
                'image_driver' => $driver ?? 'local',
                'status' => $request->status
            ]);

            if (!$response) {
                throw new Exception('Something went wrong, Please try again.');
            }

            return redirect()->route('admin.user.create.success.message', $response->id)->with('success', 'User created successfully');

        } catch (\Exception $exp) {
            return back()->with('error', $exp->getMessage());
        }
    }

    public function userCreateSuccessMessage($id)
    {
        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.components.user_add_success_message', $data);
    }

    public function userViewProfile($id)
    {
        $data['user'] = User::findOrFail($id);
        $data['basic'] = basicControl();
        $data['transactions'] = Transaction::with('user')->where('user_id', $id)->orderBy('id', 'DESC')
            ->limit(5)->get();

        $data['paymentLog'] = Deposit::with('user', 'gateway')->where('user_id', $id)
            ->where('status', '!=', 0)
            ->orderBy('id', 'DESC')
            ->limit(5)
            ->get();

        $data['withDraws'] = Payout::with('user')->where('user_id', $id)
            ->where('status', '!=', 0)
            ->orderBy('id', 'DESC')
            ->limit(5)->get();

        return view('admin.user_management.user_view_profile', $data);
    }

    public function transaction($id)
    {
        $user = User::findOrFail($id);
        return view('admin.user_management.transactions', compact('user'));
    }

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

        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;

        $filterTransactionId = $request->filterTransactionID;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = Transaction::with('user')
            ->has('user')
            ->where('user_id', $id)
            ->when(!empty($search), function ($query) use ($search) {
                $query->where(function ($innerQuery) use ($search) {
                    $innerQuery->where('trx_id', 'LIKE', "%{$search}%")
                        ->orWhere('remarks', 'LIKE', "%{$search}%");
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->orderBy('id', 'DESC')
            ->get();


        return DataTables::of($transaction)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('base_amount', function ($item) {
                $statusClass = $item->trx_type == '+' ? 'text-success' : 'text-danger';
                return "<h6 class='mb-0 $statusClass '>" . $item->trx_type . ' ' . currencyPosition($item->amount_in_base) . "</h6>";

            })
            ->addColumn('remarks', function ($item) {
                return $item->remarks;
            })
            ->addColumn('date-time', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->rawColumns(['amount', 'charge', 'no', 'trx', 'base_amount', 'remarks', 'date-time'])
            ->make(true);
    }


    public function payment($id)
    {
        $data['user'] = User::findOrFail($id);
        $data['methods'] = Gateway::where('status', 1)->orderBy('sort_by', 'asc')->get();
        return view('admin.user_management.payment_log', $data);
    }

    public function userPaymentSearch(Request $request, $id)
    {
        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $filterMethod = $request->filterMethod;
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $deposit = Deposit::query()->with(['user:id,username,firstname,lastname,image,image_driver', 'gateway:id,name,image,driver'])
            ->whereHas('user')
            ->whereHas('gateway')
            ->orderBy('id', 'desc')
            ->where('user_id', $id)
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('transaction', 'LIKE', "%$search%")
                        ->orWhereHas('user', function ($q) use ($search) {
                            $q->where('firstname', 'LIKE', "%$search%")
                                ->orWhere('lastname', 'LIKE', "%{$search}%")
                                ->orWhere('username', 'LIKE', "%{$search}%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(isset($filterMethod), function ($query) use ($filterMethod) {
                return $query->whereHas('gateway', function ($subQuery) use ($filterMethod) {
                    if ($filterMethod == "all") {
                        $subQuery->where('id', '!=', null);
                    } else {
                        $subQuery->where('id', $filterMethod);
                    }
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($deposit)
            ->addColumn('no', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('name', function ($item) {
                $url = route('admin.user.view.profile', optional($item->user)->id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('method', function ($item) {
                return '<a class="d-flex align-items-center me-2" href="javascript:void(0)">
                                <div class="flex-shrink-0">
                                  ' . $item->picture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->gateway)->name . '</h5>
                                </div>
                              </a>';


            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . fractionNumber(getAmount($item->amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . fractionNumber(getAmount($item->percentage_charge) + getAmount($item->fixed_charge)) . ' ' . $item->payment_method_currency . "</span>";
            })
            ->addColumn('payable', function ($item) {
                return "<h6 class='mb-0'>" . fractionNumber(getAmount($item->payable_amount)) . ' ' . $item->payment_method_currency . "</h6>";
            })
            ->addColumn('base_amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('action', function ($item) {
                $details = null;
                if ($item->information) {
                    $details = [];
                    foreach ($item->information as $k => $v) {
                        if ($v->type == "file") {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => getFile(config('filesystems.default'), $v->field_value),
                            ];
                        } else {
                            $details[kebab2Title($k)] = [
                                'type' => $v->type,
                                'field_name' => $v->field_name,
                                'field_value' => @$v->field_value ?? $v->field_name
                            ];
                        }
                    }
                }

                if (optional($item->gateway)->id > 999) {
                    $icon = $item->status == 2 ? 'pencil' : 'eye';
                    return "<button type='button' class='btn btn-white btn-sm edit_btn' data-bs-target='#accountInvoiceReceiptModal'
                data-detailsinfo='" . json_encode($details) . "'
                data-id='$item->id'
                data-feedback='$item->note'
                 data-amount='" . getAmount($item->payable_amount) . ' ' . $item->payment_method_currency . "'
                data-method='" . optional($item->gateway)->name . "'
                data-gatewayimage='" . getFile(optional($item->gateway)->driver, optional($item->gateway)->image) . "'
                data-datepaid='" . dateTime($item->created_at) . "'
                data-status='$item->status'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payment.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
                } else {
                    return '-';
                }
            })
            ->rawColumns(['name', 'method', 'amount', 'charge', 'payable', 'base_amount', 'status', 'action'])->make(true);

    }

    public function payout($id)
    {
        $data['user'] = User::findOrFail($id);
        return view('admin.user_management.payout_log', $data);
    }

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

        $filterTransactionId = $request->filterTransactionID;
        $filterStatus = $request->filterStatus;
        $basicControl = basicControl();
        $search = $request->search['value'] ?? null;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $payout = Payout::with('user')
            ->has('user')
            ->where('user_id', $id)
            ->where('status', '!=', 0)
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('trx_id', 'LIKE', "%$search%")
                        ->orWhereHas('method', function ($q) use ($search) {
                            $q->where('name', 'LIKE', "%$search%");
                        });
                });
            })
            ->when(!empty($filterTransactionId), function ($query) use ($filterTransactionId) {
                return $query->where('trx_id', $filterTransactionId);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            });


        return DataTables::of($payout)
            ->addColumn('No', function ($item) {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('trx', function ($item) {
                return $item->trx_id;
            })
            ->addColumn('amount', function ($item) {
                $statusClass = $item->getStatusClass();
                return "<h6 class='mb-0 $statusClass '>" . currencyPosition($item->amount, $item->payout_currency_code) . "</h6>";

            })
            ->addColumn('charge', function ($item) {
                return "<span class='text-danger'>" . currencyPosition($item->charge, $item->payout_currency_code) . "</span>";
            })
            ->addColumn('net-amount', function ($item) {
                return "<h6>" . currencyPosition($item->amount_in_base_currency) . "</h6>";
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 1) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Successful') . '</span>';
                } else if ($item->status == 3) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Cancel') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at, 'd M Y h:i A');
            })
            ->addColumn('action', function ($item) use ($basicControl) {

                $details = null;
                if ($item->information) {
                    $information = json_decode($item->information, true);
                    if (is_array($information)) {
                        $details = [];
                        foreach ($information as $k => $v) {
                            if ($v['type'] == "file") {
                                $details[kebab2Title($k)] = [
                                    'type' => $v['type'],
                                    'field_name' => $v['field_name'],
                                    'field_value' => getFile(config('filesystems.default'), @$v['field_value'] ?? $v['field_name']),
                                ];
                            } else {
                                $details[kebab2Title($k)] = [
                                    'type' => $v['type'],
                                    'field_name' => $v['field_name'],
                                    'field_value' => @$v['field_value'] ?? $v['field_name']
                                ];
                            }
                        }
                    }
                }

                $icon = $item->status == 1 ? 'pencil' : 'eye';

                $statusColor = '';
                $statusText = '';
                if ($item->status == 0) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 1) {
                    $statusColor = 'badge bg-soft-warning text-warning';
                    $statusText = 'Pending';
                } else if ($item->status == 2) {
                    $statusColor = 'badge bg-soft-success text-success';
                    $statusText = 'Success';
                } else if ($item->status == 3) {
                    $statusColor = 'badge bg-soft-danger text-danger';
                    $statusText = 'Cancel';
                }

                return "<button type='button' class='btn btn-white btn-sm edit_btn'
                data-id='$item->id'
                data-info='" . json_encode($details) . "'
                data-sendername='" . $item->user->firstname . ' ' . $item->user->lastname . "'
                data-transactionid='$item->trx_id'
                data-feedback='$item->feedback'
                data-amount=' " . currencyPosition($item->amount) . "'
                data-datepaid='" . dateTime($item->created_at, 'd M Y') . "'
                data-status='$item->status'

                 data-status_color='$statusColor'
                data-status_text='$statusText'
                data-username='" . optional($item->user)->username . "'
                data-action='" . route('admin.payout.action', $item->id) . "'
                data-bs-toggle='modal'
                data-bs-target='#accountInvoiceReceiptModal'>  <i class='bi-$icon fill me-1'></i> </button>";
            })
            ->rawColumns(['amount', 'charge', 'net-amount', 'status', 'action'])
            ->make(true);
    }

    public function userKyc($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.user_kyc', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function KycSearch(Request $request, $id)
    {
        $filterVerificationType = $request->filterVerificationType;
        $filterStatus = $request->filterStatus;

        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $transaction = UserKyc::with('user')
            ->where('user_id', $id)
            ->orderBy('id', 'DESC')
            ->when(!empty($filterVerificationType), function ($query) use ($filterVerificationType) {
                return $query->where('kyc_type', $filterVerificationType);
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus == "all") {
                    return $query->where('status', '!=', null);
                }
                return $query->where('status', $filterStatus);
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->get();

        return DataTables::of($transaction)
            ->addColumn('no', function () {
                static $counter = 0;
                $counter++;
                return $counter;
            })
            ->addColumn('verification type', function ($item) {
                return $item->kyc_type;

            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">' . trans('Pending') . '</span>';
                } else if ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">' . trans('Verified') . '</span>';
                } else if ($item->status == 2) {
                    return '<span class="badge bg-soft-danger text-danger">' . trans('Rejected') . '</span>';
                }
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);

            })
            ->addColumn('action', function ($item) {
                $url = route('admin.kyc.view', $item->id);
                return '<a href="' . $url . '" class="btn btn-white btn-sm">
                    <i class="bi-eye-fill me-1"></i>
                  </a>';
            })
            ->rawColumns(['name', 'status', 'action'])
            ->make(true);
    }


    public function loginAsUser($id)
    {
        Auth::guard('web')->loginUsingId($id);
        return redirect()->route('user.dashboard');
    }


    public function blockProfile(Request $request, $id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('No User found.');
            });

            $user->status = $user->status == 1 ? 0 : 1;
            $user->save();


            $message = $user->status == 1 ? 'Unblock Profile Successfully' : 'Block Profile Successfully';

            return back()->with('success', $message);
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function mailAllUser()
    {
        return view('admin.user_management.mail_all_user');
    }

    public function sendEmail($id)
    {
        try {
            $user = User::where('id', $id)->firstOr(function () {
                throw new \Exception('No User found.');
            });
            return view('admin.user_management.send_mail_form', compact('user'));
        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function sendMailUser(Request $request, $id = null)
    {

        $request->validate([
            'subject' => 'required|min:5',
            'description' => 'required|min:10',
        ]);

        try {

            $user = User::where('id', $id)->first();

            $subject = $request->subject;
            $template = $request->description;

            if (isset($user)) {
                Mail::to($user)->send(new SendMail(basicControl()->sender_email, $subject, $template));
            } else {
                $users = User::where('email_verification', 1)->where('status', 1)->get();
                foreach ($users as $user) {
                    Mail::to($user)->queue(new SendMail(basicControl()->sender_email, $subject, $template));
                }
            }

            return back()->with('success', 'Email Sent Successfully');

        } catch (\Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function countData()
    {
        $userData = User::selectRaw(
            'COUNT(*) as totalUsers,
             SUM(status = 1) as totalActiveUsers,
             SUM(status = 0) as totalBannedUsers,
             SUM(email_verification = 0) as totalEmailUnverified,
             SUM(sms_verification = 0) as totalSmsUnverified'
        )->first();

        $data['total_users'] = $userData->totalUsers ?? 0;
        $data['active_users'] = $userData->totalActiveUsers ?? 0;
        $data['banned_users'] = $userData->totalBannedUsers ?? 0;
        $data['email_unverified'] = $userData->totalEmailUnverified ?? 0;
        $data['sms_unverified'] = $userData->totalSmsUnverified ?? 0;

        return $data;
    }

    public function userActivity()
    {
        return view('admin.user_management.user_activity');
    }

    public function userActivitySearch(Request $request)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->filterName;
        $filterIp = $request->filterIp;
        $filterOther = $request->filterOther;

        $activities = UserTracking::query()->has('user')->with('user')->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('ip', 'LIKE', "%{$search}%")
                    ->orWhere('country_name', 'LIKE', "%{$search}%")
                    ->orWhere('region_name', 'LIKE', "%{$search}%")
                    ->orWhere('city_name', 'LIKE', "%{$search}%")
                    ->orWhere('latitude', 'LIKE', "%{$search}%")
                    ->orWhere('longitude', 'LIKE', "%{$search}%")
                    ->orWhere('timezone', 'LIKE', "%{$search}%")
                    ->orWhere('browser', 'LIKE', "%{$search}%")
                    ->orWhere('os', 'LIKE', "%{$search}%")
                    ->orWhere('device', 'LIKE', "%{$search}%")
                    ->orWhere('remark', 'LIKE', "%{$search}%")
                    ->orWhereHas('user', function ($qq) use ($search) {
                        $qq->where('firstname', 'LIKE', "%{$search}%")
                            ->orWhere('lastname', 'LIKE', "%{$search}%")
                            ->orWhere('username', 'LIKE', "%{$search}%");
                    });
            })
            ->when(isset($filterName) && !empty($filterName), function ($query) use ($filterName) {
                return $query->whereHas('user', function ($qq) use ($filterName) {
                    $qq->where('username', 'LIKE', "%{$filterName}%")
                        ->orWhere('firstname', 'LIKE', "%{$filterName}%")
                        ->orWhere('lastname', 'LIKE', "%{$filterName}%");
                });
            })
            ->when(isset($filterIp) && !empty($filterIp), function ($query) use ($filterIp) {
                return $query->where('ip', $filterIp);
            })
            ->when(isset($filterOther) && !empty($filterOther), function ($query) use ($filterOther) {
                return $query->where('country_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('region_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('city_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('latitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('longitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('timezone', 'LIKE', "%{$filterOther}%")
                    ->orWhere('browser', 'LIKE', "%{$filterOther}%")
                    ->orWhere('os', 'LIKE', "%{$filterOther}%")
                    ->orWhere('device', 'LIKE', "%{$filterOther}%")
                    ->orWhere('remark', 'LIKE', "%{$filterOther}%");
            });

        return DataTables::of($activities)
            ->addColumn('user', function ($item) {
                $url = route('admin.user.view.profile', $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . $item->user->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . $item->user->firstname . ' ' . $item->user->lastname . '</h5>
                                  <span class="fs-6 text-body">' . $item->user->username . '</span>
                                </div>
                              </a>';

            })
            ->addColumn('ip', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->ip . '</span>';
            })
            ->addColumn('city', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->city_name . ' (' . $item->region_name . ') </span>
                  <span class="d-block fs-5">' . $item->country_name . ' (' . $item->country_code . ') </span > ';
            })
            ->addColumn('lat_lon', function ($item) {
                return $item->latitude . ' - ' . $item->longitude;
            })
            ->addColumn('timezone', function ($item) {
                return $item->timezone;
            })
            ->addColumn('browser', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->browser . ' (' . $item->os . ') </span>
                  <span class="d-block fs-5">' . $item->device . ' </span > ';
            })
            ->addColumn('remark', function ($item) {
                return $item->remark;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->rawColumns(['user', 'ip', 'city', 'lat_lon', 'timezone', 'browser', 'remark', 'date'])
            ->make(true);
    }

    public function topUpOrder($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.topUp-order', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function topUpOrderSearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $status = $request->type ?? '-1';
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::payment()->type('topup')
            ->with(['gateway:id,name', 'orderDetails', 'orderDetails.detailable.topUp:id,name'])
            ->where('user_id', $id)->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                });
            });

        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('top_up', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 0) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderTopUp.complete');
                $cancel = route('admin.orderTopUp.cancel');
                $view = route('admin.orderTopUp.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 0) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'top_up', 'total_amount', 'payment_method', 'status', 'action'])
            ->make(true);
    }

    public function cardOrder($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.card-order', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function cardOrderSearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $status = $request->type ?? '-1';
        $filterStatus = $request->filterStatus;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $orders = Order::payment()->type('card')
            ->with(['gateway:id,name', 'orderDetails', 'orderDetails.detailable.card:id,name'])
            ->where('user_id', $id)->orderBy('id', 'desc')
            ->when($status != '-1', function ($query) use ($status) {
                return $query->where('status', $status);
            })
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('utr', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterStatus), function ($query) use ($filterStatus) {
                if ($filterStatus != "all") {
                    return $query->where('status', $filterStatus);
                }
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('utr', 'LIKE', "%$search%")
                        ->orWhere('amount', 'LIKE', "%$search%");
                });
            });
        return DataTables::of($orders)
            ->addColumn('order', function ($item) {
                return $item->utr;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->addColumn('card', function ($item) {
                $div = "";
                $extra = 0;
                foreach ($item->orderDetails as $key => $detail) {
                    if ($key < 3) {
                        $div .= '<span class="avatar" data-bs-toggle="tooltip" data-bs-placement="top" aria-label="Ella Lauda" data-bs-original-title="Ella Lauda">
              <img class="avatar-img" src="' . $detail->image_path . '" alt="Image Description">
            </span>';
                    } else {
                        $extra++;
                    }
                }

                if ($extra) {
                    $div .= '<span class="avatar avatar-light avatar-circle" data-bs-toggle="tooltip" data-bs-placement="top" data-bs-original-title="Sam Kart, Amanda Harvey and 1 more">
          <span class="avatar-initials">+' . $extra . '</span>
        </span>';
                }

                // Convert order details to JSON format
                $orderDetailsJson = htmlspecialchars(json_encode($item->orderDetails), ENT_QUOTES, 'UTF-8');

                return '<div class="avatar-group avatar-group-xs avatar-circle">
                ' . $div . '
                 <span class="avatar avatar-light avatar-circle seeAll" data-bs-toggle="modal" data-bs-target="#sellAll"
                  data-detail="' . $orderDetailsJson . '">
                  <a href="javascript:void(0)"><span class="avatar-initials"><i class="fa-light fa-arrow-right"></i></span></a>
                </span>
              </div>';
            })
            ->addColumn('total_amount', function ($item) {
                return '<h6>' . currencyPosition($item->amount) . '</h6>';
            })
            ->addColumn('payment_method', function ($item) {
                if ($item->payment_method_id == '-1') {
                    return 'Wallet';
                } else {
                    return $item->gateway?->name;
                }
            })
            ->addColumn('status', function ($item) {
                if ($item->status == 3) {
                    return '<span class="badge bg-soft-warning text-warning">
                    <span class="legend-indicator bg-warning"></span>' . trans('Pending (stock-short)') . '
                  </span>';

                } elseif ($item->status == 1) {
                    return '<span class="badge bg-soft-success text-success">
                    <span class="legend-indicator bg-success"></span>' . trans('Complete') . '
                  </span>';
                } elseif ($item->status == 2) {
                    return '<span class="badge bg-soft-secondary text-secondary">
                    <span class="legend-indicator bg-secondary"></span>' . trans('Refund') . '
                  </span>';
                }
            })
            ->addColumn('action', function ($item) {
                $complete = route('admin.orderCard.complete');
                $cancel = route('admin.orderCard.cancel');
                $view = route('admin.orderCard.view') . '?orderId=' . $item->utr;
                $html = '<div class="btn-group" role="group">
                      <a href="' . $view . '" class="btn btn-white btn-sm">
                        <i class="fal fa-eye me-1"></i> ' . trans("View") . '
                      </a>';

                if ($item->status == 3) {
                    $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="complete" data-id="' . $item->utr . '" data-route="' . $complete . '">
                          <i class="fal fa-check dropdown-item-icon"></i> ' . trans("Complete Order") . '
                       </a>

                       <a class="dropdown-item actionBtn" href="javascript:void(0)" data-bs-target="#orderStep"
                           data-bs-toggle="modal" data-type="cancel" data-id="' . $item->utr . '" data-route="' . $cancel . '">
                          <i class="fal fa-times dropdown-item-icon"></i> ' . trans("Cancel Order") . '
                       </a>
                      </div>
                    </div>';
                }

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['order', 'date', 'card', 'total_amount', 'payment_method', 'status', 'action'])
            ->make(true);
    }

    public function specificActivity($id)
    {
        try {
            $data['user'] = User::where('id', $id)->firstOr(function () {
                throw new Exception('No User found.');
            });
            return view('admin.user_management.specific_activity', $data);
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function specificActivitySearch(Request $request, $id)
    {
        $search = $request->search['value'] ?? null;
        $filterIp = $request->filterIp;
        $filterOther = $request->filterOther;

        $activities = UserTracking::query()->where('user_id', $id)->orderBy('id', 'DESC')
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where('ip', 'LIKE', "%{$search}%")
                    ->orWhere('country_name', 'LIKE', "%{$search}%")
                    ->orWhere('region_name', 'LIKE', "%{$search}%")
                    ->orWhere('city_name', 'LIKE', "%{$search}%")
                    ->orWhere('latitude', 'LIKE', "%{$search}%")
                    ->orWhere('longitude', 'LIKE', "%{$search}%")
                    ->orWhere('timezone', 'LIKE', "%{$search}%")
                    ->orWhere('browser', 'LIKE', "%{$search}%")
                    ->orWhere('os', 'LIKE', "%{$search}%")
                    ->orWhere('device', 'LIKE', "%{$search}%")
                    ->orWhere('remark', 'LIKE', "%{$search}%");
            })
            ->when(isset($filterIp) && !empty($filterIp), function ($query) use ($filterIp) {
                return $query->where('ip', $filterIp);
            })
            ->when(isset($filterOther) && !empty($filterOther), function ($query) use ($filterOther) {
                return $query->where('country_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('region_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('city_name', 'LIKE', "%{$filterOther}%")
                    ->orWhere('latitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('longitude', 'LIKE', "%{$filterOther}%")
                    ->orWhere('timezone', 'LIKE', "%{$filterOther}%")
                    ->orWhere('browser', 'LIKE', "%{$filterOther}%")
                    ->orWhere('os', 'LIKE', "%{$filterOther}%")
                    ->orWhere('device', 'LIKE', "%{$filterOther}%")
                    ->orWhere('remark', 'LIKE', "%{$filterOther}%");
            });

        return DataTables::of($activities)
            ->addColumn('ip', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->ip . '</span>';
            })
            ->addColumn('city', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->city_name . ' (' . $item->region_name . ') </span>
                  <span class="d-block fs-5">' . $item->country_name . ' (' . $item->country_code . ') </span > ';
            })
            ->addColumn('browser', function ($item) {
                return ' <span class="d-block h5 mb-0">' . $item->browser . ' (' . $item->os . ') </span>
                  <span class="d-block fs-5">' . $item->device . ' </span > ';
            })
            ->addColumn('remark', function ($item) {
                return $item->remark;
            })
            ->addColumn('date', function ($item) {
                return dateTime($item->created_at);
            })
            ->rawColumns(['ip', 'city', 'browser', 'remark', 'date'])
            ->make(true);
    }
}
PK     :S\Yʎ
  
  /  Http/Controllers/AAdmin/SmsConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ManualSmsConfig;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;


class SmsConfigController extends Controller
{
    public function index()
    {
        $data['smsControlMethod'] = config('SMSConfig.SMS');
        $data['smsMethodDefault'] = config('SMSConfig.default');
        return view('admin.sms_controls.index', $data);
    }

    public function smsConfigEdit($method)
    {
        try {
            $basicControl = basicControl();
            $smsControlMethod = config('SMSConfig.SMS');
            $smsMethodParameters = $smsControlMethod[$method] ?? null;

            if ($method == "manual") {
                $manualSMSMethod = ManualSmsConfig::first();
                return view('admin.sms_controls.manual_sms_config', compact("method", "manualSMSMethod", "basicControl"));
            }

            return view('admin.sms_controls.sms_config', compact('smsMethodParameters', 'method', 'basicControl'));
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function smsConfigUpdate(Request $request, $method)
    {
        $rules = [
            'method_name' => 'required|string|min:3|max:100',
            'sms_notification' => 'nullable|integer|min:0|in:0,1',
            'sms_verification' => 'nullable|integer|min:0|in:0,1',
        ];

        $smsControlMethod = config('SMSConfig.SMS');
        $smsMethodParameters = $smsControlMethod[$method] ?? null;

        foreach ($request->except('_token', '_method', 'method_name', 'sms_notification', 'sms_verification') as $key => $value) {
            if (array_key_exists($key, $smsMethodParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }

        $request->validate($rules);

        try {
            $env = [
                'TWILIO_ACCOUNT_SID' => $request->twilio_account_sid ?? $smsControlMethod['twilio']['twilio_account_sid']['value'],
                'TWILIO_AUTH_TOKEN' => $request->twilio_auth_token ?? $smsControlMethod['twilio']['twilio_auth_token']['value'],
                'TWILIO_PHONE_NUMBER' => $request->twilio_phone_number ?? $smsControlMethod['twilio']['twilio_phone_number']['value'],
                'INFOBIP_API_KEY' => $request->infobip_api_key ?? $smsControlMethod['infobip']['infobip_api_key']['value'],
                'INFOBIP_URL_BASE_PATH' => $request->infobip_url_base_path ?? $smsControlMethod['infobip']['infobip_url_base_path']['value'],
                'PLIVO_ID' => $request->plivo_id ?? $smsControlMethod['plivo']['plivo_id']['value'],
                'PLIVO_AUTH_ID' => $request->plivo_auth_id ?? $smsControlMethod['plivo']['plivo_auth_id']['value'],
                'PLIVO_AUTH_TOKEN' => $request->plivo_auth_token ?? $smsControlMethod['plivo']['plivo_auth_token']['value'],
                'VONAGE_FROM' => "VONAGE_FROM",
                'VONAGE_API_KEY' => $request->vonage_api_key ?? $smsControlMethod['vonage']['vonage_api_key']['value'],
                'VONAGE_API_SECRET' => $request->vonage_api_secret ?? $smsControlMethod['vonage']['vonage_api_secret']['value'],
            ];

            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                'sms_notification' => $request->sms_notification,
                'sms_verification' => $request->sms_verification

            ]);

            return back()->with('success', 'SMS Configuration has been updated successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

    }

    public function manualSmsMethodUpdate(Request $request, $method)
    {

        $this->validate($request, [
            'actionMethod' => 'required|in:GET,POST',
            'actionUrl' => 'required|url',
            'headerDataKeys.*' => 'nullable|string|min:2|required_with:headerValue.*',
            'headerDataValues.*' => 'nullable|string|min:2|required_with:headerKey.*',
            'paramKeys.*' => 'nullable|string|min:2|required_with:paramValue.*',
            'paramValues.*' => 'nullable|string|min:2|required_with:paramKey.*',
            'formDataKeys.*' => 'nullable|string|min:2|required_with:formDataValue.*',
            'formDataValues.*' => 'nullable|string|min:2|required_with:formDataKey.*',
            'sms_notification' => 'nullable|integer|in:0,1',
            'sms_verification' => 'nullable|integer|in:0,1'
        ], [
            'min' => 'This field must be at least :min characters.',
            'string' => 'This field must be :string.',
            'required_with' => 'This field is requird',
        ]);

        $headerData = array_combine($request->headerDataKeys, $request->headerDataValues);
        $paramData = array_combine($request->paramKeys, $request->paramValues);
        $formData = array_combine($request->formDataKeys, $request->formDataValues);

        $headerData = (empty(array_filter($headerData))) ? null : json_encode(array_filter($headerData));
        $paramData = (empty(array_filter($paramData))) ? null : json_encode(array_filter($paramData));
        $formData = (empty(array_filter($formData))) ? null : json_encode(array_filter($formData));


        $smsControl = ManualSmsConfig::firstOrCreate(['id' => 1]);
        $smsControl->action_method = $request->actionMethod;
        $smsControl->action_url = $request->actionUrl;
        $smsControl->form_data = $formData;
        $smsControl->param_data = $paramData;
        $smsControl->header_data = $headerData;
        $smsControl->save();

        $basicControl = basicControl();
        $basicControl->sms_notification = $request->sms_notification;
        $basicControl->sms_verification = $request->sms_verification;
        $basicControl->save();

        return back()->with('success', 'SMS Configuration has been updated successfully.');
    }

    public function smsSetAsDefault($method)
    {
        try {
            $env = [
                'SMS_METHOD' => $method
            ];
            BasicService::setEnv($env);

            return back()->with('success', 'SMS method set as default successfully.');

        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }
}
PK     :S\^r    1  Http/Controllers/AAdmin/EmailConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Mail\sendTestMail;
use App\Models\NotificationTemplate;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Exception;

class EmailConfigController extends Controller
{
    public function emailControls()
    {
        $data['mailMethod'] = config('mailconfig');
        $data['mailMethodDefault'] = config('mail.default');
        return view('admin.email_controls.index', $data);
    }

    public function emailConfigEdit($method)
    {
        try {
            $data['basicControl'] = basicControl();
            $mailMethod = config('mailconfig');
            $mailParameters = $mailMethod[$method] ?? null;
            return view('admin.email_controls.email_config', $data, compact('mailParameters', 'method'));

        } catch (\Exception $exception) {
            return back()->with('alert', $exception->getMessage());
        }
    }

    public function emailConfigUpdate(Request $request, $method)
    {
        $rules = [
            'sender_email' => 'required|email:rfc,dns',
            'email_method' => 'required|string',
            'email_notification' => 'nullable|integer|in:0,1',
            'email_verification' => 'nullable|integer|in:0,1',
        ];

        $mailMethod = config('mailconfig');
        $mailParameters = $mailMethod[$method] ?? null;

        foreach ($request->except('_token', '_method') as $key => $value) {
            if (array_key_exists($key, $mailParameters)) {
                $rules[$key] = 'required|max:191';
            }
        }
        $request->validate($rules);

        try {
            $env = [
                'MAIL_FROM_ADDRESS' => $request->sender_email,
                'MAIL_HOST' => $request->mail_host ?? $mailMethod['SMTP']['mail_host']['value'],
                'MAIL_PORT' => $request->mail_port ?? $mailMethod['SMTP']['mail_port']['value'],
                'MAIL_USERNAME' => $request->mail_username ?? $mailMethod['SMTP']['mail_username']['value'],
                'MAIL_PASSWORD' => isset($request->mail_password) ? '"' . $request->mail_password . '"' : $mailMethod['SMTP']['mail_password']['value'],
                'MAILGUN_DOMAIN' => $request->mailgun_domain ?? $mailMethod['mailgun']['mailgun_domain']['value'],
                'MAILGUN_SECRET' => $request->mailgun_secret ?? $mailMethod['mailgun']['mailgun_secret']['value'],
                'POSTMARK_TOKEN' => $request->postmark_token ?? $mailMethod['postmark']['postmark_token']['value'],
                'AWS_ACCESS_KEY_ID' => $request->aws_secret_access_key ?? $mailMethod['SES']['aws_access_key_id']['value'],
                'AWS_SECRET_ACCESS_KEY' => $request->aws_default_region ?? $mailMethod['SES']['aws_secret_access_key']['value'],
                'AWS_DEFAULT_REGION' => $request->aws_default_region ?? $mailMethod['SES']['aws_default_region']['value'],
                'AWS_SESSION_TOKEN' => $request->aws_session_token ?? $mailMethod['SES']['aws_session_token']['value'],
                'MAILERSEND_API_KEY' => $request->mailersend_api_key ?? $mailMethod['mailersend']['mailersend_api_key']['value'],
                'SENDINBLUE_API_KEY' => $request->sendinblue_api_key ?? $mailMethod['sendinblue']['sendinblue_api_key']['value'],
                'SENDGRID_API_KEY' => $request->sendgrid_api_key ?? $mailMethod['sendgrid']['sendgrid_api_key']['value'],
                'MAILCHIMP_API_KEY' => $request->mailchimp_api_key ?? $mailMethod['mailchimp']['mailchimp_api_key']['value'],
            ];


            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                "email_notification" => $request->email_notification,
                "email_verification" => $request->email_verification,
                "sender_email" => $request->sender_email,
            ]);

            NotificationTemplate::get()->map(function ($item) use ($request){
                $item->email_from = $request->sender_email;
                $item->save();

            });

            return back()->with('success', 'Email Configuration has been updated successfully.');

        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }

    public function emailSetAsDefault(Request $request, $method)
    {
        try {
            $env = [
                'MAIL_MAILER' => $method
            ];
            BasicService::setEnv($env);

            return back()->with('success', 'Mail method set as default successfully.');
        } catch (Exception $exception) {
            return back()->with('error', $exception->getMessage());
        }
    }


    public function testEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email:rfc,dns',
        ]);

        $basic = basicControl();

        if ($basic->email_notification !== 1) {
            return back()->with('warning', 'Your email notification is disabled');
        }

        $email_from = $basic->sender_email;
        Mail::to($request->email)->send(new sendTestMail($email_from, "Test Email", "Your " . $_SERVER['SERVER_NAME'] . " email is working."));

        return back()->with('success', 'Email has been sent successfully.');
    }

}
PK     :S\IZgg  g  6  Http/Controllers/AAdmin/SellPostCategoryController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\SellPost;
use App\Models\Language;
use App\Models\SellPostCategory;
use App\Models\SellPostCategoryDetail;
use App\Models\SellPostChat;
use App\Models\SellPostOffer;
use App\Traits\Notify;
use App\Traits\SellPostTrait;
use App\Traits\Upload;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Yajra\DataTables\Facades\DataTables;

class SellPostCategoryController extends Controller
{
    use Upload, Notify, SellPostTrait;

    public function category()
    {
        $manageCategory = SellPostCategory::with(['details'])->withCount('activePost')->latest()->get();
        return view('admin.sellPostCategory.categoryList', compact('manageCategory'));
    }

    public function categoryCreate()
    {
        $languages = Language::all();
        return view('admin.sellPostCategory.categoryCreate', compact('languages'));
    }

    public function categoryStore(Request $request, $language)
    {

        $purifiedData = $request->all();
        DB::beginTransaction();
        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
                'image' => 'required|mimes:jpg,jpeg,png',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'image.required' => 'Image is required',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $category = new SellPostCategory();

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if ($request->has('status')) {
                $category->status = $request->status;
            }

            if ($request->has('sell_charge')) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->hasFile('image')) {
                try {
                    $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp');
                    $category->image = $imageUp['path'];
                    $category->image_driver = $imageUp['driver'];
                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            $category->save();

            $category->details()->create([
                'language_id' => $language,
                'name' => $purifiedData["name"][$language],
            ]);

            DB::commit();

            return back()->with('success', 'Category Successfully Saved');
        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }
    }

    public function categoryEdit($id)
    {
        $languages = Language::all();
        $categoryDetails = SellPostCategoryDetail::with('sellPostCategory')->where('sell_post_category_id', $id)->get()->groupBy('language_id');
        return view('admin.sellPostCategory.categoryEdit', compact('languages', 'categoryDetails', 'id'));
    }


    public function categoryUpdate(Request $request, $id, $language_id)
    {
        $purifiedData = $request->all();
        DB::beginTransaction();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'name.*' => 'required|max:40',
                'sell_charge' => 'sometimes|required|numeric|min:1',
            ];
            $message = [
                'name.*.required' => 'Name field is required',
                'name.*.max' => 'This field may not be greater than :max characters',
                'sell_charge.required' => 'Sell Charge  is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }

            $input_form = [];
            if ($request->has('field_name')) {
                for ($a = 0; $a < count($request->field_name); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_name[$a]);
                    $arr['field_level'] = $request->field_name[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation[$a];
                    $input_form[$arr['field_name']] = $arr;
                }
            }

            $input_post = [];
            if ($request->has('field_specification')) {
                for ($a = 0; $a < count($request->field_specification); $a++) {
                    $arr = array();
                    $arr['field_name'] = clean($request->field_specification[$a]);
                    $arr['field_level'] = $request->field_specification[$a];
                    $arr['type'] = $request->type[$a];
                    $arr['validation'] = $request->validation_specification[$a];
                    $input_post[$arr['field_name']] = $arr;
                }
            }

            $category = SellPostCategory::findOrFail($id);

            if ($request->hasFile('image')) {
                $imageUp = $this->fileUpload($purifiedData['image'], config('filelocation.sellPostCategory.path'), null, config('filelocation.sellPostCategory.size'), 'webp', null, $category->image, $category->image_driver);
                $category->image = $imageUp['path'];
                $category->image_driver = $imageUp['driver'];
            }

            if (isset($purifiedData['field_name'])) {
                $category->form_field = $input_form;
            }

            if (isset($purifiedData['field_specification'])) {
                $category->post_specification_form = $input_post;
            }

            if (isset($purifiedData['sell_charge'])) {
                $category->sell_charge = $request->sell_charge;
            }


            if ($request->has('status')) {
                $category->status = $request->status;
            }
            $category->save();

            $category->details()->updateOrCreate([
                'language_id' => $language_id
            ],
                [
                    'name' => $purifiedData["name"][$language_id],
                ]
            );
            DB::commit();

            return back()->with('success', 'Category Successfully Updated');

        } catch (\Exception$e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function statusSellMultiple(Request $request)
    {
        if ($request->strIds == null) {
            session()->flash('error', 'You do not select Category.');
            return response()->json(['error' => 1]);
        } else {
            SellPostCategory::whereIn('id', $request->strIds)->get()->map(function ($query) {
                $query->status = $query->status ? 0 : 1;
                $query->save();
            });
            session()->flash('success', 'Status has been active');
            return response()->json(['success' => 1]);
        }
    }

    public function categoryDelete($id)
    {
        $categoryData = SellPostCategory::findOrFail($id);
        if (0 < $categoryData->post->count()) {
            session()->flash('warning', 'This Category has a lot of post');
            return back();
        }

        $this->fileDelete($categoryData->image_driver, $categoryData->image);

        $categoryData->delete();
        return back()->with('success', 'Category has been deleted');
    }

    public function sellList($status = null)
    {
        $data['value'] = $this->getValueByStatus($status);
        abort_if(!isset($data['value']), 404);

        $data['sellPost'] = collect(SellPost::selectRaw('COUNT(id) AS totalPost')
            ->selectRaw('COUNT(CASE WHEN status = 1 THEN id END) AS approvalPost')
            ->selectRaw('(COUNT(CASE WHEN status = 1 THEN id END) / COUNT(id)) * 100 AS approvalPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 0 THEN id END) AS pendingPost')
            ->selectRaw('(COUNT(CASE WHEN status = 0 THEN id END) / COUNT(id)) * 100 AS pendingPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 3 THEN id END) AS holdPost')
            ->selectRaw('(COUNT(CASE WHEN status = 3 THEN id END) / COUNT(id)) * 100 AS holdPostPercentage')
            ->selectRaw('COUNT(CASE WHEN status = 5 THEN id END) AS hardPost')
            ->selectRaw('(COUNT(CASE WHEN status = 5 THEN id END) / COUNT(id)) * 100 AS hardPostPercentage')
            ->get()
            ->toArray())->collapse();

        return view('admin.sellPostList.index', $data);
    }

    public function sellListSearch(Request $request, $status = null)
    {
        $search = $request->search['value'] ?? null;
        $filterName = $request->name;
        $filterUser = $request->user;
        $filterDate = explode('-', $request->filterDate);
        $startDate = $filterDate[0];
        $endDate = isset($filterDate[1]) ? trim($filterDate[1]) : null;

        $posts = SellPost::status($status)->latest()
            ->has('user')
            ->when(isset($filterName), function ($query) use ($filterName) {
                return $query->where('title', 'LIKE', '%' . $filterName . '%');
            })
            ->when(isset($filterUser), function ($query) use ($filterUser) {
                $query->whereHas('user', function ($qq) use ($filterUser) {
                    $qq->where('firstname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('lastname', 'LIKE', '%' . $filterUser . '%')
                        ->orWhere('username', 'LIKE', '%' . $filterUser . '%');
                });
            })
            ->when(!empty($request->filterDate) && $endDate == null, function ($query) use ($startDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $query->whereDate('created_at', $startDate);
            })
            ->when(!empty($request->filterDate) && $endDate != null, function ($query) use ($startDate, $endDate) {
                $startDate = Carbon::createFromFormat('d/m/Y', trim($startDate));
                $endDate = Carbon::createFromFormat('d/m/Y', trim($endDate));
                $query->whereBetween('created_at', [$startDate, $endDate]);
            })
            ->when(!empty($search), function ($query) use ($search) {
                return $query->where(function ($subquery) use ($search) {
                    $subquery->where('title', 'LIKE', '%' . $search . '%')
                        ->orWhereHas('category.details', function ($qq) use ($search) {
                            $qq->where('name', 'LIKE', '%' . $search . '%');
                        });
                });
            });
        return DataTables::of($posts)
            ->addColumn('title', function ($item) {
                $extra = null;
                if ($item->payment_status) {
                    $extra = '<span class="badge bg-success">' . trans('Sold') . '</span>
                             <span class="badge bg-secondary">' . $item->sellPostPayment?->transaction . '</span>';
                }
                return $item->title . ' ' . $extra;

            })
            ->addColumn('category', function ($item) {
                return optional($item->category)->details->name??null;
            })
            ->addColumn('price', function ($item) {
                return '<h5>' . currencyPosition($item->price) . '</h5>';
            })
            ->addColumn('user', function ($item) {
                $url = route("admin.user.edit", $item->user_id);
                return '<a class="d-flex align-items-center me-2" href="' . $url . '">
                                <div class="flex-shrink-0">
                                  ' . optional($item->user)->profilePicture() . '
                                </div>
                                <div class="flex-grow-1 ms-3">
                                  <h5 class="text-hover-primary mb-0">' . optional($item->user)->firstname . ' ' . optional($item->user)->lastname . '</h5>
                                  <span class="fs-6 text-body">@' . optional($item->user)->username . '</span>
                                </div>
                              </a>';
            })
            ->addColumn('status', function ($item) {
                return $item->statusMessage;
            })
            ->addColumn('date_at', function ($item) {
                return dateTime($item->created_at, basicControl()->date_time_format);
            })
            ->addColumn('action', function ($item) {
                $conversion = route('admin.sellPost.offer', [$item->id]);
                $edit = route('admin.sell.details', $item->id);

                $html = '<div class="btn-group sortable" role="group">
                      <a href="' . $edit . '" class="btn btn-white btn-sm">
                        <i class="fal fa-edit me-1"></i> ' . trans("Edit") . '
                      </a>';

                $html .= '<div class="btn-group">
                      <button type="button" class="btn btn-white btn-icon btn-sm dropdown-toggle dropdown-toggle-empty" id="userEditDropdown" data-bs-toggle="dropdown" aria-expanded="false"></button>
                      <div class="dropdown-menu dropdown-menu-end mt-1" aria-labelledby="userEditDropdown">
                        <a href="' . $conversion . '" class="dropdown-item">
                            <i class="fas fa-comments dropdown-item-icon"></i> ' . trans("Conversation") . '
                        </a>
                      </div>
                    </div>';

                $html .= '</div>';
                return $html;
            })
            ->rawColumns(['title', 'category', 'price', 'user', 'status', 'date_at', 'action'])
            ->make(true);
    }

    public function sellDetails($id)
    {
        $data['activity'] = ActivityLog::whereSell_post_id($id)->with('activityable:id,username,image,image_driver')->orderBy('id', 'desc')->get();

        $data['category'] = SellPostCategory::with('details')->whereStatus(1)->get();
        $data['sellPost'] = SellPost::findOrFail($id);

        return view('admin.sellPostList.edit', $data);
    }

    public function SellUpdate(Request $request, $id)
    {
        $purifiedData = $request->all();

        try {
            if ($request->has('image')) {
                $purifiedData['image'] = $request->image;
            }

            $rules = [
                'title' => 'required|max:40',
                'price' => 'required',
                'details' => 'required',
            ];
            $message = [
                'title.required' => 'Title field is required',
                'price.required' => 'Price field is required',
                'details.required' => 'Details field is required',
            ];

            $validate = Validator::make($purifiedData, $rules, $message);

            if ($validate->fails()) {
                return back()->withInput()->withErrors($validate);
            }


            $gameSell = SellPost::findOrFail($id);
            $gameSell->category_id = $request->category;

            $category = SellPostCategory::whereStatus(1)->findOrFail($gameSell->category_id);
            $rules = [];
            $inputField = [];
            if ($category->form_field != null) {
                foreach ($category->form_field as $key => $cus) {
                    $rules[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rules[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rules[$key], 'max:300');
                    }
                    $inputField[] = $key;
                }
            }

            $rulesSpecification = [];
            $inputFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($category->post_specification_form as $key => $cus) {
                    $rulesSpecification[$key] = [$cus->validation];
                    if ($cus->type == 'text') {
                        array_push($rulesSpecification[$key], 'max:191');
                    }
                    if ($cus->type == 'textarea') {
                        array_push($rulesSpecification[$key], 'max:300');
                    }
                    $inputFieldSpecification[] = $key;
                }
            }

            $collection = collect($request);
            $reqField = [];
            if ($category->form_field != null) {
                foreach ($collection as $k => $v) {
                    foreach ($category->form_field as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqField[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['credential'] = $reqField;
            } else {
                $gameSell['credential'] = null;
            }


            $collectionSpecification = collect($request);
            $reqFieldSpecification = [];
            if ($category->post_specification_form != null) {
                foreach ($collectionSpecification as $k => $v) {
                    foreach ($category->post_specification_form as $inKey => $inVal) {
                        if ($k != $inKey) {
                            continue;
                        } else {
                            $reqFieldSpecification[$inKey] = [
                                'field_name' => $inKey,
                                'field_value' => $v,
                                'type' => $inVal->type,
                                'validation' => $inVal->validation,
                            ];
                        }
                    }
                }
                $gameSell['post_specification_form'] = $reqFieldSpecification;
            } else {
                $gameSell['post_specification_form'] = null;
            }


            $images = array();
            if ($request->hasFile('image')) {

                try {
                    $gameImage = $purifiedData['image'];
                    $gamesellDriver = $gameSell->image_driver ?? 'local';
                    $oldImages = $request->oldImage ?? [];
                    $images = [];
                    $imagesDriver = [];

                    foreach ($gameImage as $file) {
                        $imageUp = $this->fileUpload($file, config('filelocation.sellingPost.path'), null, config('filelocation.sellingPost.thumb'), 'webp');
                        $images[] = $imageUp['path'];
                        $imagesDriver[] = $imageUp['driver'];
                    }
                    if (isset($request->changedImage) && count($request->changedImage) > 0) {
                        foreach ($request->changedImage as $key => $imageOld) {
                            if ($imageOld == 'changed') {
                                $this->fileDelete($gamesellDriver, $oldImages[$key]);
                                unset($oldImages[$key]);
                            }
                        }
                    }

                    $mergedImages = array_merge($oldImages, $images);

                    $gameSell->image = $mergedImages;
                    $gameSell->image_driver = $imagesDriver['0'];

                } catch (\Exception $exp) {
                    return back()->with('error', 'Image could not be uploaded.');
                }
            }

            if (isset($purifiedData['title'])) {
                $gameSell->title = $request->title;
            }
            if (isset($purifiedData['price'])) {
                $gameSell->price = $request->price;
            }

            if (isset($purifiedData['credential'])) {
                $gameSell->credential = $request->credential;
            }

            if (isset($purifiedData['details'])) {
                $gameSell->details = $request->details;
            }

            if (isset($purifiedData['status'])) {
                $gameSell->status = isset($purifiedData['status']) ? 1 : 0;
            }


            $gameSell->save();


            return back()->with('success', 'Successfully Updated');
        } catch (\Exception$e) {

            return back();
        }
    }

    public function sellAction(Request $request)
    {
        DB::beginTransaction();
        try {
            $gameSell = SellPost::findOrFail($request->sell_post_id);
            $gameSell->status = $request->status;
            $gameSell->save();


            $title = $gameSell->activityTitle;
            $admin = Auth::user();

            $activity = new ActivityLog();
            $activity->title = $title;
            $activity->sell_post_id = $request->sell_post_id;
            $activity->description = $request->comments;

            $admin->activities()->save($activity);
            DB::commit();

            $user = $gameSell->user;
            $msg = [
                'title' => $gameSell->title,
                'status' => $title,
                'comments' => $request->comments

            ];
            $action = [
                "link" => route('sellPost.details', [@$gameSell->title, $request->sell_post_id]),
                "icon" => "fa fa-money-bill-alt text-white"
            ];
            $this->userPushNotification($user, 'SELL_APPROVE', $msg, $action);

            $this->sendMailSms($user, 'SELL_APPROVE', [
                'title' => $gameSell->title,
                'status' => $title,
                'short_comment' => $request->comments
            ]);

            return back()->with('success', 'Update Successfully');

        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('error', $e->getMessage());
        }

    }

    public function SellDelete($id, $imgDelete)
    {
        $images = [];
        $galleryImage = SellPost::findOrFail($id);
        $old_images = $galleryImage->image;

        if (!empty($old_images)) {
            foreach ($old_images as $file) {
                $newString = Str::replaceFirst('sellingPost/', '', $file);
                if ($newString == $imgDelete) {
                    $this->fileDelete($galleryImage->image_driver, $file);
                } else {
                    $images[] = $file;
                }
            }
        }
        $galleryImage->image = $images;
        $galleryImage->save();
        return back()->with('success', 'Image has been deleted');
    }

    public function sellPostOffer($sellPostId)
    {
        $sellPostOffer = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($sellPostId)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $offer = null;
        if (0 < count($sellPostOffer)) {
            $offer = $sellPostOffer->first();

            if (!$offer->uuid) {
                $offer->uuid = Str::uuid();
                $offer->save();
            }

            return redirect()->route('admin.sellPost.conversation', $offer->uuid);
        } else {
            $offer = null;
        }


        $data['sellPostOffer'] = $sellPostOffer;
        $data['offer'] = $offer;
        return view('admin.sellPostList.offerList', $data);
    }

    public function conversation($uuid)
    {
        $offer = SellPostOffer::with(['user', 'lastMessage'])->where('uuid', $uuid)
            ->firstOrFail();

        $data['sellPostOffer'] = SellPostOffer::with(['user', 'lastMessage'])->whereSell_post_id($offer->sell_post_id)
            ->get()
            ->sortByDesc('lastMessage.created_at');

        $data['persons'] = SellPostChat::where([
            'offer_id' => $offer->id,
            'sell_post_id' => $offer->sell_post_id
        ])
            ->with('chatable')
            ->get()->pluck('chatable')->unique('chatable');

        $data['offer'] = $offer;

        return view('admin.sellPostList.offerList', $data);
    }

}
PK     :S\7<  <  2  Http/Controllers/AAdmin/PayoutMethodController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\PayoutMethod;
use Facades\App\Services\CurrencyLayerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Exception;
use App\Traits\Upload;

class PayoutMethodController extends Controller
{
    use Upload;

    public function index()
    {
        $data['payoutMethods'] = PayoutMethod::latest()->paginate(config('basic.paginate'));
        return view('admin.payout_methods.list', $data);
    }

    public function create()
    {
        $data['basicControl'] = basicControl();
        return view('admin.payout_methods.manual.create', $data);
    }

    public function store(Request $request)
    {

        $rules = [
            'name' => 'required|min:3|max:50|unique:payout_methods',
            'description' => 'required|min:3|max:50',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'is_active' => 'nullable|integer|min:0|in:0,1',
            'payout_currencies' => 'required|array',
            'payout_currencies.*.currency_symbol' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'payout_currencies.*.conversion_rate' => 'required|numeric',
            'payout_currencies.*.min_limit' => 'required|numeric',
            'payout_currencies.*.max_limit' => 'required|numeric',
            'payout_currencies.*.percentage_charge' => 'required|numeric',
            'payout_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'required|mimes:png,jpeg,gif|max:10240',
        ];


        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'payout_currencies.*.currency_symbol.required' => 'The payout currency  field is required.',
            'payout_currencies.*.currency_symbol.regex' => 'The payout currency field is invalid',
            'payout_currencies.*.conversion_rate.required' => 'The payout currency convention rate field is required.',
            'payout_currencies.*.conversion_rate.numeric' => 'The convention rate for payout currency must be a number.',
            'payout_currencies.*.min_limit.required' => 'The payout currency min limit field is required.',
            'payout_currencies.*.min_limit.numeric' => 'The min limit for payout currency must be a number.',
            'payout_currencies.*.max_limit.required' => 'The payout currency max limit field is required.',
            'payout_currencies.*.max_limit.numeric' => 'The max limit for payout currency must be a number.',
            'payout_currencies.*.percentage_charge.required' => 'The payout currency percentage charge field is required.',
            'payout_currencies.*.percentage_charge.numeric' => 'The percentage charge for payout currency must be a number.',
            'payout_currencies.*.fixed_charge.required' => 'The payout currency fixed charge is required.',
            'payout_currencies.*.fixed_charge.numeric' => 'The fixed charge for payout currency must be a number.',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessages);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        $inputForm = [];
        if ($request->has('field_name')) {
            for ($a = 0; $a < count($request->field_name); $a++) {
                $arr = array();
                $arr['field_name'] = clean($request->field_name[$a]);
                $arr['field_label'] = $request->field_name[$a];
                $arr['type'] = $request->input_type[$a];
                $arr['validation'] = $request->is_required[$a];
                $inputForm[$arr['field_name']] = $arr;
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.payoutMethod.path'), null, null, 'webp', 70);
                if ($image) {
                    $payoutGatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }

        $collection = collect($request->payout_currencies);
        $supportedCurrency = $collection->pluck('currency_symbol')->all();
        $response = PayoutMethod::create([
            'name' => $request->name,
            'code' => Str::slug($request->name),
            'description' => $request->description,
            'banks' => $request->banks ?? null,
            'supported_currency' => $supportedCurrency,
            'payout_currencies' => $request->payout_currencies,
            'is_active' => $request->status,
            'inputForm' => $inputForm,
            'logo' => $payoutGatewayImage ?? null,
            'driver' => $driver ?? null
        ]);

        if (!$response) {
            throw new Exception('Something went wrong.Please try again');
        }

        return redirect()->back()->with('success', 'Payout Method Successfully Saved');

    }

    public function edit($id)
    {
        $basicControl = basicControl();
        $payoutMethod = PayoutMethod::findOrFail($id);

        $banks = $payoutMethod->banks ?? [];

        return view('admin.payout_methods.edit', compact('payoutMethod', 'banks', 'basicControl'));
    }


    public function update(Request $request, $id)
    {
        $rules = [
            'name' => 'required|min:3|max:50|unique:payout_methods,name,' . $id,
            'description' => 'required|min:3|max:50',
            'field_name.*' => 'required|string',
            'input_type.*' => 'required|in:text,textarea,file,date,number',
            'is_required.*' => 'required|in:required,optional',
            'is_active' => 'nullable|integer|min:0|in:0,1',
            'payout_currencies' => 'required|array',
            'payout_currencies.*.currency_symbol' => 'required|string|max:255|regex:/^[A-Z\s]+$/',
            'payout_currencies.*.conversion_rate' => 'required|numeric',
            'payout_currencies.*.min_limit' => 'required|numeric',
            'payout_currencies.*.max_limit' => 'required|numeric',
            'payout_currencies.*.percentage_charge' => 'required|numeric',
            'payout_currencies.*.fixed_charge' => 'required|numeric',
            'image' => 'nullable|mimes:png,jpeg,gif|max:10240',
            'auto_update_currency' => 'nullable|integer|in:0,1'
        ];

        $customMessages = [
            'field_name.*.required' => 'The form label field is required.',
            'input_type.*.required' => 'The input type field is required.',
            'is_required.*.required' => 'The required field is required.',
            'input_type.*.in' => 'The Input type is invalid.',
            'is_required.*.in' => 'The required value is invalid.',
            'payout_currencies.*.currency_symbol.required' => 'The payout currency  field is required.',
            'payout_currencies.*.currency_symbol.regex' => 'The payout currency symbol must contain only uppercase letters.',
            'payout_currencies.*.conversion_rate.required' => 'The payout currency convention rate field is required.',
            'payout_currencies.*.conversion_rate.numeric' => 'The convention rate for payout currency must be a number.',
            'payout_currencies.*.min_limit.required' => 'The payout currency min limit field is required.',
            'payout_currencies.*.min_limit.numeric' => 'The min limit for payout currency must be a number.',
            'payout_currencies.*.max_limit.required' => 'The payout currency max limit field is required.',
            'payout_currencies.*.max_limit.numeric' => 'The max limit for payout currency must be a number.',
            'payout_currencies.*.percentage_charge.required' => 'The payout currency percentage charge field is required.',
            'payout_currencies.*.percentage_charge.numeric' => 'The percentage charge for payout currency must be a number.',
            'payout_currencies.*.fixed_charge.required' => 'The payout currency fixed charge is required.',
            'payout_currencies.*.fixed_charge.numeric' => 'The fixed charge for payout currency must be a number.',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessages);

        if ($validator->fails()) {
            $names = collect(request()->payout_currencies)
                ->filter(function ($item) {
                    return isset($item['name']) && $item['name'] !== null;
                })
                ->pluck('name')
                ->toArray();
            return redirect()
                ->back()
                ->withErrors($validator)
                ->withInput($request->input())
                ->with('selectedCurrencyList', $names);
        }

        $payoutMethod = PayoutMethod::findOrFail($id);

        $inputForm = [];
        if (isset($request->field_name)) {
            $inputs = [];
            for ($i = 0; $i < count($request->field_name); $i++) {
                $inputs['field_name'] = strtolower(Str::snake($request->field_name[$i]));
                $inputs['field_label'] = $request->field_name[$i];
                $inputs['type'] = $request->input_type[$i];
                $inputs['validation'] = $request->is_required[$i];
                $inputForm[$inputs['field_name']] = $inputs;
            }
        }

        $parameters = [];
        if ($payoutMethod->parameters) {
            foreach ($request->except('_token', '_method', 'image') as $k => $v) {
                foreach ($payoutMethod->parameters as $key => $cus) {
                    if ($k != $key) {
                        continue;
                    } else {
                        $rules[$key] = 'required|max:191';
                        $parameters[$key] = $v;
                    }
                }
            }
        }

        if ($request->hasFile('image')) {
            try {
                $image = $this->fileUpload($request->image, config('filelocation.payoutMethod.path'), null, null, 'webp', 70, $payoutMethod->logo, $payoutMethod->driver);
                if ($image) {
                    $gatewayImage = $image['path'];
                    $driver = $image['driver'];
                }
            } catch (\Exception $exp) {
                return back()->with('error', 'Image could not be uploaded.');
            }
        }


        $collection = collect($request->payout_currencies);
        if ($payoutMethod->is_automatic == 1) {
            $supportedCurrency = $collection->pluck('name')->all();
        } else {

            $supportedCurrency = $collection->pluck('currency_symbol')->all();
        }


        $response = $payoutMethod->update([
            'name' => $request->name,
            'banks' => $request->banks,
            'parameters' => $parameters,
            'description' => $request->description,
            'supported_currency' => $supportedCurrency,
            'payout_currencies' => $request->payout_currencies,
            'is_active' => $request->status,
            'is_auto_update' => $request->auto_update_currency,
            'environment' => $request->environment ?? 1,
            'inputForm' => $inputForm ?? $payoutMethod->inputForm,
            'logo' => $gatewayImage ?? $payoutMethod->logo,
            'driver' => $driver ?? $payoutMethod->driver,
        ]);

        if (!$response) {
            throw new Exception('Something went wrong.Please try again');
        }

        return redirect()->back()->with('success', 'Withdraw Method Updated Successfully');
    }


    public function activeDeactivate(Request $request)
    {
        try {
            $payoutMethod = PayoutMethod::where('code', $request->code)->firstOrFail();
            $payoutMethod->update([
                'is_active' => $payoutMethod->is_active == 1 ? 0 : 1
            ]);
            return back()->with('success', 'Payout method status updated successfully.');
        } catch (Exception $e) {
            return back()->with('error', $e->getMessage());
        }
    }

    public function autoUpdate(Request $request, $id)
    {
        $updateForMethods = PayoutMethod::where('code', '!=', 'coinbase')
            ->where('is_automatic', 1)
            ->where('is_auto_update', 1)
            ->where('id', $id)->firstOrFail();

        $autoCurrencyUpdate = CurrencyLayerService::getCurrencyRate();

        $autoUp = [];
        foreach ($autoCurrencyUpdate->quotes as $key => $quote) {
            $strReplace = str_replace($autoCurrencyUpdate->source, '', $key);
            $autoUp[$strReplace] = $quote;
        }

        $usdToBase = 1.00;
        $currenciesArr = [];
        foreach ($updateForMethods->payout_currencies as $key => $payout_currency) {
            foreach ($payout_currency as $key1 => $item) {
                $resRate = $this->getCheck($payout_currency->name, $autoUp);
                $curRate = round($resRate / $usdToBase, 2);
                if ($resRate && $key1 == 'conversion_rate') {
                    $currenciesArr[$key][$key1] = $curRate;
                } else {
                    $currenciesArr[$key][$key1] = $item;
                }
            }
        }
        $updateForMethods->payout_currencies = $currenciesArr;
        $updateForMethods->save();
        return back()->with('success', 'Auto Currency Updated Successfully');
    }


    public function withdrawDays()
    {
        $data['withdrawalConfig'] = config("withdrawaldays");
        return view('admin.payout_methods.withdraw_days', $data);
    }

    public function withdrawDaysUpdate(Request $request)
    {
        $request->validate([
            "monday" => "nullable|integer|in:0,1",
            "tuesday" => "nullable|integer|in:0,1",
            "wednesday" => "nullable|integer|in:0,1",
            "thursday" => "nullable|integer|in:0,1",
            "friday" => "nullable|integer|in:0,1",
            "saturday" => "nullable|integer|in:0,1",
            "sunday" => "nullable|integer|in:0,1",
        ]);

        config(['withdrawaldays.Monday' => (int)$request->monday]);
        config(['withdrawaldays.Tuesday' => (int)$request->tuesday]);
        config(['withdrawaldays.Wednesday' => (int)$request->wednesday]);
        config(['withdrawaldays.Thursday' => (int)$request->thursday]);
        config(['withdrawaldays.Friday' => (int)$request->friday]);
        config(['withdrawaldays.Saturday' => (int)$request->saturday]);
        config(['withdrawaldays.Sunday' => (int)$request->sunday]);

        $fp = fopen(base_path() . '/config/withdrawaldays.php', 'w');
        fwrite($fp, '<?php return ' . var_export(config('withdrawaldays'), true) . ';');
        fclose($fp);

        Artisan::call('config:clear');

        return back()->with("success", "Successfully Updated");
    }

    public function getCheck($currency, $autoUp)
    {
        foreach ($autoUp as $key => $auto) {
            if ($key == $currency) {
                return $auto;
            }
        }
    }

}
PK     :S\b    2  Http/Controllers/AAdmin/CookiePolicyController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Traits\Notify;
use App\Traits\Upload;
use Illuminate\Http\Request;

class CookiePolicyController extends Controller
{
    use Upload, Notify;
    public function cookiePolicySetting(){
        return view('admin.control_panel.cookie_policy_settings');
    }

    public function cookiePolicyUpdate (Request $request){

        $basic = basicControl();

        if ($request->hasFile('cookie_image')) {
            $photo = $this->fileUpload($request->cookie_image, config('filelocation.cookie.path'), null, null, 'webp', 60);

            $basic->cookie_image = $photo['path'] ?? null;
            $basic->cookie_image_driver = $photo['driver'] ?? null;
            $basic->save();
        }

        $basic->cookie_status = $request->cookie_status;
        $basic->cookie_heading = $request->cookie_heading;
        $basic->cookie_description = $request->cookie_description;
        $basic->cookie_button = $request->cookie_button;
        $basic->cookie_button_link = $request->cookie_button_link;
        $basic->save();


        return back()->with('success', 'cookie settings changed.');
    }
}
PK     :S\@Wݺn  n  4  Http/Controllers/AAdmin/FirebaseConfigController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Facades\App\Services\BasicService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class FirebaseConfigController extends Controller
{
    public function firebaseConfig()
    {
        $data['basicControl'] = basicControl();
        $data['firebaseNotify'] = config('firebase');
        return view('admin.control_panel.firebase_config', $data);
    }

    public function firebaseConfigUpdate(Request $request)
    {
        $request->validate([
            'api_key' => 'required|string',
            'vapid_key' => 'required|string',
            'auth_domain' => 'required|string',
            'project_id' => 'required|string',
            'storage_bucket' => 'required|string',
            'messaging_sender_id' => 'required|string',
            'app_id' => 'required|string',
            'measurement_id' => 'required|string',
            'push_notification' => 'nullable|integer|in:0,1',
            'user_foreground' => 'nullable|integer|in:0,1',
            'user_background' => 'nullable|integer|in:0,1',
            'admin_foreground' => 'nullable|integer|in:0,1',
            'admin_background' => 'nullable|integer|in:0,1',
        ]);

        try {
            $env = [
                'FIREBASE_API_KEY' => $request->api_key,
                'FIREBASE_VAPID_KEY' => $request->vapid_key,
                'FIREBASE_AUTH_DOMAIN' => $request->auth_domain,
                'FIREBASE_PROJECT_ID' => $request->project_id,
                'FIREBASE_STORAGE_BUCKET' => $request->storage_bucket,
                'FIREBASE_MESSAGING_SENDER_ID' => $request->messaging_sender_id,
                'FIREBASE_API_ID' => $request->app_id,
                'FIREBASE_MEASUREMENT_ID' => $request->measurement_id,
                'USER_FOREGROUND' => $request->user_foreground,
                'USER_BACKGROUND' => $request->user_background,
                'ADMIN_FOREGROUND' => $request->admin_foreground,
                'ADMIN_BACKGROUND' => $request->admin_background,
            ];

            BasicService::setEnv($env);

            $basicControl = basicControl();
            $basicControl->update([
                'push_notification' => $request->push_notification
            ]);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Firebase Configure Successfully.');
    }

    public function firebaseConfigFileUpload(Request $request)
    {
        $this->validate($request, [
            'file' => 'required|file|mimetypes:application/json|mimes:json',
        ]);

        $file = $request->file('file');
        $file->move(base_path(), getFirebaseFileName());

        return back()->with('success', 'Uploaded Successfully');
    }

    public function firebaseConfigFileDownload()
    {
        $filePath = base_path(getFirebaseFileName());
        if (File::exists($filePath)) {
            return response()->download($filePath, getFirebaseFileName());
        } else {
            return response()->json(['error' => 'File not found!'], 404);
        }
    }

}
PK     :S\hU)    :  Http/Controllers/AAdmin/Auth/ConfirmPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\ConfirmsPasswords;

class ConfirmPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Confirm Password Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password confirmations and
    | uses a simple trait to include the behavior. You're free to explore
    | this trait and override any functions that require customization.
    |
    */

    use ConfirmsPasswords;

    /**
     * Where to redirect users when the intended url fails.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::ADMIN;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }
}
PK     :S\    9  Http/Controllers/AAdmin/Auth/ForgotPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Mail\SendMail;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;

class ForgotPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset emails and
    | includes a trait which assists in sending these notifications from
    | your application to your users. Feel free to explore this trait.
    |
    */

    use SendsPasswordResetEmails;

    /**
     * Display the form to request a password reset link.
     *
     * @return \Illuminate\View\View
     */
    public function showLinkRequestForm()
    {
        return view('admin.auth.passwords.email');
    }

    /**
     * Send a reset link to the given user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    public function sendResetLinkEmail(Request $request)
    {

        $this->validateEmail($request);

        // We will send the password reset link to this user. Once we have attempted
        // to send the link, we will examine the response then see the message we
        // need to show to the user. Finally, we'll send out a proper response.
        $response = $this->broker()->sendResetLink(
            $this->credentials($request)
        );

        return $response == Password::RESET_LINK_SENT
            ? $this->sendResetLinkResponse($request, $response)
            : $this->sendResetLinkFailedResponse($request, $response);

    }

    /**
     * Get the response for a successful password reset link.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $response
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
     */
    protected function sendResetLinkResponse(Request $request, $response)
    {
        $userEmail = $request->get('email');
        $passwordReset = DB::table('password_reset_tokens')->where('email', $userEmail)->first();
        if (!$passwordReset) {
            return back()->with('error','Password reset token not found. Please try again.');
        }
        $token = $passwordReset->token;
        $resetUrl = url(basicControl()->admin_prefix.'/password/reset', rawurlencode($token)) . '?email='.$userEmail;
        $message = 'Your Password Recovery Link: <a href="' . $resetUrl . '" target="_blank">Click To Reset Password</a>';
        $emailFrom = basicControl()->sender_email;

        try {
            Mail::to($userEmail)->send(new SendMail($emailFrom, 'Password Recovery', $message));
        } catch (\Exception $e) {
            return back()->with('error','Failed to send the password reset email. Please try again later.');
        }

        return back()->with('success','Password reset email successfully sent.');
    }


    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('admins');
    }
}
PK     :S\+q  q  7  Http/Controllers/AAdmin/Auth/VerificationController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\VerifiesEmails;

class VerificationController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Email Verification Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling email verification for any
    | user that recently registered with the application. Emails may also
    | be re-sent if the user didn't receive the original email message.
    |
    */

    use VerifiesEmails;

    /**
     * Where to redirect users after verification.
     *
     * @var string
     */
    protected $redirectTo = RouteServiceProvider::ADMIN;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('signed')->only('verify');
        $this->middleware('throttle:6,1')->only('verify', 'resend');
    }
}
PK     :S\TS  S  0  Http/Controllers/AAdmin/Auth/LoginController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Validator;
use Facades\App\Services\Google\GoogleRecaptchaService;


class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    protected $redirectTo = 'admin/dashboard';

    public function __construct()
    {
        $this->middleware('guest:admin')->except('logout');
    }

    public function showLoginForm()
    {
        $data['basicControl'] = basicControl();
        return view('admin.auth.login', $data);
    }

    protected function guard()
    {
        return Auth::guard('admin');
    }

    public function login(Request $request)
    {
        $basicControl = basicControl();
        $input = $request->all();

        $rules[$this->username()] = 'required';
        $rules ['password'] = 'required';
        if ($basicControl->manual_recaptcha == 1 && $basicControl->manual_recaptcha_admin_login == 1) {
            $rules['captcha'] = ['required',
                Rule::when((!empty($request->captcha) && strcasecmp(session()->get('captcha'), $_POST['captcha']) != 0), ['confirmed']),
            ];
        }

        if ($basicControl->google_recaptcha_admin_login == 1 && $basicControl->google_recaptcha == 1) {
            GoogleRecaptchaService::responseRecaptcha($request['g-recaptcha-response']);
            $rules['g-recaptcha-response'] = 'sometimes|required';
        }

        $message['captcha.confirmed'] = "The captcha does not match.";
        $validator = Validator::make($request->all(), $rules, $message);
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $remember_me = $request->has('remember_me') ? true : false;
        $fieldType = filter_var($request->username, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        if (auth()->guard('admin')->attempt(array($fieldType => $input['username'], 'password' => $input['password']), $remember_me)) {
            return $this->sendLoginResponse($request);
        } else {
            return redirect()->route('admin.login')
                ->with('error', 'Email-Address And Password Are Wrong.');
        }
    }

    public function username()
    {
        $login = request()->input('username');
        $field = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        request()->merge([$field => $login]);
        return $field;
    }

    protected function validateLogin(Request $request)
    {
        $request->validate([
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    public function logout(Request $request)
    {
        $this->guard('guard')->logout();
        $request->session()->invalidate();
        return $this->loggedOut($request) ?: redirect()->route('admin.login');
    }

    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        if ($response = $this->authenticated($request, $this->guard('admin')->user())) {
            return $response;
        }

        return $request->wantsJson()
            ? new JsonResponse([], 204)
            : redirect()->intended($this->redirectPath());
    }


    /**
     * The user has been authenticated.
     *
     * @param \Illuminate\Http\Request $request
     * @param mixed $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        if ($user->status == 0) {
            $this->guard('guard')->logout();
            return redirect()->route('admin.login')->with('error', 'You are banned from this application. Please contact with system Administrator.');
        }
        $user->last_login = Carbon::now();
        $user->save();

        if (config('demo.IS_DEMO') == true) {
            $checkUser = \App\Models\User::firstOrNew(['id' => 1]);
            $checkUser->username = 'demouser';
            $checkUser->password = bcrypt('demouser');
            $checkUser->sms_verification = 1;
            $checkUser->email_verification = 1;
            $checkUser->two_fa = 0;
            $checkUser->two_fa_verify = 1;
            $checkUser->status = 1;
            $checkUser->save();
        }
    }
}
PK     :S\V9[O  O  8  Http/Controllers/AAdmin/Auth/ResetPasswordController.phpnu [        <?php

namespace App\Http\Controllers\Admin\Auth;

use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\ResetsPasswords;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Password;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */
    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = 'admin/dashboard';

    /**
     * Display the password reset view for the given token.
     *
     * If no token is present, display the link request form.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string|null  $token
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showResetForm(Request $request, $token = null)
    {

        return view('admin.auth.passwords.reset')->with(
            ['token' => $token, 'email' => $request->email]
        );
    }

    public function reset(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|confirmed|min:5',
            'token' => 'required',
        ]);
        $token = rawurldecode($request->token);

        $passwordReset = DB::table('password_reset_tokens')->where('email', $request->email)->first();
        if (!$passwordReset || $passwordReset->token != $token) {
            return back()->withErrors(['email' => 'This password reset token is invalid.']);
        }

        $user = Admin::where('email', $request->email)->first();
        $user->password = bcrypt($request->password);
        $user->save();
        //DB::table('password_reset_tokens')->where('email', $request->email)->delete();

        return redirect()->route('admin.login')->with('success', 'Your password has been reset!');
    }


    /**
     * Get the broker to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\PasswordBroker
     */
    public function broker()
    {
        return Password::broker('admins');
    }


    /**
     * Get the guard to be used during password reset.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }
}
PK     :S\"t^  ^  /  Http/Controllers/AAdmin/SocialiteController.phpnu [        <?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Validator;
use Stevebauman\Purify\Facades\Purify;

class SocialiteController extends Controller
{
    public function index()
    {
        return view('admin.control_panel.socialiteConfig');
    }

    public function githubConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.githubControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'github_client_id' => 'required|min:3',
                'github_client_secret' => 'required|min:3',
                'github_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;
            config(['socialite.github_status' => $purifiedData->github_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('GITHUB_CLIENT_ID', $purifiedData->github_client_id, $env);
            $env = $this->set('GITHUB_CLIENT_SECRET', $purifiedData->github_client_secret, $env);
            $env = $this->set('GITHUB_REDIRECT_URL', route('socialiteCallback', 'github'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    public function googleConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.googleControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'google_client_id' => 'required|min:3',
                'google_client_secret' => 'required|min:3',
                'google_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;
            config(['socialite.google_status' => $purifiedData->google_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('GOOGLE_CLIENT_ID', $purifiedData->google_client_id, $env);
            $env = $this->set('GOOGLE_CLIENT_SECRET', $purifiedData->google_client_secret, $env);
            $env = $this->set('GOOGLE_REDIRECT_URL', route('socialiteCallback', 'google'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    public function facebookConfig(Request $request)
    {
        if ($request->isMethod('get')) {
            return view('admin.control_panel.facebookControl');
        } elseif ($request->isMethod('post')) {
            $purifiedData = Purify::clean($request->all());

            $validator = Validator::make($purifiedData, [
                'facebook_client_id' => 'required|min:3',
                'facebook_client_secret' => 'required|min:3',
                'facebook_status' => 'nullable|integer|min:0|in:0,1',
            ]);

            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
            $purifiedData = (object)$purifiedData;

            config(['socialite.facebook_status' => $purifiedData->facebook_status]);
            $fp = fopen(base_path() . '/config/socialite.php', 'w');
            fwrite($fp, '<?php return ' . var_export(config('socialite'), true) . ';');
            fclose($fp);

            $envPath = base_path('.env');
            $env = file($envPath);
            $env = $this->set('FACEBOOK_CLIENT_ID', $purifiedData->facebook_client_id, $env);
            $env = $this->set('FACEBOOK_CLIENT_SECRET', $purifiedData->facebook_client_secret, $env);
            $env = $this->set('FACEBOOK_REDIRECT_URL', route('socialiteCallback', 'facebook'), $env);

            $fp = fopen($envPath, 'w');
            fwrite($fp, implode($env));
            fclose($fp);

            Artisan::call('optimize:clear');
            return back()->with('success', 'Successfully Updated');
        }
    }

    private function set($key, $value, $env)
    {
        foreach ($env as $env_key => $env_value) {
            $entry = explode("=", $env_value, 2);
            if ($entry[0] == $key) {
                $env[$env_key] = $key . "=" . $value . "\n";
            } else {
                $env[$env_key] = $env_value;
            }
        }
        return $env;
    }
}
PK       u\qF  F                  Rules/PhoneLength.phpnu [        PK       x\m    !              Rules/AlphaDashWithoutSlashes.phpnu [        PK       x\                y  Console/Kernel.phpnu [        PK       x\`                 Z  Console/Commands/ReviewCount.phpnu [        PK       x\=ºm  m  *              Console/Commands/GatewayCurrencyUpdate.phpnu [        PK       x\                        '  Console/Commands/index.phpnu [        PK       x\⨏n  n  -            '  Console/Commands/PayoutCurrencyUpdateCron.phpnu [        PK       x\b    "            6  Console/Commands/CampaignCheck.phpnu [        PK       x\16    !            G  Events/UpdateUserNotification.phpnu [        PK       x\*    "            J  Events/UpdateAdminNotification.phpnu [        PK       x\"  "               	N  Events/OfferChatNotification.phpnu [        PK       x\u|8  8              {Q  Events/AdminNotification.phpnu [        PK       x\uil  l              T  Events/UserNotification.phpnu [        PK       x\$<    &            W  Events/UpdateOfferChatNotification.phpnu [        PK       x\>,W                [  Exceptions/Handler.phpnu [        PK       x\4  4              a^  Scopes/EnsureCardIdScope.phpnu [        PK       x\c7  7              _  Scopes/EnsureTopUpIdScope.phpnu [        PK       x\"<  <               ea  Scopes/EnsureCategoryIdScope.phpnu [        PK       x\Ğ    )            b  Http/Controllers/Api/CouponController.phpnu [        PK       x\r"  r"  '            p  Http/Controllers/Api/CardController.phpnu [        PK       x\\1%  %  '              Http/Controllers/Api/AuthController.phpnu [        PK       x\,  ,  0            
  Http/Controllers/Api/SupportTicketController.phpnu [        PK       x\ )  )  *            {  Http/Controllers/Api/ProfileController.phpnu [        PK       x\
^  ^  )             Http/Controllers/Api/PayoutController.phpnu [        PK       x\@4  4  &            n Http/Controllers/Api/BuyController.phpnu [        PK       x\ٴ(,  ,  (             Http/Controllers/Api/TopUpController.phpnu [        PK       x\{  {  +             Http/Controllers/Api/SellPostController.phpnu [        PK       x\f    0            q| Http/Controllers/Api/TwoFASecurityController.phpnu [        PK       x\\_7  _7  *             Http/Controllers/Api/MyOrderController.phpnu [        PK       x\F=nA  nA  '            U Http/Controllers/Api/ShopController.phpnu [        PK       x\#\  #\  '             Http/Controllers/Api/HomeController.phpnu [        PK       x\>E    /            ^ Http/Controllers/Api/VerificationController.phpnu [        PK       x\3+  +              r Http/Controllers/Controller.phpnu [        PK       x\2&E
  E
  0            %t Http/Controllers/InAppNotificationController.phpnu [        PK       x\	ïJ      .            ~ Http/Controllers/ManualRecaptchaController.phpnu [        PK       x\0>B=  =  '             Http/Controllers/FrontendController.phpnu [        PK       x\[D!'  '  1            R Http/Controllers/User/SupportTicketController.phpnu [        PK       x\&e=i  i  *            : Http/Controllers/User/PayoutController.phpnu [        PK       x\"    -            0O Http/Controllers/User/DashboardController.phpnu [        PK       x\A  A  ,            V Http/Controllers/User/SellPostController.phpnu [        PK       x\6    3            : Http/Controllers/User/KycVerificationController.phpnu [        PK       x\1!    )            I' Http/Controllers/User/OrderController.phpnu [        PK       x\zn2  2  (            o5 Http/Controllers/User/HomeController.phpnu [        PK       x\[͉0\  \  0            h Http/Controllers/User/VerificationController.phpnu [        PK       x\#׭	  	  +            K Http/Controllers/User/DepositController.phpnu [        PK       x\[]  ]  0             Http/Controllers/User/NotificationController.phpnu [        PK       x\iT  T  -            } Http/Controllers/User/SocialiteController.phpnu [        PK       x\vw3    /            . Http/Controllers/ChatNotificationController.phpnu [        PK       x\w&  &  ,             Http/Controllers/Frontend/CardController.phpnu [        PK       x\gKiN2  N2  -             Http/Controllers/Frontend/TopUpController.phpnu [        PK       x\+Zj-  -  ,            S Http/Controllers/Frontend/CartController.phpnu [        PK       x\,    ,            * Http/Controllers/Frontend/BlogController.phpnu [        PK       x\ق    )            9 Http/Controllers/FaSecurityController.phpnu [        PK       x\cJj  j  )            D Http/Controllers/Admin/LogoController.phpnu [        PK       x\fH2  H2  -            QQ Http/Controllers/Admin/LanguageController.phpnu [        PK       x\F6  6  (             Http/Controllers/Admin/KycController.phpnu [        PK       x\z  z  2             Http/Controllers/Admin/PaymentMethodController.phpnu [        PK       x\2-  -  2             Http/Controllers/Admin/SupportTicketController.phpnu [        PK       x\R8_2  2  3            _ Http/Controllers/Admin/RolePermissionController.phpnu [        PK       x\%]Ժ)  )  ,            5 Http/Controllers/Admin/ContentController.phpnu [        PK       x\g  g  ,            _ Http/Controllers/Admin/StorageController.phpnu [        PK       x\x#*  #*  -            Xs Http/Controllers/Admin/CurrencyController.phpnu [        PK       x\uCA  CA  )            ؝ Http/Controllers/Admin/PageController.phpnu [        PK       x\k[=    /            t Http/Controllers/Admin/ManageMenuController.phpnu [        PK       x\c     4             Http/Controllers/Admin/MaintenanceModeController.phpnu [        PK       x\Y1  1  .            : Http/Controllers/Admin/PayoutLogController.phpnu [        PK       x\>:  :  .            o5 Http/Controllers/Admin/DashboardController.phpnu [        PK       x\db[H+  H+  2            wp Http/Controllers/Admin/ManualGatewayController.phpnu [        PK       x\N    1            ! Http/Controllers/Admin/BlogCategoryController.phpnu [        PK       x\pUk<  k<  9             Http/Controllers/Admin/NotificationTemplateController.phpnu [        PK       x\qγn    +             Http/Controllers/Admin/PluginController.phpnu [        PK       x\ۖQ  Q  1            	 Http/Controllers/Admin/BasicControlController.phpnu [        PK       x\t0XM  M  .            "	 Http/Controllers/Admin/SubscribeController.phpnu [        PK       x\AA      8            w1	 Http/Controllers/Admin/AdminProfileSettingController.phpnu [        PK       x\PM  M  /            >	 Http/Controllers/Admin/PaymentLogController.phpnu [        PK       x\>,  ,  )            @	 Http/Controllers/Admin/BlogController.phpnu [        PK       x\J  J  3            b	 Http/Controllers/Admin/TransactionLogController.phpnu [        PK       x\KI	  	  8            	 Http/Controllers/Admin/TranslateAPISettingController.phpnu [        PK       x\O5  5  -            i	 Http/Controllers/Admin/TempleteController.phpnu [        PK       x\Ol[n  n  1            	 Http/Controllers/Admin/PusherConfigController.phpnu [        PK       x\]    2            	 Http/Controllers/Admin/Module/CouponController.phpnu [        PK       x\pH  H  0            A	 Http/Controllers/Admin/Module/CardController.phpnu [        PK       x\yk5  5  8            QH
 Http/Controllers/Admin/Module/TopUpServiceController.phpnu [        PK       x\Wz	D8  D8  7            ~
 Http/Controllers/Admin/Module/CardServiceController.phpnu [        PK       x\Ͼ)  )  7            Z
 Http/Controllers/Admin/Module/SellSummaryController.phpnu [        PK       x\F  F  1            
 Http/Controllers/Admin/Module/TopUpController.phpnu [        PK       x\b9z<  z<  5            n( Http/Controllers/Admin/Module/CardOrderController.phpnu [        PK       x\@5]    4            Me Http/Controllers/Admin/Module/CampaignController.phpnu [        PK       x\И"  "  2            lx Http/Controllers/Admin/Module/ReviewController.phpnu [        PK       x\?"  "  ;             Http/Controllers/Admin/Module/CardServiceCodeController.phpnu [        PK       x\Ǝ5  5  6             Http/Controllers/Admin/Module/TopUpOrderController.phpnu [        PK       x\W,'  '  4             Http/Controllers/Admin/Module/CategoryController.phpnu [        PK       x\SY6g  g  <             Http/Controllers/Admin/Module/SellPostCategoryController.phpnu [        PK       x\Fև    5             Http/Controllers/Admin/GoogleApiSettingController.phpnu [        PK       x\X=% =% *             Http/Controllers/Admin/UsersController.phpnu [        PK       x\Yʎ
  
  .             Http/Controllers/Admin/SmsConfigController.phpnu [        PK       x\^r    0             Http/Controllers/Admin/EmailConfigController.phpnu [        PK       x\IZgg  g  5            S Http/Controllers/Admin/SellPostCategoryController.phpnu [        PK       x\7<  <  1            EG Http/Controllers/Admin/PayoutMethodController.phpnu [        PK       x\b    1            { Http/Controllers/Admin/CookiePolicyController.phpnu [        PK       x\@Wݺn  n  3             Http/Controllers/Admin/FirebaseConfigController.phpnu [        PK       x\hU)    9            V Http/Controllers/Admin/Auth/ConfirmPasswordController.phpnu [        PK       x\    8            ƚ Http/Controllers/Admin/Auth/ForgotPasswordController.phpnu [        PK       x\+q  q  6             Http/Controllers/Admin/Auth/VerificationController.phpnu [        PK       x\TS  S  /             Http/Controllers/Admin/Auth/LoginController.phpnu [        PK       x\V9[O  O  7             Http/Controllers/Admin/Auth/ResetPasswordController.phpnu [        PK       x\"t^  ^  .            V Http/Controllers/Admin/SocialiteController.phpnu [        PK       x\( 4#  4#  &             Http/Controllers/PaymentController.phpnu [        PK       x\[      3             Http/Controllers/Auth/ConfirmPasswordController.phpnu [        PK       x\*1    ,            
 Http/Controllers/Auth/RegisterController.phpnu [        PK       x\>a1    2            Y' Http/Controllers/Auth/ForgotPasswordController.phpnu [        PK       x\8    0            0 Http/Controllers/Auth/VerificationController.phpnu [        PK       x\4b?  ?  )            6 Http/Controllers/Auth/LoginController.phpnu [        PK       x\D*  *  1            Q Http/Controllers/Auth/ResetPasswordController.phpnu [        PK       x\	    $            !W Http/Requests/CardServiceRequest.phpnu [        PK       x\k\    #            Z Http/Requests/TopUpStoreRequest.phpnu [        PK       x\(    &            ^ Http/Requests/CurrencyStoreRequest.phpnu [        PK       x\+~~  ~  '            a Http/Requests/CategoryUpdateRequest.phpnu [        PK       x\X~  ~  &            d Http/Requests/CategoryStoreRequest.phpnu [        PK       x\j D  D  +            ug Http/Requests/BannerSettingStoreRequest.phpnu [        PK       x\Ss-E  E  %            k Http/Requests/TopUpServiceRequest.phpnu [        PK       x\%q    "            n Http/Requests/GameStoreRequest.phpnu [        PK       x\3c    "            r Http/Requests/CardStoreRequest.phpnu [        PK       x\ 8    #            w Http/Middleware/MaintenanceMode.phpnu [        PK       x\f    #            y Http/Middleware/CheckUserStatus.phpnu [        PK       x\@                | Http/Middleware/Demo.phpnu [        PK       x\	1@  @               Http/Middleware/Preview.phpnu [        PK       x\I	  	  "            h Http/Middleware/CheckStatusApi.phpnu [        PK       x\~}  }               Http/Middleware/TrimStrings.phpnu [        PK       x\Y    #             Http/Middleware/VerifyCsrfToken.phpnu [        PK       x\{{n  n  4             Http/Middleware/PreventRequestsDuringMaintenance.phpnu [        PK       x\    +             Http/Middleware/RedirectIfAuthenticated.phpnu [        PK       x\Q#{  {              Ε Http/Middleware/TrustHosts.phpnu [        PK       x\g{R  R               Http/Middleware/CheckModule.phpnu [        PK       x\bi'  '              8 Http/Middleware/Language.phpnu [        PK       x\j                  Http/Middleware/TrustProxies.phpnu [        PK       x\Q                 Http/Middleware/apiKYC.phpnu [        PK       x\^sI    "            ^ Http/Middleware/CheckModuleApi.phpnu [        PK       x\=;a  a  "            z Http/Middleware/ActivityByUser.phpnu [        PK       x\Gf    %            - Http/Middleware/ValidateSignature.phpnu [        PK       x\"q3  3  "            N Http/Middleware/EncryptCookies.phpnu [        PK       x\*?_  _              ӵ Http/Middleware/KYC.phpnu [        PK       x\q      '            y Http/Middleware/ValidateRequestData.phpnu [        PK       x\K )  )               о Http/Middleware/Authenticate.phpnu [        PK       x\Gk    ,            I Http/Middleware/AdminAuthorizeMiddleware.phpnu [        PK       x\v&N  N               Http/Kernel.phpnu [        PK       x\{fKV  V               Models/Payout.phpnu [        PK       x\[JZ                 Models/Kyc.phpnu [        PK       x\ }PZ
  
               Models/MaintenanceMode.phpnu [        PK       x\:}                 Models/SellPostOffer.phpnu [        PK       x\                 Models/OrderDetail.phpnu [        PK       x\	g  g               Models/CardService.phpnu [        PK       x\T                 Models/TopUp.phpnu [        PK       x\[                 Models/PayoutMethod.phpnu [        PK       x\}KA                 Models/SellPost.phpnu [        PK       x\bE  E               Models/BlogCategory.phpnu [        PK       x\[[ٗ                ] Models/UserKyc.phpnu [        PK       x\BXpJ  J               Models/UserLogin.phpnu [        PK       x\óU                5 Models/User.phpnu [        PK       x\6?  ?              4% Models/NotificationTemplate.phpnu [        PK       x\d7                  ' Models/Currency.phpnu [        PK       x\Fݨ(  (  "            ( Models/SupportTicketAttachment.phpnu [        PK       x\|b<m  m              T+ Models/NotificationSettings.phpnu [        PK       x\!  !              . Models/ManualSmsConfig.phpnu [        PK       x\4Qy  y              {/ Models/Gateway.phpnu [        PK       x\JPjX  X              65 Models/SmsControl.phpnu [        PK       x\                6 Models/Coupon.phpnu [        PK       x\< }                (: Models/Blog.phpnu [        PK       x\W8>                V< Models/Content.phpnu [        PK       x\J!                  &> Models/Subscriber.phpnu [        PK       x\                        ? Models/index.phpnu [        PK       x\U                \? Models/SupportTicket.phpnu [        PK       x\߯b                  C Models/Campaign.phpnu [        PK       x\r  r              D Models/Page.phpnu [        PK       x\~P.                }H Models/Transaction.phpnu [        PK       x\Dj  j  !            nN Models/SellPostCategoryDetail.phpnu [        PK       x\|                )P Models/SellPostChat.phpnu [        PK       x\
"[w  w              S Models/Role.phpnu [        PK       x\J                T Models/SellPostPayment.phpnu [        PK       x\Jt                W Models/TopUpService.phpnu [        PK       x\
W  W              /` Models/Language.phpnu [        PK       x\LTv  v              d Models/SupportTicketMessage.phpnu [        PK       x\/                g Models/ManageMenu.phpnu [        PK       x\p!                i Models/Order.phpnu [        PK       x\L~                  q Models/RazorpayContact.phpnu [        PK       x\G\  \              r Models/Category.phpnu [        PK       x\i                u Models/Code.phpnu [        PK       x\Gr                w Models/Deposit.phpnu [        PK       x\5J                 Models/Review.phpnu [        PK       x\3                O Models/ContentDetails.phpnu [        PK       x\o                e Models/InAppNotification.phpnu [        PK       x\$Y)  )              ^ Models/ActivityLog.phpnu [        PK       x\sh
  
              ͋ Models/Admin.phpnu [        PK       x\NS-`  `               Models/BlogDetails.phpnu [        PK       x\,s
@  @              2 Models/FileStorage.phpnu [        PK       x\.	  	               Models/Card.phpnu [        PK       x\2ln  n              ȣ Models/PageDetail.phpnu [        PK       x\$R
  
              { Models/SellPostCategory.phpnu [        PK       x\E|  |              Ы Models/FireBaseToken.phpnu [        PK       x\-,[  [               Models/BasicControl.phpnu [        PK       x\`                  6 Models/UserTracking.phpnu [        PK       x\@F\k  k              k Exports/TopUpServiceExport.phpnu [        PK       x\Wok  k              $ Exports/CodeExport.phpnu [        PK       x\<g  g              ռ Exports/CardServiceExport.phpnu [        PK       x\z|V  V               Jobs/UpdateChildCountJob.phpnu [        PK       x\n̩    "            + Jobs/UserNotificationTempletes.phpnu [        PK       x\K  K              & Jobs/UserTrackingJob.phpnu [        PK       x\                  Jobs/CodeSendBuyer.phpnu [        PK       x\`
  `
               Jobs/UserAllRecordDeleteJob.phpnu [        PK       x\Vd!  !  !             Jobs/UpdateReviewAndRatingJob.phpnu [        PK       x\-a[  [  !             Services/Payout/paystack/Card.phpnu [        PK       x\I.  .  %             Services/Payout/perfectmoney/Card.phpnu [        PK       x\                ! Services/Payout/paypal/Card.phpnu [        PK       x\s                 	 Services/Payout/binance/Card.phpnu [        PK       x\.  .  $            [ Services/Payout/flutterwave/Card.phpnu [        PK       x\O̎    !            * Services/Payout/razorpay/Card.phpnu [        PK       x\z%z:  :  !            @ Services/Payout/coinbase/Card.phpnu [        PK       x\I    %            {G Services/Gateway/cinetpay/Payment.phpnu [        PK       x\2U3(  (  -            U Services/Gateway/coinbasecommerce/Payment.phpnu [        PK       x\bO    #            <^ Services/Gateway/khalti/Payment.phpnu [        PK       x\D$    #            f Services/Gateway/skrill/Payment.phpnu [        PK       x\`    )            m Services/Gateway/authorizenet/Payment.phpnu [        PK       x\Ng.    "            9 Services/Gateway/paytm/Payment.phpnu [        PK       x\6n    (            q Services/Gateway/paytm/PaytmChecksum.phpnu [        PK       x\                 Р Services/Gateway/paytm/PayTM.phpnu [        PK       x\GHt#  #  %            8 Services/Gateway/voguepay/Payment.phpnu [        PK       x\EԯI  I  %             Services/Gateway/cashonex/Payment.phpnu [        PK       x\Ng  g  %            N Services/Gateway/paystack/Payment.phpnu [        PK       x\o
  
  $            
 Services/Gateway/swagger/Payment.phpnu [        PK       x\    )            < Services/Gateway/perfectmoney/Payment.phpnu [        PK       x\/  /  (             Services/Gateway/twocheckout/Payment.phpnu [        PK       x\Yo	  o	  $             Services/Gateway/monnify/Payment.phpnu [        PK       x\I
  I
  '            h  Services/Gateway/blockchain/Payment.phpnu [        PK       x\T♡    %             Services/Gateway/shkeeper/Payment.phpnu [        PK       x\#    #             Services/Gateway/paypal/Payment.phpnu [        PK       x\kN
  
  *             Services/Gateway/peachpayments/Payment.phpnu [        PK       x\X    &            + Services/Gateway/instamojo/Payment.phpnu [        PK       x\r  r  "            c2 Services/Gateway/bkash/Payment.phpnu [        PK       x\>     $            'E Services/Gateway/binance/Payment.phpnu [        PK       x\yL
  
  "            U Services/Gateway/mypay/Payment.phpnu [        PK       x\9	  	  +            a Services/Gateway/cashonexHosted/Payment.phpnu [        PK       x\_YA  A  %            [k Services/Gateway/midtrans/Payment.phpnu [        PK       x\9?  ?  %            w Services/Gateway/cashmaal/Payment.phpnu [        PK       x\	  	  &            } Services/Gateway/payumoney/Payment.phpnu [        PK       x\9pu  u  )            ڇ Services/Gateway/coinpayments/Payment.phpnu [        PK       x\Uj    3             Services/Gateway/coinpayments/CoinPaymentHosted.phpnu [        PK       x\Ճ    #            ϶ Services/Gateway/imepay/Payment.phpnu [        PK       x\LkR  R  (             Services/Gateway/flutterwave/Payment.phpnu [        PK       x\.5
  5
  &             Services/Gateway/freekassa/Payment.phpnu [        PK       x\yߗ#    $            1 Services/Gateway/konnect/Payment.phpnu [        PK       x\o߷    %            N Services/Gateway/eCitizen/Payment.phpnu [        PK       x\ն|    #             Services/Gateway/stripe/Payment.phpnu [        PK       x\,e    %              Services/Gateway/razorpay/Payment.phpnu [        PK       x\Ԛ    %            	 Services/Gateway/coingate/Payment.phpnu [        PK       x\~-x
  x
  #             Services/Gateway/payeer/Payment.phpnu [        PK       x\_u    (             Services/Gateway/nowpayments/Payment.phpnu [        PK       x\Zp  p  $            + Services/Gateway/fastpay/Payment.phpnu [        PK       x\ &
  
  (            9 Services/Gateway/mercadopago/Payment.phpnu [        PK       x\W    #            eD Services/Gateway/mollie/Payment.phpnu [        PK       x\    "            J Services/Gateway/nagad/Payment.phpnu [        PK       x\$  $  &            g Services/Gateway/toyyibpay/Payment.phpnu [        PK       x\^                v Services/BasicService.phpnu [        PK       x\:	  	  ,            5 Services/Translate/AzureTranslateService.phpnu [        PK       x\    +            b Services/Translate/BaseTranslateService.phpnu [        PK       x\^    -             Services/Translate/GoogleTranslateService.phpnu [        PK       x\d赈T  T               Services/BasicCurl.phpnu [        PK       x\                ( Services/SMS/PlivoService.phpnu [        PK       x\Pڤ                 Services/SMS/TwilioService.phpnu [        PK       x\x6s  s              z Services/SMS/VonageService.phpnu [        PK       x\mH  H              ; Services/SMS/BaseSmsService.phpnu [        PK       x\e}G)  )              һ Services/SMS/InfobipService.phpnu [        PK       x\		  	               J Services/LocalizationService.phpnu [        PK       x\zmD  D  !            : Services/CurrencyLayerService.phpnu [        PK       x\/o  o  *             Services/Google/GoogleRecaptchaService.phpnu [        PK       x\                         Imports/index.phpnu [        PK       x\Qx3                 Imports/TopUpServiceImport.phpnu [        PK       x\Vvx                 Imports/CodeImport.phpnu [        PK       x\t&w  w              , Imports/CardServiceImport.phpnu [        PK       x\q	q  q               Traits/ContentDelete.phpnu [        PK       x\$  $               Traits/MakeOrder.phpnu [        PK       x\I_0  0               Traits/Bkash.phpnu [        PK       x\&                  j Traits/Frontend.phpnu [        PK       x\2!eQ'  '  !            b8 Traits/PaymentValidationCheck.phpnu [        PK       x\n5
  
              K Traits/Upload.phpnu [        PK       x\e#K)  )              V Traits/ApiPayment.phpnu [        PK       x\G                 Traits/Nagad.phpnu [        PK       x\e'{l  l              ̏ Traits/SellPostTrait.phpnu [        PK       x\/y2w  w               Traits/Rating.phpnu [        PK       x\|A  A              8 Traits/ApiValidation.phpnu [        PK       x\/2  2               Traits/Translatable.phpnu [        PK       x\                : Traits/ToyyibPay.phpnu [        PK       x\/?^  ^               Traits/Notify.phpnu [        PK       x\.                
 Traits/Sample.phpnu [        PK       x\0F                 Traits/CurrencyRateUpdate.phpnu [        PK       x\3dB                 Mail/TestMail.phpnu [        PK       x\UR  R               Mail/SendMail.phpnu [        PK       x\M?r                 Mail/sendTestMail.phpnu [        PK       x\8tnt  t  "             Providers/EventServiceProvider.phpnu [        PK       x\O'  '  "            # Providers/RouteServiceProvider.phpnu [        PK       x\Ɩ    !            * Providers/AuthServiceProvider.phpnu [        PK       x\                        ^, Providers/index.phpnu [        PK       x\ԇ=                 , Providers/AppServiceProvider.phpnu [        PK       x\RPQ8g  g  &            ? Providers/BroadcastServiceProvider.phpnu [        PK       x\!  !              JA Helpers/GoogleAuthenticator.phpnu [        PK       x\`                Y Helpers/UserSystemInfo.phpnu [        PK       x\q                p Helpers/helpers.phpnu [        PK       9S\.o                Http/Controllers/Admin/Admin.zipnu [        PK       :S\A               Http/Controllers/AAdmin.zipnu [        PK       :S\cJj  j  *            C Http/Controllers/AAdmin/LogoController.phpnu [        PK       :S\fH2  H2  .             Http/Controllers/AAdmin/LanguageController.phpnu [        PK       :S\F6  6  )             Http/Controllers/AAdmin/KycController.phpnu [        PK       :S\z  z  3            0 Http/Controllers/AAdmin/PaymentMethodController.phpnu [        PK       :S\2-  -  3            J Http/Controllers/AAdmin/SupportTicketController.phpnu [        PK       :S\R8_2  2  4            x Http/Controllers/AAdmin/RolePermissionController.phpnu [        PK       :S\oN,)  )  -            : Http/Controllers/AAdmin/ContentController.phpnu [        PK       :S\g  g  -            * Http/Controllers/AAdmin/StorageController.phpnu [        PK       :S\x#*  #*  .             Http/Controllers/AAdmin/CurrencyController.phpnu [        PK       :S\uCA  CA  *            o Http/Controllers/AAdmin/PageController.phpnu [        PK       :S\k[=    0            U Http/Controllers/AAdmin/ManageMenuController.phpnu [        PK       :S\c     5            pp Http/Controllers/AAdmin/MaintenanceModeController.phpnu [        PK       :S\Y1  1  /            x Http/Controllers/AAdmin/PayoutLogController.phpnu [        PK       :S\>:  :  /            
 Http/Controllers/AAdmin/DashboardController.phpnu [        PK       :S\db[H+  H+  3             Http/Controllers/AAdmin/ManualGatewayController.phpnu [        PK       :S\N    2             Http/Controllers/AAdmin/BlogCategoryController.phpnu [        PK       :S\pUk<  k<  :             Http/Controllers/AAdmin/NotificationTemplateController.phpnu [        PK       :S\qγn    ,            \ Http/Controllers/AAdmin/PluginController.phpnu [        PK       :S\ۖQ  Q  2            x Http/Controllers/AAdmin/BasicControlController.phpnu [        PK       :S\t0XM  M  /            m Http/Controllers/AAdmin/SubscribeController.phpnu [        PK       :S\AA      9             Http/Controllers/AAdmin/AdminProfileSettingController.phpnu [        PK       :S\PM  M  0             Http/Controllers/AAdmin/PaymentLogController.phpnu [        PK       :S\>,  ,  *             Http/Controllers/AAdmin/BlogController.phpnu [        PK       :S\J  J  4            0 Http/Controllers/AAdmin/TransactionLogController.phpnu [        PK       :S\KI	  	  9            B Http/Controllers/AAdmin/TranslateAPISettingController.phpnu [        PK       :S\O5  5  .            M Http/Controllers/AAdmin/TempleteController.phpnu [        PK       :S\Ol[n  n  2            P Http/Controllers/AAdmin/PusherConfigController.phpnu [        PK       :S\]    3            sW Http/Controllers/AAdmin/Module/CouponController.phpnu [        PK       :S\G!-H  H  1            t Http/Controllers/AAdmin/Module/CardController.phpnu [        PK       :S\yk5  5  9             Http/Controllers/AAdmin/Module/TopUpServiceController.phpnu [        PK       :S\Wz	D8  D8  8            \ Http/Controllers/AAdmin/Module/CardServiceController.phpnu [        PK       :S\Ͼ)  )  8            - Http/Controllers/AAdmin/Module/SellSummaryController.phpnu [        PK       :S\F  F  2            .W Http/Controllers/AAdmin/Module/TopUpController.phpnu [        PK       :S\b9z<  z<  6             Http/Controllers/AAdmin/Module/CardOrderController.phpnu [        PK       :S\@5]    5             Http/Controllers/AAdmin/Module/CampaignController.phpnu [        PK       :S\И"  "  3             Http/Controllers/AAdmin/Module/ReviewController.phpnu [        PK       :S\?"  "  <            r Http/Controllers/AAdmin/Module/CardServiceCodeController.phpnu [        PK       :S\Ǝ5  5  7            4 Http/Controllers/AAdmin/Module/TopUpOrderController.phpnu [        PK       :S\W,'  '  5            j Http/Controllers/AAdmin/Module/CategoryController.phpnu [        PK       :S\SY6g  g  =            Β Http/Controllers/AAdmin/Module/SellPostCategoryController.phpnu [        PK       :S\Fև    6             Http/Controllers/AAdmin/GoogleApiSettingController.phpnu [        PK       :S\X=% =% +               Http/Controllers/AAdmin/UsersController.phpnu [        PK       :S\Yʎ
  
  /            T&! Http/Controllers/AAdmin/SmsConfigController.phpnu [        PK       :S\^r    1            ?! Http/Controllers/AAdmin/EmailConfigController.phpnu [        PK       :S\IZgg  g  6            U! Http/Controllers/AAdmin/SellPostCategoryController.phpnu [        PK       :S\7<  <  2            ! Http/Controllers/AAdmin/PayoutMethodController.phpnu [        PK       :S\b    2            8! Http/Controllers/AAdmin/CookiePolicyController.phpnu [        PK       :S\@Wݺn  n  4            C! Http/Controllers/AAdmin/FirebaseConfigController.phpnu [        PK       :S\hU)    :            " Http/Controllers/AAdmin/Auth/ConfirmPasswordController.phpnu [        PK       :S\    9            " Http/Controllers/AAdmin/Auth/ForgotPasswordController.phpnu [        PK       :S\+q  q  7            " Http/Controllers/AAdmin/Auth/VerificationController.phpnu [        PK       :S\TS  S  0            #" Http/Controllers/AAdmin/Auth/LoginController.phpnu [        PK       :S\V9[O  O  8            c7" Http/Controllers/AAdmin/Auth/ResetPasswordController.phpnu [        PK       :S\"t^  ^  /            C" Http/Controllers/AAdmin/SocialiteController.phpnu [        PK    jj  X"   