<?php

use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Service\WebsiteService;
use ChurchCRM\Service\CloudinaryService;
use ChurchCRM\view\PageHeader;
use ChurchCRM\Authentication\AuthenticationManager;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\UploadedFileInterface;
use Slim\Views\PhpRenderer;

function handleFileUpload(array $files, string $fieldName, ?string $existingUrl = null): ?string
{
    if (empty($files[$fieldName])) {
        return $existingUrl;
    }
    $file = $files[$fieldName];
    if ($file instanceof UploadedFileInterface && $file->getError() === UPLOAD_ERR_OK) {
        $tmpPath = $file->getStream()->getMetadata('uri');
        $cloudUrl = CloudinaryService::uploadFile($tmpPath);
        if ($cloudUrl) {
            return $cloudUrl;
        }
    }
    return $existingUrl;
}

function wasFileUploaded(array $files, string $fieldName): bool
{
    return !empty($files[$fieldName])
        && $files[$fieldName] instanceof UploadedFileInterface
        && $files[$fieldName]->getError() === UPLOAD_ERR_OK;
}

// ---- Sermons ----

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

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Manage Sermons'),
        'sPageSubtitle' => gettext('Add, edit, and manage your church sermons'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Sermons')],
        ]),
        'sermons' => $sermons,
    ];

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

$app->get('/website/sermons/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Sermon'),
        'sPageSubtitle' => gettext('Create a new sermon'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Sermons'), '/admin/website/sermons'],
            [gettext('Add')],
        ]),
        'sermon' => null,
    ];

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

$app->post('/website/sermons/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    $data['audio_url'] = handleFileUpload($files, 'audio_file', $data['audio_url'] ?? null);
    $userId = AuthenticationManager::getCurrentUser()->getId();
    WebsiteService::createSermon($data, $userId);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/sermons')->withStatus(302);
});

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

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

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Sermon'),
        'sPageSubtitle' => $sermon['serm_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Sermons'), '/admin/website/sermons'],
            [gettext('Edit')],
        ]),
        'sermon' => $sermon,
    ];

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

$app->post('/website/sermons/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    $data['audio_url'] = handleFileUpload($files, 'audio_file', $data['audio_url'] ?? null);
    WebsiteService::updateSermon((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/sermons')->withStatus(302);
});

$app->get('/website/sermons/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteSermon((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/sermons')->withStatus(302);
});

// ---- Videos ----

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

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Manage Videos'),
        'sPageSubtitle' => gettext('Add, edit, and manage your church videos'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Videos')],
        ]),
        'videos' => $videos,
    ];

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

$app->get('/website/videos/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Video'),
        'sPageSubtitle' => gettext('Add a new video'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Videos'), '/admin/website/videos'],
            [gettext('Add')],
        ]),
        'video' => null,
    ];

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

$app->post('/website/videos/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['thumbnail_url'] = handleFileUpload($files, 'thumbnail_file', $data['thumbnail_url'] ?? null);
    $data['url'] = handleFileUpload($files, 'video_file', $data['url'] ?? null);
    $userId = AuthenticationManager::getCurrentUser()->getId();
    WebsiteService::createVideo($data, $userId);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/videos')->withStatus(302);
});

$app->get('/website/videos/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $video = WebsiteService::getVideo((int) $args['id']);

    if (!$video) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/videos')->withStatus(302);
    }

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Video'),
        'sPageSubtitle' => $video['vid_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Videos'), '/admin/website/videos'],
            [gettext('Edit')],
        ]),
        'video' => $video,
    ];

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

$app->post('/website/videos/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['thumbnail_url'] = handleFileUpload($files, 'thumbnail_file', $data['thumbnail_url'] ?? null);
    $data['url'] = handleFileUpload($files, 'video_file', $data['url'] ?? null);
    WebsiteService::updateVideo((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/videos')->withStatus(302);
});

$app->get('/website/videos/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteVideo((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/videos')->withStatus(302);
});

// ---- Prayer Requests ----

$app->get('/website/prayers', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $prayers = WebsiteService::getAllPrayerRequests();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Prayer Requests'),
        'sPageSubtitle' => gettext('Manage prayer requests from visitors'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Prayer Requests')],
        ]),
        'prayers' => $prayers,
    ];

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

$app->post('/website/prayers/status/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    WebsiteService::updatePrayerStatus((int) $args['id'], $data['status'], $data['answer_notes'] ?? null);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/prayers')->withStatus(302);
});

$app->get('/website/prayers/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deletePrayerRequest((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/prayers')->withStatus(302);
});

// ---- Contact Submissions ----

$app->get('/website/contact', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $submissions = WebsiteService::getContactSubmissions();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Contact Submissions'),
        'sPageSubtitle' => gettext('Messages from the website contact form'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Contact')],
        ]),
        'submissions' => $submissions,
    ];

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

$app->get('/website/contact/read/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::markContactRead((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/contact')->withStatus(302);
});

$app->get('/website/contact/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteContactSubmission((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/contact')->withStatus(302);
});

// ---- Church Content (Mandate, Vision, History, etc.) ----

$app->get('/website/content', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $content = WebsiteService::getAllContent();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Church Content'),
        'sPageSubtitle' => gettext('Manage mandate, vision, history, and other church content'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Church Content')],
        ]),
        'content' => $content,
    ];

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

$app->get('/website/content/edit/{key}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $item = WebsiteService::getContentByKey($args['key']);

    if (!$item) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/content')->withStatus(302);
    }

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Content'),
        'sPageSubtitle' => $item['cct_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Church Content'), '/admin/website/content'],
            [gettext('Edit')],
        ]),
        'item' => $item,
    ];

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

$app->post('/website/content/edit/{key}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    $userId = AuthenticationManager::getCurrentUser()->getId();
    WebsiteService::upsertContent($args['key'], $data, $userId);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/content')->withStatus(302);
});

$app->get('/website/content/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteContent((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/content')->withStatus(302);
});

// ---- Events ----

$app->get('/website/events', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $events = WebsiteService::getEvents();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Manage Events'),
        'sPageSubtitle' => gettext('Add, edit, and manage church events'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Events')],
        ]),
        'events' => $events,
    ];

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

$app->get('/website/events/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Event'),
        'sPageSubtitle' => gettext('Create a new event'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Events'), '/admin/website/events'],
            [gettext('Add')],
        ]),
        'event' => null,
    ];

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

$app->post('/website/events/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    $userId = AuthenticationManager::getCurrentUser()->getId();
    WebsiteService::createEvent($data, $userId);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/events')->withStatus(302);
});

$app->get('/website/events/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $event = WebsiteService::getEvent((int) $args['id']);

    if (!$event) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/events')->withStatus(302);
    }

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Event'),
        'sPageSubtitle' => $event['evt_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Events'), '/admin/website/events'],
            [gettext('Edit')],
        ]),
        'event' => $event,
    ];

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

$app->post('/website/events/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::updateEvent((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/events')->withStatus(302);
});

$app->get('/website/events/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteEvent((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/events')->withStatus(302);
});

// ---- Gallery ----

$app->get('/website/gallery', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $images = WebsiteService::getGalleryImages();

    $sGlobalMessage = '';
    $sGlobalMessageClass = 'success';
    if (isset($_SESSION['sGlobalMessage'])) {
        $sGlobalMessage = $_SESSION['sGlobalMessage'];
        $sGlobalMessageClass = $_SESSION['sGlobalMessageClass'] ?? 'success';
        unset($_SESSION['sGlobalMessage'], $_SESSION['sGlobalMessageClass']);
    }

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Photo Gallery'),
        'sPageSubtitle' => gettext('Manage gallery images for the website'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Gallery')],
        ]),
        'images' => $images,
        'sGlobalMessage' => $sGlobalMessage,
        'sGlobalMessageClass' => $sGlobalMessageClass,
    ];

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

$app->get('/website/gallery/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Gallery Image'),
        'sPageSubtitle' => gettext('Add a new image to the gallery'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Gallery'), '/admin/website/gallery'],
            [gettext('Add')],
        ]),
        'image' => null,
    ];
    return $renderer->render($response, 'website-gallery-edit.php', $pageArgs);
});

$app->post('/website/gallery/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $fileUploaded = wasFileUploaded($files, 'image_file');
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::createGalleryImage($data);
    if ($fileUploaded && empty($data['image_url'])) {
        if (!CloudinaryService::isConfigured()) {
            $_SESSION['sGlobalMessage'] = gettext('Cloudinary is not configured. Go to System Settings to set up Cloudinary API keys. The image was not saved.');
            $_SESSION['sGlobalMessageClass'] = 'danger';
        } else {
            $_SESSION['sGlobalMessage'] = gettext('Image upload to Cloudinary failed. Check your Cloudinary configuration and try again.');
            $_SESSION['sGlobalMessageClass'] = 'warning';
        }
    } elseif (empty($data['image_url'])) {
        $_SESSION['sGlobalMessage'] = gettext('Gallery image saved without an image. Edit it to add one.');
        $_SESSION['sGlobalMessageClass'] = 'warning';
    } else {
        $_SESSION['sGlobalMessage'] = gettext('Gallery image added successfully.');
        $_SESSION['sGlobalMessageClass'] = 'success';
    }
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/gallery')->withStatus(302);
});

$app->get('/website/gallery/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $images = WebsiteService::getGalleryImages();
    $image = null;
    foreach ($images as $img) {
        if ((int)$img['gal_id'] === (int)$args['id']) {
            $image = $img;
            break;
        }
    }
    if (!$image) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/gallery')->withStatus(302);
    }
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Gallery Image'),
        'sPageSubtitle' => $image['gal_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Gallery'), '/admin/website/gallery'],
            [gettext('Edit')],
        ]),
        'image' => $image,
    ];
    return $renderer->render($response, 'website-gallery-edit.php', $pageArgs);
});

$app->post('/website/gallery/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $fileUploaded = wasFileUploaded($files, 'image_file');
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::updateGalleryImage((int) $args['id'], $data);
    if ($fileUploaded && empty($data['image_url'])) {
        if (!CloudinaryService::isConfigured()) {
            $_SESSION['sGlobalMessage'] = gettext('Cloudinary is not configured. Go to System Settings to set up Cloudinary API keys.');
            $_SESSION['sGlobalMessageClass'] = 'danger';
        } else {
            $_SESSION['sGlobalMessage'] = gettext('Image upload to Cloudinary failed. Check your Cloudinary configuration and try again.');
            $_SESSION['sGlobalMessageClass'] = 'warning';
        }
    } else {
        $_SESSION['sGlobalMessage'] = gettext('Gallery image updated successfully.');
        $_SESSION['sGlobalMessageClass'] = 'success';
    }
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/gallery')->withStatus(302);
});

$app->get('/website/gallery/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteGalleryImage((int) $args['id']);
    $_SESSION['sGlobalMessage'] = gettext('Gallery image deleted successfully.');
    $_SESSION['sGlobalMessageClass'] = 'success';
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/gallery')->withStatus(302);
});

// ---- Groups ----

$app->get('/website/groups', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $groups = WebsiteService::getGroups();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Manage Groups'),
        'sPageSubtitle' => gettext('Add, edit, and manage small groups'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Groups')],
        ]),
        'groups' => $groups,
    ];

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

$app->get('/website/groups/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Group'),
        'sPageSubtitle' => gettext('Add a new small group'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Groups'), '/admin/website/groups'],
            [gettext('Add')],
        ]),
        'group' => null,
    ];
    return $renderer->render($response, 'website-groups-edit.php', $pageArgs);
});

$app->post('/website/groups/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::createGroup($data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/groups')->withStatus(302);
});

$app->get('/website/groups/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $group = WebsiteService::getGroup((int) $args['id']);
    if (!$group) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/groups')->withStatus(302);
    }
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Group'),
        'sPageSubtitle' => $group['grp_name'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Groups'), '/admin/website/groups'],
            [gettext('Edit')],
        ]),
        'group' => $group,
    ];
    return $renderer->render($response, 'website-groups-edit.php', $pageArgs);
});

$app->post('/website/groups/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::updateGroup((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/groups')->withStatus(302);
});

$app->get('/website/groups/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteGroup((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/groups')->withStatus(302);
});

// ---- Team / Leadership ----

$app->get('/website/team', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $team = WebsiteService::getTeam();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Leadership Team'),
        'sPageSubtitle' => gettext('Manage church staff and leadership'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Leadership')],
        ]),
        'team' => $team,
    ];

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

$app->get('/website/team/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Team Member'),
        'sPageSubtitle' => gettext('Add a new leadership team member'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Leadership'), '/admin/website/team'],
            [gettext('Add')],
        ]),
        'member' => null,
    ];
    return $renderer->render($response, 'website-team-edit.php', $pageArgs);
});

$app->post('/website/team/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::createTeamMember($data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/team')->withStatus(302);
});

$app->get('/website/team/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $member = WebsiteService::getTeamMember((int) $args['id']);
    if (!$member) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/team')->withStatus(302);
    }
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Team Member'),
        'sPageSubtitle' => $member['tem_name'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Leadership'), '/admin/website/team'],
            [gettext('Edit')],
        ]),
        'member' => $member,
    ];
    return $renderer->render($response, 'website-team-edit.php', $pageArgs);
});

$app->post('/website/team/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::updateTeamMember((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/team')->withStatus(302);
});

$app->get('/website/team/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteTeamMember((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/team')->withStatus(302);
});

// ---- Ministries ----

$app->get('/website/ministries', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $ministries = WebsiteService::getMinistries();

    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Manage Ministries'),
        'sPageSubtitle' => gettext('Add, edit, and manage ministries displayed on the website'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Ministries')],
        ]),
        'ministries' => $ministries,
    ];

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

$app->get('/website/ministries/create', function (Request $request, Response $response): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Add Ministry'),
        'sPageSubtitle' => gettext('Add a new ministry'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Ministries'), '/admin/website/ministries'],
            [gettext('Add')],
        ]),
        'ministry' => null,
    ];
    return $renderer->render($response, 'website-ministries-edit.php', $pageArgs);
});

$app->post('/website/ministries/create', function (Request $request, Response $response): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::createMinistry($data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/ministries')->withStatus(302);
});

$app->get('/website/ministries/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    $ministry = WebsiteService::getMinistry((int) $args['id']);
    if (!$ministry) {
        return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/ministries')->withStatus(302);
    }
    $pageArgs = [
        'sRootPath' => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Edit Ministry'),
        'sPageSubtitle' => $ministry['min_title'],
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Admin'), '/admin/'],
            [gettext('Website')],
            [gettext('Ministries'), '/admin/website/ministries'],
            [gettext('Edit')],
        ]),
        'ministry' => $ministry,
    ];
    return $renderer->render($response, 'website-ministries-edit.php', $pageArgs);
});

$app->post('/website/ministries/edit/{id}', function (Request $request, Response $response, array $args): Response {
    $data = $request->getParsedBody();
    $files = $request->getUploadedFiles();
    $data['image_url'] = handleFileUpload($files, 'image_file', $data['image_url'] ?? null);
    WebsiteService::updateMinistry((int) $args['id'], $data);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/ministries')->withStatus(302);
});

$app->get('/website/ministries/delete/{id}', function (Request $request, Response $response, array $args): Response {
    WebsiteService::deleteMinistry((int) $args['id']);
    return $response->withHeader('Location', SystemURLs::getRootPath() . '/admin/website/ministries')->withStatus(302);
});
