<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Apptitle;
use App\Models\Footertext;
use App\Models\Seosetting;
use App\Models\Pages;
use App\Models\Setting;
use Artisan;
use Jenssegers\Agent\Agent;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\EmployeeActivity;
use Illuminate\Support\Facades\Auth;

class MaintanancemodeController extends Controller
{


    public function store(Request $request){

        if($request->input('maintenancemode') == 'off'){

            $data['MAINTENANCE_MODE']  =  $request->maintenancemode;
            $data['MAINTENANCE_MODE_VALUE']  =  null;
            $this->updateSettings($data);

            Artisan::call('up');

            return response()->json(['success' => 'Updated Successfully']);

        }
        if($request->input('maintenancemode') == 'on'){

            $data['MAINTENANCE_MODE']  =  $request->maintenancemode;
            $data['MAINTENANCE_MODE_VALUE']  =  $request->input('maintenancemode_value');
            $this->updateSettings($data);

            $geolocation = GeoIP::getLocation(request()->getClientIp());
            $agent = new Agent();
            $activity = new EmployeeActivity();
            $activity->user_id = Auth::user()->id;
            $activity->activity_type = 'Changed Maintenance_Mode settings';
            $activity->ip_address = $geolocation->ip;
            $activity->browser = $agent->browser();
            $activity->device = $agent->device();
            $activity->save();

            Artisan::call('down --secret="'.setting('MAINTENANCE_MODE_VALUE').'" ');

            return response()->json(['success' => 'Updated Successfully']);

        }
        
    }

    /**
     *  Settings Save/Update.
     *
     * @return \Illuminate\Http\Response
     */
    private function updateSettings($data)
    {
        foreach($data as $key => $val){
        	$setting = Setting::where('key', $key);
        	if( $setting->exists() )
        	$setting->first()->update(['value' => $val]);
        }

    }
}
