<?php

use Claromentis\Comments;
use Claromentis\Comments\Model\Attachment;
use Claromentis\Core\Acl\RoleBased\RoleRepository;
use Claromentis\Core\Repository\Repository;
use Claromentis\Projects\Permissions;
use Claromentis\Projects\ProjectsRepository;

if (!defined('INSTALL_PROGRESS'))
	die("This file cannot be executed directly");

if (!isset($installer))
	throw new Exception("Install options are not defined");
/** @var $installer Claromentis\Setup\SetupFacade */

$plugins = $installer->GetPluginsRepository();
$plugins->Remove('projects', '\Claromentis\Projects\ProjectsPlugin');

// Remove admin panel permissions
$panels = $installer->GetAdminPanelCreator();
$panels->Delete('projects');

$db = $installer->GetDb();

// Delete metadata
$md_set_type = 61; // \Claromentis\Projects\Repository\ProjectRepository::METADATA_SET_PROJECTS_PROJECT;
$db->query("DELETE FROM metadata_set_fields WHERE set_id IN (SELECT id FROM metadata_set WHERE set_type=int:set_type)", $md_set_type);
$db->query("DELETE FROM metadata_set WHERE set_type=int:set_type", $md_set_type);


$db->query("DELETE FROM metadata_simple WHERE aggregation=int:aggr", 121 /* AGGREGATION_PROJECTS_PROJECT */);

$db->query("DELETE FROM variables WHERE var_name eq:str:projects_root_folder_variable", ProjectsRepository::PROJECTS_ROOT_FOLDER);
$db->query("DELETE FROM variables WHERE var_name eq:str:projects_files_dmsv_view_style_variable", ProjectsRepository::PROJECTS_FILES_DMSV_VIEW_STYLE);
$db->query("DELETE FROM variables WHERE var_name eq:str:projects_files_dmsv_action_variable", ProjectsRepository::PROJECTS_FILES_DMSV_ACTION);
$db->query("DELETE FROM variables WHERE var_name eq:str:projects_files_dmsv_detailed_upload", ProjectsRepository::PROJECTS_FILES_DMSV_DETAILED_UPLOAD);
$db->query("DELETE FROM variables WHERE var_name eq:str:projects_files_dmsv_new_window", ProjectsRepository::PROJECTS_FILES_DMSV_NEW_WINDOW);

// Delete Project and Task comments
$comments_repository = new Comments\CommentsRepository($db);
$comment_attachments_repository = new Repository($db, new Attachment());

$aggregation_ids = [Permissions::PROJECT_AGGREGATION, Permissions::TASK_AGGREGATION];

foreach ($aggregation_ids as $aggregation_id)
{
	$comments = $comments_repository->GetAggregationTopLevelComments($aggregation_id);
	foreach ($comments as $comment)
	{
		$comments_repository->Delete($comment, $comment_attachments_repository);
	}
}

$role_ids = $db
	->query("SELECT id FROM acl_role WHERE aggregation=int:agg", Permissions::PROJECT_AGGREGATION)
	->fetchAllValues();
$db->query("DELETE FROM acl_role WHERE aggregation=int:agg", Permissions::PROJECT_AGGREGATION);
$db->query("DELETE FROM permissions WHERE class_id=int:class_id AND object_id IN in:int:ids", RoleRepository::PERM_CLASS_ACL_ROLE, $role_ids);
