<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\ClientEditLog;
use App\Models\SchedulePackageChange;
use App\Models\SubPackage;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use PhpParser\Node\Stmt\Return_;

class SchedulePackageChangeController extends Controller
{
    public function scheduleClientPackageChange(Request $request)
    {


        if (!auth()->user()->hasPermissionTo('schedule-package-change')) {
            Toastr::error("Sorry You don't authorized for this action");
           return redirect()->back();
        }

        if(!$request->schedule_date){
            Toastr::error("Please Select a date");
            return redirect()->back();
        }

        if(!$request->schedule_package_id){
            Toastr::error("Please Select a package");
            return redirect()->back();
        }


        DB::beginTransaction();
        try{

            $check_pending_package_change_schedule = SchedulePackageChange::where('client_id',$request->id)->where('status','!=','Complete')->get();

            if($check_pending_package_change_schedule->count() > 0){
                foreach($check_pending_package_change_schedule as $schedule){
                    $schedule->status = "Deleted";
                    $schedule->process_description = "New Schedule Add";
                    $schedule->save();

                }
            }


            $client = Client::with('pop')->find($request->id);

            $schedule_package_change = new SchedulePackageChange();
            $schedule_package_change->client_id = $request->id;
            $schedule_package_change->old_package_id = $client->package_id;
            if($client->pop->subreseller == 'yes'){
                $schedule_package_change->old_sub_package_id = $client->sub_package_id;
                $schedule_package_change->new_sub_package_id = $request->schedule_package_id;

                $sub_package = SubPackage::find($request->schedule_package_id);
                $schedule_package_change->new_package_id = $sub_package->package_id;

            }else{
                $schedule_package_change->new_package_id = $request->schedule_package_id;
            }

            $schedule_package_change->schedule_date = Carbon::parse($request->schedule_date)->format('Y-m-d');
            $schedule_package_change->schedule_by = auth()->user()->id;

            $schedule_package_change->save();

            // dd($schedule_package_change);
            DB::commit();
            Toastr::success("Package Change Schedule Successful");
            return redirect()->back();

        }catch(\Exception $e){
            Toastr::error("Package Change Schedule Not Successful");
            return redirect()->back();
        }


    }

    public function schedulePackageChangeList()
    {

        if (!auth()->user()->hasPermissionTo('schedule-package-change')) {
            Toastr::error("Sorry You don't authorized for this action");
           return redirect()->back();
        }
        $schedulePackageChangeList = SchedulePackageChange::with('client.pop','newSubPackage','newPackage','scheduleBy')->orderBy('created_at','desc')->get();

        $data = [
            'lists' => $schedulePackageChangeList
        ];
        return view('schedulPackageChange.list',$data);

    }

    public function schedulePackageChangeDestroy(Request $request)
    {
        $schedule_package_change =  SchedulePackageChange::find($request->id);
        $schedule_package_change->status = "Deleted";
        $schedule_package_change->process_description = "Schedule deleted by ". auth()->user()->name;
        $schedule_package_change->save();

        Toastr::success("Schedule deleted successful");
        return redirect()->back();
    }


    public static function changeSchedulePackageChange()
    {
        $today = Carbon::parse(now())->format('Y-m-d 00:00:00');
        $schedule_package_change_clients = SchedulePackageChange::where('schedule_date',$today)->where('status','Pending')->get();
        // dd($schedule_package_change_clients);
        if(checkAPI()){
            foreach($schedule_package_change_clients as $item){
                DB::beginTransaction();
                try{

                    $client = Client::with('pop')->find($item->client_id);
                    $old_client = Client::with('clientsinfo')->withTrashed()->find($client->id);
                    if($client->pop->subreseller == 'yes'){
                        $sub_package = SubPackage::find($item->new_sub_package_id);
                        $client->package_id = $sub_package->package_id;
                        $client->sub_package_id = $sub_package->id;
                        $client->save();
                    }else{
                        $client->package_id = $item->new_package_id;
                        $client->save();
                    }

                    $item->status = "Complete";
                    $item->save();
                    $new_data_client = Client::with('clientsinfo')->withTrashed()->find($client->id);

                    $client_update_log = new ClientEditLog();
                    $client_update_log->client_id = $client->id;
                    $client_update_log->user_id = $item->schedule_by;
                    $client_update_log->old_data = json_encode($old_client);
                    $client_update_log->new_data = json_encode($new_data_client);
                    $client_update_log->save();

                    DB::commit();

                }catch(\Exception $e){
                    DB::rollBack();
                }

            }
        }else{
            foreach($schedule_package_change_clients as $item){
                DB::beginTransaction();
                try{

                    $client = Client::with('pop')->find($item->client_id);
                    $old_client = Client::with('clientsinfo')->withTrashed()->find($client->id);
                    if($client->pop->subreseller == 'yes'){
                        $sub_package = SubPackage::find($item->new_sub_package_id);
                        $client->package_id = $sub_package->package_id;
                        $client->sub_package_id = $sub_package->id;
                        $client->save();

                        DB::table('radusergroup')
                            ->updateOrInsert(
                            [
                                'username' => $client->userid,
                                'groupname' => $sub_package->package_id
                            ],
                            [
                                'priority' => 1
                            ]
                        );
                    }else{
                        $client->package_id = $item->new_package_id;
                        $client->save();

                        DB::table('radusergroup')
                            ->updateOrInsert(
                            [
                                'username' => $client->userid,
                                'groupname' => $item->new_package_id
                            ],
                            [
                                'priority' => 1
                            ]
                        );
                    }

                    $item->status = "Complete";
                    $item->save();


                    $new_data_client = Client::with('clientsinfo')->withTrashed()->find($client->id);

                    $client_update_log = new ClientEditLog();
                    $client_update_log->client_id = $client->id;
                    $client_update_log->user_id = $item->schedule_by;
                    $client_update_log->old_data = json_encode($old_client);
                    $client_update_log->new_data = json_encode($new_data_client);
                    $client_update_log->save();

                    DB::commit();

                }catch(\Exception $e){
                    DB::rollBack();
                }

            }
        }

        exec('/usr/bin/sudo /etc/init.d/freeradius restart');

    }
}
