<?php

use ChurchCRM\dto\SystemConfig;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\model\ChurchCRM\FamilyQuery;
use ChurchCRM\model\ChurchCRM\PersonQuery;
use ChurchCRM\model\ChurchCRM\UserQuery;
use ChurchCRM\Plugin\PluginManager;
use ChurchCRM\view\PageHeader;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\PhpRenderer;

// Get Started — onboarding wizard page
$app->get('/get-started', function (Request $request, Response $response) {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');

    // Determine whether the database already contains user data. The demo
    // data import API only runs on a truly fresh install (exactly 1 person,
    // no families). When data is present we surface a warning in the UI
    // *before* the user clicks, instead of letting them discover the 403.
    $personCount = PersonQuery::create()->count();
    $familyCount = FamilyQuery::create()->count();
    $hasExistingData = $personCount > 1 || $familyCount > 0;

    $pageArgs = [
        'sRootPath'  => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Get Your Data Into ChurchCRM'),
        'sPageSubtitle' => gettext('Choose how you\'d like to populate your database. You can always use a different method later.'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Get Started')],
        ]),
        'hasExistingData' => $hasExistingData,
        'personCount'     => $personCount,
        'familyCount'     => $familyCount,
    ];

    return $renderer->render($response, 'get-started.php', $pageArgs);
});

// Match /admin root path
$app->get('/', function (Request $request, Response $response) {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');

    // Setup progress checklist
    $churchName    = SystemConfig::getValue('sChurchName');
    $churchAddress = SystemConfig::getValue('sChurchAddress');
    $churchEmail   = SystemConfig::getValue('sChurchEmail');

    $hasChurchInfo  = $churchName !== 'Some Church' && $churchName !== '' && $churchAddress !== '' && $churchEmail !== '';
    $hasData        = FamilyQuery::create()->select('Id')->findOne() !== null
        || PersonQuery::create()->select('Id')->findOne() !== null;
    $hasEmail       = SystemConfig::hasValidMailServerSettings();
    $userCount      = UserQuery::create()->count();
    $hasMultiUser   = $userCount > 1;
    // PluginManager::init() is normally called by Header.php (during view render),
    // but we need the plugin state before rendering, so initialize it here.
    // init() is idempotent — calling it twice is safe.
    PluginManager::init(SystemURLs::getDocumentRoot() . '/plugins');
    $hasPlugins = PluginManager::hasAnyActivePlugin();

    // New steps: HTTPS configuration and Admin contact (name/email) for password resets
    $hasHttps = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';

    // Check for an admin user with an email address
    $adminUser = UserQuery::create()->filterByAdmin(true)->findOne();
    $hasAdminContact = $adminUser && !empty($adminUser->getEmail());

    $completedSteps = (int)$hasChurchInfo + (int)$hasData + (int)$hasEmail + (int)$hasMultiUser + (int)$hasPlugins + (int)$hasHttps + (int)$hasAdminContact;
    $totalSteps     = 7;

    $setupChecklist = [
        [
            'done'  => $hasChurchInfo,
            'label' => gettext('Church Information'),
            'desc'  => gettext('Set your church name, address, and contact email'),
            'link'  => SystemURLs::getRootPath() . '/admin/system/church-info',
            'icon'  => 'fa-church',
        ],
        [
            'done'  => $hasData,
            'label' => gettext('Add Your Data'),
            'desc'  => gettext('Import, restore, or manually enter your congregation'),
            'link'  => SystemURLs::getRootPath() . '/admin/get-started',
            'icon'  => 'fa-users',
        ],
        [
            'done'  => $hasEmail,
            'label' => gettext('Configure Email'),
            'desc'  => gettext('Connect an SMTP server so ChurchCRM can send emails'),
            'link'  => SystemURLs::getRootPath() . '/v2/email/dashboard?settings=open',
            'icon'  => 'fa-envelope',
        ],
            [
                'done'  => $hasHttps,
                'label' => gettext('Enable HTTPS'),
                'desc'  => gettext('Install a TLS/SSL certificate for secure connections'),
                'link'  => 'https://docs.churchcrm.io/installation/ssl-https',
                'icon'  => 'fa-lock',
            ],
            [
                'done'  => $hasAdminContact,
                'label' => gettext('Update Admin Contact'),
                'desc'  => gettext('Set an admin user email so you can reset passwords and receive notifications'),
                'link'  => SystemURLs::getRootPath() . '/admin/system/users',
                'icon'  => 'fa-user-shield',
            ],
        [
            'done'    => $hasMultiUser,
            'label'   => gettext('Invite Your Team'),
            'desc'    => gettext('Add staff or volunteers as system users'),
            'link'    => SystemURLs::getRootPath() . '/admin/system/users',
            'icon'    => 'fa-user-plus',
        ],
        [
            'done'  => $hasPlugins,
            'label' => gettext('Enable Plugins'),
            'desc'  => gettext('Extend ChurchCRM with MailChimp, backups, and more'),
            'link'  => SystemURLs::getRootPath() . '/plugins/management',
            'icon'  => 'fa-plug',
        ],
    ];

    $pageArgs = [
        'sRootPath'        => SystemURLs::getRootPath(),
        'sPageTitle'       => gettext('Admin Dashboard'),
        'sPageSubtitle'    => gettext("Let's get your system set up and ready to use"),
        'aBreadcrumbs'     => PageHeader::breadcrumbs([
            [gettext('Admin')],
        ]),
        'sPageHeaderButtons' => PageHeader::buttons([
            ['label' => gettext('System Settings'), 'url' => '/SystemSettings.php', 'icon' => 'fa-cog'],
            ['label' => gettext('Church Info'), 'url' => '/admin/system/church-info', 'icon' => 'fa-church'],
            ['label' => gettext('Users'), 'url' => '/admin/system/users', 'icon' => 'fa-user-shield'],
        ]),
        'setupChecklist'   => $setupChecklist,
        'completedSteps'   => $completedSteps,
        'totalSteps'       => $totalSteps,
        'allDone'          => $completedSteps === $totalSteps,
    ];

    return $renderer->render($response, 'dashboard.php', $pageArgs);
});
