<?php

namespace Dashboard\Controllers\Ajax;

use Curl\Curl;
use Dashboard\Core\Controller;
use Dashboard\Libs\DiscordWebhook;
use Dashboard\Libs\Rcon\Rcon;
use Dashboard\Libs\Websend;
use Dashboard\Libs\Websender;
use PDO;
use PDOException;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class CheckController extends Controller
{
    public function __construct()
    {
        $_POST = json_decode(file_get_contents('php://input'),true);
    }

    public function console()
    {
        abort_perm('MANAGE_SERVERS');

        $validate = validate([
            'serverIP' => 'required',
            'consoleID' => 'required',
            'consolePort' => 'required_if:consoleID,1,2,3',
            'consolePassword' => 'required_if:consoleID,1,2,3',
            'consoleToken' => 'required_if:consoleID,4',
        ], false);

        if (!empty($validate))
          response()->json([
            'status' => false,
            'message' => $validate[0]
          ]);

        $consoleIP = input("serverIP");
        $consoleType = input("consoleID");
        $consolePort = input("consolePort");
        $consoleToken = input("consoleToken");
        $consolePassword = input("consolePassword");

        if ($consoleType == 4) {
          $curl = new Curl();
          $curl->setHeader('Content-Type', 'application/json');
	        $curl->setHeader('Accept', 'application/json');
          $curl->post("https://connect-api.leaderos.net/api/socket/ping-test", [
            "apiKey"   => settings('apiKey'),
            "token"    => $consoleToken,
          ]);

          if (isset($curl->response->status)) {
            if ($curl->response->status) {
              response()->json([
                'status' => true
              ]);
            }

            response()->json([
              'status' => false,
              'message' => $curl->response->error
            ]);
          }

          response()->json([
            'status' => false,
            'message' => 'Request error'
          ]);
        } else {
	        if ($consoleType == 1) {
		        $console = new Websend($consoleIP, $consolePort);
		        $console->password = $consolePassword;
		        
		        try {
			        $console->connect();
			        $console->sendCommand("say Test!");
			        $console->disconnect();
			        
			        response()->json([
				        'status' => true
			        ]);
		        } catch (\Exception $e) {
			        response()->json([
				        'status' => false,
				        'message' => $e->getMessage()
			        ]);
		        }
	        }
	        else if ($consoleType == 2) {
		        $console = new Rcon($consoleIP, $consolePort, $consolePassword);
						
						if ($console->checkConnection()) {
							response()->json([
								'status' => true
							]);
						} else {
							response()->json([
								'status' => false,
								'message' => 'Failed to connect to the RCON server.'
							]);
						}
	        }
	        else if ($consoleType == 3) {
		        $console = new Websender($consoleIP, $consolePassword, $consolePort);
						
						try {
							$console->connect();
							$console->sendCommand("say Test!");
							$console->disconnect();
							
							response()->json([
								'status' => true
							]);
						} catch (\Exception $e) {
							response()->json([
								'status' => false,
								'message' => $e->getMessage()
							]);
						}
	        }
        }
    }

    public function mysql()
    {
        abort_perm('MANAGE_LEADERBOARDS');

        $validate = validate([
            'mysqlServer' => 'required',
            'mysqlPort' => 'required',
            'mysqlUsername' => 'required',
            'mysqlPassword' => 'required',
            'mysqlDatabase' => 'required',
        ], false);

        if (!empty($validate))
            response()->json([
                'status' => false,
                'message' => $validate[0]
            ]);

        try {
            $dbConnectionTest = new PDO("mysql:host=" . input("mysqlServer") . "; port=" . input("mysqlPort") . "; dbname=" . input("mysqlDatabase") . "; charset=utf8", input("mysqlUsername"), input("mysqlPassword"));
            $dbConnectionTest = null;

            response()->json([
              'status' => true
            ]);
        } catch (PDOException $e) {
            response()->json([
              'status' => false,
              'message' => $e->getMessage()
            ]);
        }
    }

    public function smtp()
    {
        abort_perm('MANAGE_SETTINGS');

        $validate = validate([
            'smtpServer' => 'required',
            'smtpPort' => 'required',
            'smtpSecure' => 'required',
            'smtpUsername' => 'required',
            'smtpPassword' => 'required',
        ], false);

        if (!empty($validate))
          response()->json([
            'status' => false,
            'message' => $validate[0]
          ]);

        $phpMailer = new PHPMailer(true);
        try {
            $phpMailer->IsSMTP();
            $phpMailer->SMTPAuth = true;
            $phpMailer->Host = input("smtpServer");
            $phpMailer->Port = input("smtpPort");
            $phpMailer->SMTPSecure = ((input("smtpSecure") == 1) ? PHPMailer::ENCRYPTION_SMTPS : ((input("smtpSecure") == 2) ? PHPMailer::ENCRYPTION_STARTTLS : PHPMailer::ENCRYPTION_SMTPS));
            $phpMailer->Username = input("smtpUsername");
            $phpMailer->Password = input("smtpPassword");
            $phpMailer->SetFrom(input('smtpSenderEmail'), settings("serverName"));
            $phpMailer->AddAddress(auth()->user()->email(), auth()->user()->displayName());
            $phpMailer->isHTML(true);
            $phpMailer->CharSet = 'UTF-8';
            $phpMailer->Subject = "Test Email";
            $phpMailer->Body = "This is an SMTP connection check test.";
            $phpMailer->send();
            response()->json([
                'status' => true
            ]);
        } catch (Exception $e) {
            response()->json([
                'status' => false,
                'message' => strip_tags($e->errorMessage())
            ]);
        }
    }

    public function webhook()
    {
			$variables = [];
			
			switch (input("event")) {
				case 'forum.thread.posted':
					$variables = [
						'username' => auth()->user()->displayName(),
						'title' => 'Test Thread',
						'url' => websiteUrl() . "/forum/threads/1/test-thread"
					];
					break;
				case 'store.purchase.credit':
					$variables = [
						'username' => auth()->user()->displayName(),
						'credit' => '10.00',
						'currency' => 'USD'
					];
					break;
				case 'store.purchase.product':
					$variables = [
						'username' => auth()->user()->displayName(),
						'product' => 'Test Product',
						'category' => 'Test Category',
						'quantity' => '3',
						'price' => '10.00',
						'currency' => 'USD'
					];
					break;
				case 'support.ticket.opened':
					$variables = [
						'username' => auth()->user()->displayName(),
						'category' => 'Test Category',
						'title' => 'Test Ticket',
						'message' => 'Test Message',
						'dashboard_url' => websiteUrl() . "/dashboard/support/tickets/1"
					];
					break;
				case 'support.ticket.answered':
					$variables = [
						'username' => auth()->user()->displayName(),
						'category' => 'Test Category',
						'title' => 'Test Ticket',
						'message' => 'Test Message',
						'dashboard_url' => websiteUrl() . "/dashboard/support/tickets/1"
					];
					break;
				case 'support.ticket.replied':
					$variables = [
						'username' => auth()->user()->displayName(),
						'category' => 'Test Category',
						'title' => 'Test Ticket',
						'message' => 'Test Message',
						'dashboard_url' => websiteUrl('/dashboard/support/tickets/1')
					];
					break;
				case 'support.ticket.closed':
					$variables = [
						'username' => auth()->user()->displayName(),
						'category' => 'Test Category',
						'title' => 'Test Ticket',
						'dashboard_url' => websiteUrl('/dashboard/support/tickets/1')
					];
					break;
				case 'blog.post.published':
					$variables = [
						'username' => auth()->user()->displayName(),
						'title' => 'Test Post',
						'content' => 'Test Content',
						'category' => 'Test Category',
						'thumbnail' => 'https://placehold.co/600x400/EEE/31343.png',
						'url' => websiteUrl() . "/posts/1/test-post"
					];
					break;
				case 'blog.post.commented':
					$variables = [
						'username' => auth()->user()->displayName(),
						'title' => 'Test Post',
						'comment' => 'Test Comment',
						'message' => 'Test Comment',
						'url' => websiteUrl() . "/posts/1/test",
						'dashboard_url' => websiteUrl() . "/dashboard/blog/comments/1/edit"
					];
					break;
				case 'wheel.won':
					$variables = [
						'username' => auth()->user()->displayName(),
						'name' => "Test Wheel of Fortune",
						'award' => "Test Award"
					];
					break;
				case 'application.submitted':
					$variables = [
						'username' => auth()->user()->displayName(),
						'form_title' => "Test Application",
						'dashboard_url' => websiteUrl() . "/dashboard/applications/1"
					];
					break;
				case 'changelog.published':
					$variables = [
						'username' => auth()->user()->displayName(),
						'title' => 'Test Changelog',
						'url' => websiteUrl() . "/changelog"
					];
					break;
				default:
			}
    
	    try {
		    $discordWebhook = new DiscordWebhook(
			    input("event"),
			    input("url"),
			    input("botName"),
			    input("botAvatar"),
			    input("data"),
			    $variables
		    );
		    $response = $discordWebhook->send();
				
				if ($response === 204) {
					response()->json([
						'status' => true
					]);
				} else {
					response()->json([
						'status' => false
					]);
				}
	    } catch (\Exception $ex) {
		    response()->json([
			    'status' => false,
			    'message' => $ex->getMessage()
		    ]);
	    }
    }
}