<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models;
use Session;

class ClickInfrastructureController extends Controller
{
    
    public function servers(){
        // dd(session('current_user'));
        // die;
    	$servers = Models\ClickServer::with('direct_connections_info', 'credentials_info')->get();
    	$data = [
    		'page_title' => 'Servers', 
    		'servers' => $servers
    	];
    	return view('infrastructure.index', $data);

    }
    public function domains(){
    	
    }
    public function create_direct($id)
    {

        $server = Models\ClickServer::find($id);
        $data = [
            'page_title' => 'Servers',
            'server' => $server,
            'connection_types' => ['vpn' => 'VPN', 'fqdn' => 'FQDN' ]
        ];
        return view('infrastructure.create_direct_connection', $data);
    }
    public function store_direct(Request $request){
        // dd($request->all());

        $request->validate([
            'direct_partner' => 'required',
            'server_id' => 'required',
            'connection_type' => 'required',
            'port' => 'required_with:main_ip_address,domain_name',
            'main_ip_address' => 'sometimes|nullable|ip',
            'private_ip_address' => 'sometimes|nullable|ip',
            'domain_name' => 'required_if:connection_type,fqdn|nullable|regex:/^([a-zA-Z0-9][a-zA-Z0-9-_]*\.)*[a-zA-Z0-9]*[a-zA-Z0-9-_]*[[a-zA-Z0-9]+$/',
            'vpn_peer_ip' => 'required_if:connection_type,vpn|nullable|ip',
            'connection_form' => 'sometimes|nullable|max:2000|mimes:doc,docx,xlx,xlsx,png,jpg,jpeg,bmp,pdf',
        ]);
        // dd($request->all());
        if ($request->main_ip_address == null && $request->domain_name == null ) {
            return redirect()->back()->withInput()->withErrors(['You need either an IP address or a Domain name']);
        }
        $direct_arr = $request->except('_token');
        $direct_arr['last_modified_by'] = session('current_user.id');
        
        if ($request->hasFile('connection_form')) {
           if ($request->file('connection_form')->isValid()) {
               $filename = "connection_document_" . time() . "." . $request->connection_form->extension();
                $request->connection_form->storeAs('connection_files', $filename, 'public');
                $direct_arr['connection_document'] = $filename;
            }
        }
        // dd($direct_arr);

        $result = Models\DirectConnection::create($direct_arr);
        Session::flash('success_message', 'Direct connection successfully added');
        return redirect(url('infrastructure/servers'));
    }

    public function edit_direct($id)
    {

        $direct_connection = Models\DirectConnection::find($id);
        // dump($direct_connection);
        // TNM_CLICKB_NOSIR_NEW_SMSC
        $server = Models\ClickServer::find($direct_connection->server_id);
        // dd($server);
        $data = [
            'page_title' => 'Servers',
            'server' => $server,
            'direct_connection' => $direct_connection,
            'connection_types' => ['vpn' => 'VPN', 'fqdn' => 'FQDN' ]
        ];
        return view('infrastructure.edit_direct_connection', $data);
    }
    public function create()
    {
        $data = [
            'page_title' => 'Add Server',
        ];
        return view('infrastructure.create', $data);        
    }
    public function update_direct(Request $request){

        $request->validate([
            'direct_partner' => 'required',
            'server_id' => 'required',
            'connection_type' => 'required',
            'port' => 'required_with:main_ip_address,domain_name',
            'main_ip_address' => 'sometimes|nullable|ip',
            'private_ip_address' => 'sometimes|nullable|ip',
            'domain_name' => 'sometimes|nullable|regex:/^([a-zA-Z0-9][a-zA-Z0-9-_]*\.)*[a-zA-Z0-9]*[a-zA-Z0-9-_]*[[a-zA-Z0-9]+$/',
            'vpn_peer_ip' => 'required_if:connection_type,vpn|nullable|ip',
            'connection_form' => 'sometimes|nullable|max:2000|mimes:doc,docx,xlx,xlsx,png,jpg,jpeg,bmp',
        ]);
        if ($request->direct_id == null) {
            return redirect()->back()->withInput()->withErrors(['Your request could not be handled at this time. Try again!']);
        } 
        $direct_connection = Models\DirectConnection::find($request->direct_id);

        if ($request->main_ip_address == null && $request->domain_name == null ) {
            return redirect()->back()->withInput()->withErrors(['You need either an IP address or a Domain name']);
        }
        $direct_arr = $request->except('_token');
        $direct_arr['last_modified_by'] = session('current_user.id');
        // dd($direct_arr);

        if ($request->hasFile('connection_form')) {
           if ($request->file('connection_form')->isValid()) {
               $filename = "connection_document_" . time() . "." . $request->connection_form->extension();
                $request->connection_form->storeAs('connection_files', $filename, 'public');
                $direct_arr['connection_document'] = $filename;
            }
        }

        $result = $direct_connection->update($direct_arr);
        Session::flash('success_message', 'Direct connection successfully updated');
        return redirect(url('infrastructure/servers'));
    }
    public function server_list(){

        //$servers = Models\ClickServer::with('credentials_info')->get();
        // dd($servers[0]->credentials_info->where('username', 'root')->first());
        $data = [
            'page_title' => 'Servers', 
        ];
        return view('infrastructure.server_list', $data);

    }
    public function getServerListJson(Request $request)
    {
        //$this->log_query();
        $server_arr = \DB::table('click_servers')
            ->join('auth_users', 'auth_users.id', '=', 'click_servers.last_modified_by_id')
            ->select('click_servers.id','click_servers.server_id', 'auth_users.name AS username', 'click_servers.friendly_name','click_servers.status', 'click_servers.public_ip_address', 'click_servers.private_ip_address', 'click_servers.main_use', 'click_servers.remarks', 'click_servers.updated_at')
            ->orderBy('click_servers.friendly_name', 'ASC')
            ->paginate(20);

        if($request->has('keyword')){
            $keyword = $request->keyword;
            $server_arr = \DB::table('click_servers')
            ->join('auth_users', 'auth_users.id', '=', 'click_servers.last_modified_by_id')
            ->select('click_servers.id', 'click_servers.server_id', 'auth_users.name AS username', 'click_servers.friendly_name', 'click_servers.status', 'click_servers.public_ip_address', 'click_servers.private_ip_address', 'click_servers.main_use', 'click_servers.remarks', 'click_servers.updated_at')
            ->whereRaw("click_servers.server_id LIKE '%$keyword%' OR click_servers.friendly_name LIKE '%$keyword%' OR click_servers.public_ip_address LIKE '%$keyword%' OR click_servers.private_ip_address LIKE '%$keyword%' OR auth_users.name LIKE '%$keyword%' OR click_servers.main_use LIKE '%$keyword%' OR click_servers.remarks LIKE '%$keyword%' OR click_servers.updated_at LIKE '%$keyword%' OR click_servers.updated_at LIKE '%$keyword%' OR click_servers.updated_at LIKE '%$keyword%' OR click_servers.status LIKE '%$keyword%' ")    
            ->orderBy('click_servers.friendly_name', 'ASC')
            ->paginate(15);
        }     
        return response()->json($server_arr);
    }
    public function edit_server($id)
    {
        $server = Models\ClickServer::find($id);
        //$credentials = Models\ServerCredential::where('username', 'root')->where('server_id', $server->id) ->first();
        // dd($server);
        $data = [
            'page_title' => 'Servers',
            'server' => $server,
            'status_arr' => ['Active' => 'Active', 'Inactive' => 'Inactive', 'Decommissioned' => 'Decommissioned']
        ];
        return view('infrastructure.edit_server', $data);
    }
    public function updateserver(Request $request){
        $request->validate([
            'friendly_name' => 'required',
            'server_id' => 'required',
            'public_ip_address' => 'sometimes|ip',
            'private_ip_address' => 'sometimes|nullable|ip',
            'main_use' => 'required',
            'remarks' => 'nullable',
            'status' => 'required',
            'server_number' => 'required',
        ]);
        $server = Models\ClickServer::findOrFail($request->server_id);
        $server_arr = $request->except('_token', 'server_id', 'server_number');
        $server_arr['last_modified_by_id'] = session('current_user.id');
        $server_arr['server_id'] = $request->server_number;
        //dd($server_arr);
        /*
        if ($request->password !== null) {
            // dd('foo bar');
            $credentials_arr = [
                'server_id' => $request->server_id,
                'username' => 'root',
                'password' => encrypt($request->password),
                'last_modified_by' => session('current_user.id')
            ];
            $retval = Models\ServerCredential::find($request->server_id);
            if ($retval) {
                $retval->update($credentials_arr);
            }
            else{
                $result = Models\ServerCredential::create($credentials_arr);
            }
        }
        */
        $result = $server->update($server_arr);
        Session::flash('success_message', 'Server Details successfully updated');
        return redirect(url('infrastructure/server-list'));
    }
    public function storeserver(Request $request){
        $request->validate([
            'friendly_name' => 'required',
            'server_number' => 'required',
            'public_ip_address' => 'sometimes|ip',
            'private_ip_address' => 'sometimes|nullable|ip',
            'main_use' => 'required',
            'remarks' => 'nullable',
            'server_number' => 'required',
        ]);
        $server_arr = $request->except('_token', 'server_id', 'server_number');
        $server_arr['last_modified_by_id'] = session('current_user.id');
        $server_arr['server_id'] = $request->server_number;
      
        
        $result = Models\ClickServer::create($server_arr);
        Session::flash('success_message', 'Server Details successfully added');
        return redirect(url('infrastructure/server-list'));
    }
    public function reveal_password($id){
        $server = Models\ClickServer::find($id);
        if ($server) {
            $response_arr = [
                'code' => 1,
                'password' => decrypt($server->root_password)
            ];
        }
        else{
            $response_arr = [
                'code' => 3,
                'msg' => 'not found'
            ];   
        }
        return response()->json($response_arr);
    }
}