<?php

namespace Dashboard\Controllers\Support;

use Dashboard\Core\Controller;
use PDO;

class CategoryController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_SUPPORT');
    }

    public function index()
    {
        $categories = db()->query("SELECT * FROM SupportCategories ORDER BY id DESC");
        $categories = $categories->fetchAll();
        return view('support.categories.index', compact('categories'));
    }

    public function create()
    {
		    $permissions = db()->query("SELECT * FROM SupportCategoryPermissions");
		    $permissions = $permissions->fetchAll();
				
				$roles = db()->query("SELECT * FROM Roles ORDER BY priority DESC");
				$roles = $roles->fetchAll();
				$roles = array_map(function ($role) {
					$rolePermissions = db()->prepare("SELECT * FROM RolePermissions RP INNER JOIN Permissions P ON P.id = RP.permissionID WHERE RP.roleID = ?");
					$rolePermissions->execute(array($role["id"]));
					$rolePermissions = $rolePermissions->fetchAll(PDO::FETCH_ASSOC);
					$rolePermissions = array_column($rolePermissions, "name");
					
					// Remove roles that don't have the required permissions
					if (
						!in_array("SUPER_ADMIN", $rolePermissions) &&
						!in_array("MANAGE_SUPPORT", $rolePermissions) &&
						!in_array("MANAGE_SUPPORT_TICKETS", $rolePermissions)
					) {
						return null;
					}
					
					// If the role has MANAGE_SUPPORT or SUPER_ADMIN permissions, it's an admin role for the support category.
					$role["isAdmin"] = in_array("SUPER_ADMIN", $rolePermissions) || in_array("MANAGE_SUPPORT", $rolePermissions);
					
					return $role;
				}, $roles);
				$roles = array_filter($roles);
				
        return view('support.categories.create', compact('permissions', 'roles'));
    }

    public function store()
    {
        validate([
            'name' => 'required',
        ]);

        $insertSupportCategories = db()->prepare("INSERT INTO SupportCategories (name) VALUES (?)");
        $insertSupportCategories->execute(array(input("name")));

        $categoryID = db()->lastInsertId();
	    
		    foreach ($_POST as $key => $value) {
			    if (substr($key, 0, 11) == "permission_") {
				    $roleAndPerm = explode("_", substr($key, 11));
				    $roleID = $roleAndPerm[0];
				    $permissionID = $roleAndPerm[1];
				    if (input($key) == 1) {
					    $insertSupportCategoryRolePermissions = db()->prepare("INSERT INTO SupportCategoryRolePermissions (categoryID, roleID, permissionID) VALUES (?, ?, ?)");
					    $insertSupportCategoryRolePermissions->execute(array($categoryID, $roleID, $permissionID));
				    }
			    }
		    }
				
        foreach ($_POST["supportField"] as $key => $value) {
            if ($_POST["supportField"][$key] == '')
                continue;
            $_POST["supportField"][$key] = strip_tags($_POST["supportField"][$key]);
            $_POST["supportFieldType"][$key] = strip_tags($_POST["supportFieldType"][$key]);
            $_POST["supportFieldVariables"][$key] = ($_POST["supportFieldVariables"][$key] != null) ? strip_tags($_POST["supportFieldVariables"][$key]) : '-';
            $insertCustomSupportFields = db()->prepare("INSERT INTO CustomSupportFields (categoryID, field, type, variables) VALUES (?, ?, ?, ?)");
            $insertCustomSupportFields->execute(array($categoryID, $_POST["supportField"][$key], $_POST["supportFieldType"][$key], $_POST["supportFieldVariables"][$key]));
        }

        return back()->flash("success", t__('Category has been added successfully!'));
    }

    public function edit($id)
    {
        $category = db()->prepare("SELECT * FROM SupportCategories WHERE id = ?");
        $category->execute(array($id));
        $category = $category->fetch();

        if (!$category) return view('404');
	    
		    $availablePermissions = db()->prepare("SELECT * FROM SupportCategoryRolePermissions WHERE categoryID = ?");
		    $availablePermissions->execute(array($category["id"]));
		    $availablePermissions = $availablePermissions->fetchAll();
		    
		    $permissions = db()->query("SELECT * FROM SupportCategoryPermissions");
		    $permissions = array_map(function ($permission) use ($availablePermissions) {
			    $permission["roles"] = [];
			    foreach ($availablePermissions as $availablePermission) {
				    if ($availablePermission["permissionID"] == $permission["id"]) {
					    $permission["roles"][] = $availablePermission["roleID"];
				    }
			    }
			    return $permission;
		    }, $permissions->fetchAll());
	    
		    $roles = db()->query("SELECT * FROM Roles ORDER BY priority DESC");
		    $roles = $roles->fetchAll();
		    $roles = array_map(function ($role) {
			    $rolePermissions = db()->prepare("SELECT * FROM RolePermissions RP INNER JOIN Permissions P ON P.id = RP.permissionID WHERE RP.roleID = ?");
			    $rolePermissions->execute(array($role["id"]));
			    $rolePermissions = $rolePermissions->fetchAll(PDO::FETCH_ASSOC);
			    $rolePermissions = array_column($rolePermissions, "name");
			    
			    // Remove roles that don't have the required permissions
			    if (
				    !in_array("SUPER_ADMIN", $rolePermissions) &&
				    !in_array("MANAGE_SUPPORT", $rolePermissions) &&
				    !in_array("MANAGE_SUPPORT_TICKETS", $rolePermissions)
			    ) {
				    return null;
			    }
			    
			    // If the role has MANAGE_SUPPORT or SUPER_ADMIN permissions, it's an admin role for the support category.
			    $role["isAdmin"] = in_array("SUPER_ADMIN", $rolePermissions) || in_array("MANAGE_SUPPORT", $rolePermissions);
			    
			    return $role;
		    }, $roles);
		    $roles = array_filter($roles);

        $customFields = db()->prepare("SELECT * FROM CustomSupportFields WHERE categoryID = ? AND isEnabled = '1'");
        $customFields->execute(array($id));
        $category["customFields"] = array_map(function ($customField) {
            return [
                "field" => $customField["field"],
                "type" => $customField["type"],
                "variables" => $customField["variables"],
            ];
        }, $customFields->fetchAll(PDO::FETCH_ASSOC));

        return view('support.categories.edit', compact('category', 'permissions', 'roles'));
    }

    public function update($id)
    {
        validate([
            'name' => 'required',
        ]);

        $supportCategory = db()->prepare("SELECT * FROM SupportCategories WHERE id = ?");
        $supportCategory->execute(array($id));
        $readSupportCategory = $supportCategory->fetch();

        $updateSupportCategories = db()->prepare("UPDATE SupportCategories SET name = ? WHERE id = ?");
        $updateSupportCategories->execute(array(input("name"), $id));

        $categoryID = $readSupportCategory["id"];
        $disableOldQuestions = db()->prepare("UPDATE CustomSupportFields SET isEnabled = ? WHERE categoryID = ?");
        $disableOldQuestions->execute(array(0, $categoryID));
        foreach ($_POST["supportField"] as $key => $value) {
            if ($_POST["supportField"][$key] == '')
                continue;
            $_POST["supportField"][$key] = strip_tags($_POST["supportField"][$key]);
            $_POST["supportFieldType"][$key] = strip_tags($_POST["supportFieldType"][$key]);
            $_POST["supportFieldVariables"][$key] = ($_POST["supportFieldVariables"][$key] != null) ? strip_tags($_POST["supportFieldVariables"][$key]) : '-';
            $insertsupportFields = db()->prepare("INSERT INTO CustomSupportFields (categoryID, field, type, variables) VALUES (?, ?, ?, ?)");
            $insertsupportFields->execute(array($categoryID, $_POST["supportField"][$key], $_POST["supportFieldType"][$key], $_POST["supportFieldVariables"][$key]));
        }
	    
		    $deletePermissions = db()->prepare("DELETE FROM SupportCategoryRolePermissions WHERE categoryID = ?");
		    $deletePermissions->execute(array($id));
		    foreach ($_POST as $key => $value) {
			    if (substr($key, 0, 11) == "permission_") {
				    $roleAndPerm = explode("_", substr($key, 11));
				    $roleID = $roleAndPerm[0];
				    $permissionID = $roleAndPerm[1];
				    if (input($key) == 1) {
					    $insertSupportCategoryRolePermissions = db()->prepare("INSERT INTO SupportCategoryRolePermissions (categoryID, roleID, permissionID) VALUES (?, ?, ?)");
					    $insertSupportCategoryRolePermissions->execute(array($id, $roleID, $permissionID));
				    }
			    }
		    }
				
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

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