<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;
use Dashboard\Services\CommandService;
use PDO;

class CommandLogController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_STORE');
    }

    public function sendAll()
    {
      validate([
        'dataType' => 'required',
        'dataID' => 'required|numeric'
      ]);

      $dataType = input('dataType');
      $dataID = input('dataID');

      $servers = [];

      $commandLogs = db()->prepare("SELECT CL.id, CL.dataType, CL.command, PC.serverID FROM CommandLogs CL INNER JOIN ProductCommands PC ON PC.id = CL.commandID WHERE dataType = ? AND dataID = ? AND (status = 'error' OR (status = 'sending' AND updatedAt <= ?))");
	    $commandLogs->execute([$dataType, $dataID, date('Y-m-d H:i:s', strtotime('-1 minutes'))]);
	    $commandLogs = $commandLogs->fetchAll(PDO::FETCH_ASSOC);
			
      foreach ($commandLogs as $commandLog) {
        $servers[$commandLog["serverID"]][] = [
          'command' => $commandLog["command"],
          'logID' => $commandLog["id"]
        ];
      }
			
      foreach ($servers as $serverID => $commands) {
        $server = db()->prepare("SELECT * FROM Servers WHERE id = ?");
        $server->execute(array($serverID));
        $server = $server->fetch();

        if (!$server) continue;

        $consoleIP = $server["ip"];
        $consoleType = $server["consoleID"];
        $consolePort = $server["consolePort"];
        $consolePassword = $server["consolePassword"];
        $consoleToken = $server["consoleToken"];
	      
	      $updateCommandLogs = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ?, retry = retry + 1 WHERE id = ?");
	      foreach ($commands as $command) {
		      $updateCommandLogs->execute(['sending', datetime(), $command["logID"]]);
	      }
				
	      CommandService::sendCommand($consoleIP, $consolePort, $consolePassword, $consoleToken, $consoleType, $commands);
      }

      return back();
    }

    public function send($id)
    {
      $date = datetime();
      $dateLong = convertTime($date, 2, true);
      $dateShort = convertTime($date);

      $commandLog = db()->prepare("SELECT CL.id, CL.dataType, CL.dataID, CL.command, PC.serverID FROM CommandLogs CL INNER JOIN ProductCommands PC ON PC.id = CL.commandID WHERE CL.id = ? AND (status = 'error' OR (status = 'sending' AND updatedAt <= ?))");
      $commandLog->execute(array($id, date('Y-m-d H:i:s', strtotime('-1 minutes'))));
      $commandLog = $commandLog->fetch();

      if (!$commandLog) {
        response()->json([
          'status' => false,
          'message' => t__('An error occurred while sending the command.'),
        ]);
      }

      $server = db()->prepare("SELECT * FROM Servers WHERE id = ?");
      $server->execute(array($commandLog["serverID"]));
      $server = $server->fetch();

      if (!$server) {
        response()->json([
          'status' => false,
          'message' => t__('An error occurred while sending the command.'),
        ]);
      }

      $consoleIP = $server["ip"];
      $consoleType = $server["consoleID"];
      $consolePort = $server["consolePort"];
      $consolePassword = $server["consolePassword"];
      $consoleToken = $server["consoleToken"];
	    $commands = [
		    [
			    'command' => $commandLog["command"],
			    'logID' => $commandLog["id"]
		    ]
	    ];
	    
	    $updateCommandLogs = db()->prepare("UPDATE CommandLogs SET status = ?, updatedAt = ?, retry = retry + 1 WHERE id = ?");
	    $updateCommandLogs->execute(['sending', datetime(), $commandLog["id"]]);

      $sendCommand = CommandService::sendCommand($consoleIP, $consolePort, $consolePassword, $consoleToken, $consoleType, $commands);
			
      if ($sendCommand) {
        response()->json([
          'status' => $consoleType == 4 ? 'sending' : 'completed',
          'message' => $consoleType == 4 ? t__('Command send request received successfully!') : t__('Command has been sent successfully!'),
          'dateLong' => $dateLong,
          'dateShort' => $dateShort
        ]);
      }
			
      response()->json([
        'status' => 'error',
        'message' => t__('Could not connect to the server!'),
        'dateLong' => $dateLong,
        'dateShort' => $dateShort
      ]);
    }

    public function destroy($id)
    {
        $deleteCommandLog = db()->prepare("DELETE FROM CommandLogs WHERE id = ?");
		    $deleteCommandLog->execute(array($id));
			
        return back();
    }
}