<?php

use ChurchCRM\dto\ChurchMetaData;
use ChurchCRM\dto\SystemConfig;
use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Service\WebsiteService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\PhpRenderer;

function commonVars(): array
{
    return [
        'rootPath' => SystemURLs::getRootPath(),
        'churchName' => ChurchMetaData::getChurchName(),
        'churchAddress' => SystemConfig::getValue('sChurchAddress'),
        'churchCity' => SystemConfig::getValue('sChurchCity'),
        'churchState' => SystemConfig::getValue('sChurchState'),
        'churchZip' => SystemConfig::getValue('sChurchZip'),
        'churchPhone' => SystemConfig::getValue('sChurchPhone'),
        'churchEmail' => SystemConfig::getValue('sChurchEmail'),
    ];
}

$app->get('/', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $featuredSermon = WebsiteService::getFeaturedSermon();
    $featuredVideo = WebsiteService::getFeaturedVideo();
    $latestSermons = WebsiteService::getSermons(3);
    $latestVideos = WebsiteService::getVideos(3);
    $prayers = WebsiteService::getPrayerRequests('approved');

    return $renderer->render($response, 'home.php', array_merge(commonVars(), [
        'featuredSermon' => $featuredSermon,
        'featuredVideo' => $featuredVideo,
        'latestSermons' => $latestSermons,
        'latestVideos' => $latestVideos,
        'prayers' => $prayers,
        'showHero' => true,
    ]));
});

$app->get('/sermons', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $sermons = WebsiteService::getSermons();

    return $renderer->render($response, 'sermons.php', array_merge(commonVars(), [
        'sermons' => $sermons,
        'pageHeaderTitle' => 'Sermons',
        'pageHeaderSubtitle' => 'Listen to our latest messages and teachings',
    ]));
});

$app->get('/sermon/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer('templates/website/');
    $sermon = WebsiteService::getSermon((int) $args['id']);

    if (!$sermon) {
        return $response->withStatus(404)->withHeader('Location', SystemURLs::getRootPath() . '/external/sermons');
    }

    return $renderer->render($response, 'sermon-detail.php', array_merge(commonVars(), [
        'sermon' => $sermon,
    ]));
});

$app->get('/videos', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $videos = WebsiteService::getVideos();

    return $renderer->render($response, 'videos.php', array_merge(commonVars(), [
        'videos' => $videos,
        'pageHeaderTitle' => 'Videos',
        'pageHeaderSubtitle' => 'Watch our latest videos and messages',
    ]));
});

$app->get('/prayer', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $prayers = WebsiteService::getPrayerRequests('answered');

    return $renderer->render($response, 'prayer.php', array_merge(commonVars(), [
        'prayers' => $prayers,
        'success' => false,
        'pageHeaderTitle' => 'Prayer',
        'pageHeaderSubtitle' => 'Share your prayer requests with our community',
    ]));
});

$app->post('/prayer', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $data = $request->getParsedBody();

    if (empty($data['request'])) {
        $prayers = WebsiteService::getPrayerRequests('answered');
        return $renderer->render($response, 'prayer.php', array_merge(commonVars(), [
            'prayers' => $prayers,
            'success' => false,
            'error' => 'Please enter your prayer request.',
            'pageHeaderTitle' => 'Prayer',
            'pageHeaderSubtitle' => 'Share your prayer requests with our community',
        ]));
    }

    WebsiteService::submitPrayerRequest([
        'name' => $data['name'] ?? '',
        'email' => $data['email'] ?? '',
        'request' => $data['request'],
    ]);

    $prayers = WebsiteService::getPrayerRequests('answered');
    return $renderer->render($response, 'prayer.php', array_merge(commonVars(), [
        'prayers' => $prayers,
        'success' => true,
        'pageHeaderTitle' => 'Prayer',
        'pageHeaderSubtitle' => 'Share your prayer requests with our community',
    ]));
});

$app->get('/about', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    return $renderer->render($response, 'about.php', array_merge(commonVars(), []));
});

$app->get('/contact', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    return $renderer->render($response, 'contact.php', array_merge(commonVars(), [
        'success' => false,
    ]));
});

$app->post('/contact', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer('templates/website/');
    $data = $request->getParsedBody();

    if (empty($data['name']) || empty($data['email']) || empty($data['message'])) {
        return $renderer->render($response, 'contact.php', array_merge(commonVars(), [
            'success' => false,
            'error' => 'Please fill in all required fields.',
        ]));
    }

    WebsiteService::submitContactForm([
        'name' => $data['name'],
        'email' => $data['email'],
        'subject' => $data['subject'] ?? '',
        'message' => $data['message'],
    ]);

    return $renderer->render($response, 'contact.php', array_merge(commonVars(), [
        'success' => true,
    ]));
});

$app->get('/website', function (Request $request, Response $response): Response {
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/external/')->withStatus(302);
});
