<?php

namespace idoit\Module\System\Controller;

use isys_application;
use isys_helper_link;
use isys_module_system;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Throwable;

/**
 * System relevant add-on controller.
 *
 * @package   Modules
 * @copyright synetics GmbH
 * @license   http://www.i-doit.com/license
 */
class DuplicateUsernameCheckController
{
    public function getModalData(): Response
    {
        $dao = isys_application::instance()->container->get('cmdb_dao');
        $template = isys_application::instance()->container->get('template');
        $response = [
            'success' => true,
            'data'    => null,
            'message' => ''
        ];

        try {
            $duplicatedData = [];

            $sql = "SELECT isys_cats_person_list__title AS title, COUNT(isys_cats_person_list__title) AS cnt
                FROM isys_cats_person_list
                WHERE isys_cats_person_list__title != '' AND isys_cats_person_list__title IS NOT NULL
                GROUP BY isys_cats_person_list__title
                HAVING COUNT(isys_cats_person_list__title) > 1;";

            $result = $dao->retrieve($sql);
            $hasDuplicates = count($result) > 0;

            while ($row = $result->get_row()) {
                $username = $dao->convert_sql_text($row['title']);
                $sql = "SELECT isys_obj__id AS id, isys_obj__title AS title
                    FROM isys_cats_person_list
                    INNER JOIN isys_obj ON isys_obj__id = isys_cats_person_list__isys_obj__id
                    WHERE isys_cats_person_list__title = {$username};";

                $details = [];
                $duplicatesResult = $dao->retrieve($sql);

                while ($duplicateRow = $duplicatesResult->get_row()) {
                    $details[] = [
                        'id'    => (int)$duplicateRow['id'],
                        'title' => $duplicateRow['title'],
                        'link'  => isys_helper_link::create_cats_url([
                            C__CMDB__GET__OBJECT => $duplicateRow['id'],
                            C__CMDB__GET__CATS => C__CATS__PERSON_LOGIN
                        ])
                    ];
                }

                $duplicatedData[] = [
                    'amount'  => (int)$row['cnt'],
                    'title'   => $row['title'],
                    'details' => $details
                ];
            }

            $response['data'] = $template
                ->assign('hasDuplicates', $hasDuplicates)
                ->assign('duplicatedData', $duplicatedData)
                ->fetch(isys_module_system::getPath() . '/templates/modal/duplicate-username-check.tpl');
        } catch (Throwable $e) {
            $response['success'] = false;
            $response['message'] = $e->getMessage();
        }

        return new JsonResponse($response);
    }
}
