<?php

use ChurchCRM\dto\ChurchMetaData;
use ChurchCRM\dto\SystemConfig;
use ChurchCRM\Service\WebsiteService;
use ChurchCRM\Slim\SlimUtils;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Routing\RouteCollectorProxy;

$app->group('/public/website', function (RouteCollectorProxy $group): void {
    $group->get('/sermons', 'getPublicSermons');
    $group->get('/sermons/featured', 'getPublicFeaturedSermon');
    $group->get('/sermons/{id}', 'getPublicSermon');
    $group->get('/videos', 'getPublicVideos');
    $group->get('/videos/featured', 'getPublicFeaturedVideo');
    $group->get('/videos/{id}', 'getPublicVideo');
    $group->get('/prayers/answered', 'getPublicAnsweredPrayers');
    $group->post('/prayer', 'submitPublicPrayer');
    $group->post('/contact', 'submitPublicContact');
    $group->get('/info', 'getPublicChurchInfo');
    $group->get('/content', 'getPublicAllContent');
    $group->get('/content/{key}', 'getPublicContentByKey');
    $group->get('/events', 'getPublicEvents');
    $group->get('/events/{id}', 'getPublicEvent');
    $group->get('/gallery', 'getPublicGallery');
    $group->get('/gallery/categories', 'getPublicGalleryCategories');
    $group->get('/groups', 'getPublicGroups');
    $group->post('/groups/join', 'submitPublicGroupJoin');
    $group->get('/team', 'getPublicTeam');
    $group->get('/ministries', 'getPublicMinistries');
});

function getPublicSermons(Request $request, Response $response): Response
{
    $params = $request->getQueryParams();
    $limit = isset($params['limit']) ? (int) $params['limit'] : 0;
    $offset = isset($params['offset']) ? (int) $params['offset'] : 0;
    $sermons = WebsiteService::getSermons($limit, $offset);
    return SlimUtils::renderJSON($response, ['sermons' => $sermons]);
}

function getPublicFeaturedSermon(Request $request, Response $response): Response
{
    $sermon = WebsiteService::getFeaturedSermon();
    return SlimUtils::renderJSON($response, ['sermon' => $sermon]);
}

function getPublicSermon(Request $request, Response $response, array $args): Response
{
    $sermon = WebsiteService::getSermon((int) $args['id']);
    if (!$sermon) {
        return SlimUtils::renderJSON($response, ['error' => 'Sermon not found'], 404);
    }
    return SlimUtils::renderJSON($response, ['sermon' => $sermon]);
}

function getPublicVideos(Request $request, Response $response): Response
{
    $params = $request->getQueryParams();
    $limit = isset($params['limit']) ? (int) $params['limit'] : 0;
    $offset = isset($params['offset']) ? (int) $params['offset'] : 0;
    $videos = WebsiteService::getVideos($limit, $offset);
    return SlimUtils::renderJSON($response, ['videos' => $videos]);
}

function getPublicFeaturedVideo(Request $request, Response $response): Response
{
    $video = WebsiteService::getFeaturedVideo();
    return SlimUtils::renderJSON($response, ['video' => $video]);
}

function getPublicVideo(Request $request, Response $response, array $args): Response
{
    $video = WebsiteService::getVideo((int) $args['id']);
    if (!$video) {
        return SlimUtils::renderJSON($response, ['error' => 'Video not found'], 404);
    }
    return SlimUtils::renderJSON($response, ['video' => $video]);
}

function getPublicAnsweredPrayers(Request $request, Response $response): Response
{
    $prayers = WebsiteService::getPrayerRequests('answered');
    return SlimUtils::renderJSON($response, ['prayers' => $prayers]);
}

function submitPublicPrayer(Request $request, Response $response): Response
{
    $data = json_decode((string) $request->getBody(), true);
    if (empty($data['request'])) {
        return SlimUtils::renderJSON($response, ['error' => 'Prayer request is required'], 400);
    }
    WebsiteService::submitPrayerRequest([
        'name' => $data['name'] ?? '',
        'email' => $data['email'] ?? '',
        'request' => $data['request'],
    ]);
    return SlimUtils::renderJSON($response, ['success' => true]);
}

function submitPublicContact(Request $request, Response $response): Response
{
    $data = json_decode((string) $request->getBody(), true);
    if (empty($data['name']) || empty($data['email']) || empty($data['message'])) {
        return SlimUtils::renderJSON($response, ['error' => 'Name, email, and message are required'], 400);
    }
    WebsiteService::submitContactForm([
        'name' => $data['name'],
        'email' => $data['email'],
        'subject' => $data['subject'] ?? '',
        'message' => $data['message'],
    ]);
    return SlimUtils::renderJSON($response, ['success' => true]);
}

function getPublicChurchInfo(Request $request, Response $response): Response
{
    return SlimUtils::renderJSON($response, [
        'name' => ChurchMetaData::getChurchName(),
        'address' => SystemConfig::getValue('sChurchAddress'),
        'city' => SystemConfig::getValue('sChurchCity'),
        'state' => SystemConfig::getValue('sChurchState'),
        'zip' => SystemConfig::getValue('sChurchZip'),
        'phone' => SystemConfig::getValue('sChurchPhone'),
        'email' => SystemConfig::getValue('sChurchEmail'),
        'website' => SystemConfig::getValue('sChurchWebSite'),
        'logo_url' => ChurchMetaData::getChurchLogoURL(),
    ]);
}

function getPublicAllContent(Request $request, Response $response): Response
{
    $content = WebsiteService::getAllContent();
    $mapped = [];
    foreach ($content as $c) {
        $mapped[$c['cct_key']] = [
            'id' => $c['cct_id'],
            'key' => $c['cct_key'],
            'title' => $c['cct_title'],
            'content' => $c['cct_content'],
            'image_url' => $c['cct_image_url'],
            'icon' => $c['cct_icon'],
        ];
    }
    return SlimUtils::renderJSON($response, ['content' => $mapped]);
}

function getPublicContentByKey(Request $request, Response $response, array $args): Response
{
    $item = WebsiteService::getContentByKey($args['key']);
    if (!$item) {
        return SlimUtils::renderJSON($response, ['error' => 'Content not found'], 404);
    }
    return SlimUtils::renderJSON($response, ['content' => $item]);
}

function getPublicEvents(Request $request, Response $response): Response
{
    $params = $request->getQueryParams();
    $limit = isset($params['limit']) ? (int) $params['limit'] : 0;
    $featured = !empty($params['featured']);
    $events = WebsiteService::getEvents($limit, $featured);
    return SlimUtils::renderJSON($response, ['events' => $events]);
}

function getPublicEvent(Request $request, Response $response, array $args): Response
{
    $event = WebsiteService::getEvent((int) $args['id']);
    if (!$event) {
        return SlimUtils::renderJSON($response, ['error' => 'Event not found'], 404);
    }
    return SlimUtils::renderJSON($response, ['event' => $event]);
}

function getPublicGallery(Request $request, Response $response): Response
{
    $params = $request->getQueryParams();
    $category = $params['category'] ?? '';
    $images = WebsiteService::getGalleryImages($category);
    return SlimUtils::renderJSON($response, ['images' => $images]);
}

function getPublicGalleryCategories(Request $request, Response $response): Response
{
    $categories = WebsiteService::getGalleryCategories();
    return SlimUtils::renderJSON($response, ['categories' => $categories]);
}

function getPublicGroups(Request $request, Response $response): Response
{
    $groups = WebsiteService::getGroups();
    return SlimUtils::renderJSON($response, ['groups' => $groups]);
}

function submitPublicGroupJoin(Request $request, Response $response): Response
{
    $data = $request->getParsedBody();

    if (empty($data['group_id']) || empty($data['name']) || empty($data['email'])) {
        return SlimUtils::renderJSON($response, ['error' => 'Missing required fields'], 400);
    }

    WebsiteService::submitGroupJoin($data);

    return SlimUtils::renderJSON($response, ['success' => true, 'message' => 'You will receive a confirmation email shortly.']);
}

function getPublicTeam(Request $request, Response $response): Response
{
    $team = WebsiteService::getTeam();
    return SlimUtils::renderJSON($response, ['team' => $team]);
}

function getPublicMinistries(Request $request, Response $response): Response
{
    $ministries = WebsiteService::getMinistries();
    return SlimUtils::renderJSON($response, ['ministries' => $ministries]);
}
