<?php

namespace Dashboard\Controllers\Store;

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

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

    public function index()
    {
        if (isset($_GET["page"])) {
            if (!is_numeric($_GET["page"])) {
                $_GET["page"] = 1;
            }
            $page = intval(get("page"));
        } else {
            $page = 1;
        }

        $visiblePageCount = 5;
        $limit = 50;

        $chestLogs = db()->query("SELECT count(CH.id) FROM ChestsHistory CH INNER JOIN Accounts A ON CH.accountID = A.id INNER JOIN Chests C ON CH.chestID = C.id INNER JOIN Products P ON C.productID = P.id INNER JOIN ProductCategories PC ON P.categoryID = PC.id");
        $itemsCount = $chestLogs->fetchColumn();
        $pageCount = ceil($itemsCount / $limit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $limit - $limit;
        $chestLogs = db()->query("SELECT CH.*, A.username, A.realname, OA.realname as otherAccountUsername, P.id as productID, P.name as productName, PC.id as categoryID, PC.name as categoryName FROM ChestsHistory CH INNER JOIN Accounts A ON CH.accountID = A.id LEFT JOIN Accounts OA ON OA.id = CH.otherAccountID INNER JOIN Chests C ON CH.chestID = C.id INNER JOIN Products P ON C.productID = P.id INNER JOIN ProductCategories PC ON P.categoryID = PC.id ORDER BY CH.id DESC LIMIT $visibleItemsCount, $limit");

        if (isset($_GET["search"])) {
            if (get("search") != null) {
                $chestLogs = db()->prepare("SELECT CH.*, A.username, A.realname, P.id as productID, P.name as productName, PC.id as categoryID, PC.name as categoryName FROM ChestsHistory CH INNER JOIN Accounts A ON CH.accountID = A.id INNER JOIN Chests C ON CH.chestID = C.id INNER JOIN Products P ON C.productID = P.id INNER JOIN ProductCategories PC ON P.categoryID = PC.id WHERE (A.realname LIKE :search OR A.username LIKE :search OR P.name LIKE :search OR PC.name LIKE :search) ORDER BY CH.id DESC");
                $chestLogs->execute(array(
                    "search" => '%' . get("search") . '%'
                ));
            }
        }

        $chestLogs = $chestLogs->fetchAll(PDO::FETCH_ASSOC);

        return view('store.chest-logs.index', compact('chestLogs', 'page', 'visiblePageCount', 'pageCount'));
    }

    public function show($id)
    {
        $chestLog = db()->prepare("SELECT CH.*, A.username, A.realname, OA.realname as otherAccountUsername, P.name as productName, PC.id as categoryID, PC.name as categoryName FROM ChestsHistory CH INNER JOIN Accounts A ON CH.accountID = A.id LEFT JOIN Accounts OA ON OA.id = CH.otherAccountID INNER JOIN Chests C ON CH.chestID = C.id INNER JOIN Products P ON C.productID = P.id INNER JOIN ProductCategories PC ON P.categoryID = PC.id WHERE CH.id = ?");
        $chestLog->execute(array($id));
        $chestLog = $chestLog->fetch(PDO::FETCH_ASSOC);

        if (!$chestLog) return view('404');
	    
		    $chestProductVariableValues = db()->prepare("SELECT V.*, CPVV.value FROM ChestProductVariableValues CPVV INNER JOIN StoreVariables V ON V.id = CPVV.variableID  WHERE chestID = ?");
		    $chestProductVariableValues->execute([$chestLog["chestID"]]);
		    $chestLog["variables"] = $chestProductVariableValues->fetchAll(PDO::FETCH_ASSOC);

        global $categoryList;
        $chestLog = CategoryService::getCategoryList([$chestLog], array_column([$chestLog], "categoryID"))[0];

        $commandLogs = db()->prepare("SELECT CL.id, CL.command, S.name as serverName, P.name as productName, CL.status, CL.updatedAt FROM CommandLogs CL INNER JOIN ProductCommands PC ON PC.id = CL.commandID INNER JOIN Servers S ON S.id = PC.serverID INNER JOIN Products P ON P.id = PC.productID WHERE CL.dataType = ? AND CL.dataID = ?");
        $commandLogs->execute(array('chest', $chestLog["chestID"]));
	      $commandLogs = $commandLogs->fetchAll(PDO::FETCH_ASSOC);

        return view('store.chest-logs.show', compact('chestLog', 'commandLogs'));
    }

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