<?php

namespace Dashboard\Controllers\Store;

use Dashboard\Core\Controller;
use PDO;

class CreatorCodeLogController 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;

        $creatorCodeLogs = db()->prepare("SELECT count(CH.orderID) FROM OrderCreatorCodes CH INNER JOIN Orders O ON O.id = CH.orderID INNER JOIN Accounts A ON O.accountID = A.id INNER JOIN CreatorCodes CC ON CH.codeID = CC.id WHERE O.status = ?");
				$creatorCodeLogs->execute([1]);
        $itemsCount = $creatorCodeLogs->fetchColumn();
        $pageCount = ceil($itemsCount / $limit);
        if ($page > $pageCount) {
            $page = 1;
        }
        $visibleItemsCount = $page * $limit - $limit;
        $creatorCodeLogs = db()->prepare("SELECT CH.*, O.accountID, A.username, A.realname, CC.code, O.creationDate FROM OrderCreatorCodes CH INNER JOIN Orders O ON O.id = CH.orderID INNER JOIN Accounts A ON O.accountID = A.id INNER JOIN CreatorCodes CC ON CH.codeID = CC.id WHERE O.status = ? ORDER BY CH.orderID DESC LIMIT $visibleItemsCount, $limit");
				$creatorCodeLogs->execute([1]);

        if (isset($_GET["search"])) {
            if (get("search") != null) {
                $creatorCodeLogs = db()->prepare("SELECT CH.*, O.accountID, A.username, A.realname, CC.code, O.creationDate FROM OrderCreatorCodes CH INNER JOIN Orders O ON O.id = CH.orderID INNER JOIN Accounts A ON O.accountID = A.id INNER JOIN CreatorCodes CC ON CH.codeID = CC.id WHERE O.status = :orderStatus AND (A.realname LIKE :search OR A.username LIKE :search) ORDER BY CH.orderID DESC");
                $creatorCodeLogs->execute(array(
										"orderStatus" => 1,
                    "search" => '%' . get("search") . '%'
                ));
            }
        }

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

        return view('store.creator-codes.logs', compact('creatorCodeLogs', 'page', 'visiblePageCount', 'pageCount'));
    }

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