<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once dirname(__DIR__, 2) . '/modules/notifications/helpers.php';

$mediaModuleBoot = 'media_module_boot';
$validateNewsPayload = 'validate_news_payload';
$validateMediaPayload = 'validate_media_payload';
$findNewsPostOrAbort = 'find_news_post_or_abort';
$findMediaItemOrAbort = 'find_media_item_or_abort';

$mediaModuleBoot();

if (!is_post()) {
    redirect('app/modules/media/index.php');
}

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'create_news') {
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateNewsPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the news form errors.']);
        redirect('app/modules/media/create-news.php');
    }

    $featuredImage = null;
    if (isset($_FILES['featured_image']) && ($_FILES['featured_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $featuredImage = upload_file($_FILES['featured_image'], [
                'directory' => 'news',
                'max_size' => 4 * 1024 * 1024,
                'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
                'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
            ]);
        } catch (RuntimeException $exception) {
            flash('errors', ['featured_image' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/media/create-news.php');
        }
    }

    db_query(
        'INSERT INTO news_posts (
            title, slug, category, body, featured_image, status, created_by, published_at, created_at
         ) VALUES (
            :title, :slug, :category, :body, :featured_image, :status, :created_by, :published_at, NOW()
         )',
        $payload + ['featured_image' => $featuredImage]
    );

    $postId = (int) db()->lastInsertId();
    if (($payload['status'] ?? 'draft') === 'published') {
        web_push_send_news_post($postId);
    }
    audit_log('create_news_post', 'news_posts', $postId, null, $payload + ['featured_image' => $featuredImage]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'News post created successfully.']);
    redirect('app/modules/media/view-news.php?id=' . $postId);
}

if ($action === 'update_news') {
    $postId = (int) ($_POST['id'] ?? 0);
    $existingPost = $findNewsPostOrAbort($postId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateNewsPayload($_POST, $errors, $postId);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the news form errors.']);
        redirect('app/modules/media/edit-news.php?id=' . $postId);
    }

    $featuredImage = $existingPost['featured_image'];
    if (isset($_FILES['featured_image']) && ($_FILES['featured_image']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $featuredImage = upload_file($_FILES['featured_image'], [
                'directory' => 'news',
                'max_size' => 4 * 1024 * 1024,
                'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
                'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
            ]);
            delete_uploaded_file($existingPost['featured_image']);
        } catch (RuntimeException $exception) {
            flash('errors', ['featured_image' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/media/edit-news.php?id=' . $postId);
        }
    }

    db_query(
        'UPDATE news_posts
         SET title = :title,
             slug = :slug,
             category = :category,
             body = :body,
             featured_image = :featured_image,
             status = :status,
             published_at = :published_at
         WHERE id = :id',
        $payload + ['featured_image' => $featuredImage, 'id' => $postId]
    );

    if (($existingPost['status'] ?? 'draft') !== 'published' && ($payload['status'] ?? 'draft') === 'published') {
        web_push_send_news_post($postId);
    }

    audit_log('update_news_post', 'news_posts', $postId, $existingPost, $payload + ['featured_image' => $featuredImage]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'News post updated successfully.']);
    redirect('app/modules/media/view-news.php?id=' . $postId);
}

if ($action === 'delete_news') {
    $postId = (int) ($_POST['id'] ?? 0);
    $existingPost = $findNewsPostOrAbort($postId);
    db_query('DELETE FROM news_posts WHERE id = :id', ['id' => $postId]);
    delete_uploaded_file($existingPost['featured_image']);
    audit_log('delete_news_post', 'news_posts', $postId, $existingPost, null);
    flash('success', ['type' => 'success', 'message' => 'News post deleted successfully.']);
    redirect('app/modules/media/index.php');
}

if ($action === 'create_media') {
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateMediaPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the gallery form errors.']);
        redirect('app/modules/media/create-gallery.php' . ($payload['fixture_id'] !== null ? '?fixture_id=' . $payload['fixture_id'] : ''));
    }

    $filePath = null;
    if (!isset($_FILES['media_file']) || ($_FILES['media_file']['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) {
        flash('errors', ['media_file' => 'Media file is required.']);
        flash('error', ['type' => 'danger', 'message' => 'Media file is required.']);
        redirect('app/modules/media/create-gallery.php' . ($payload['fixture_id'] !== null ? '?fixture_id=' . $payload['fixture_id'] : ''));
    }

    try {
        $uploadOptions = $payload['media_type'] === 'video'
            ? [
                'directory' => 'media',
                'max_size' => 20 * 1024 * 1024,
                'allowed_mime_types' => ['video/mp4', 'video/webm'],
                'allowed_extensions' => ['mp4', 'webm'],
            ]
            : [
                'directory' => 'media',
                'max_size' => 6 * 1024 * 1024,
                'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
                'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
            ];
        $filePath = upload_file($_FILES['media_file'], $uploadOptions);
    } catch (RuntimeException $exception) {
        flash('errors', ['media_file' => $exception->getMessage()]);
        flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
        redirect('app/modules/media/create-gallery.php' . ($payload['fixture_id'] !== null ? '?fixture_id=' . $payload['fixture_id'] : ''));
    }

    db_query(
        'INSERT INTO media_gallery (
            title, file_path, media_type, fixture_id, club_id, created_at
         ) VALUES (
            :title, :file_path, :media_type, :fixture_id, :club_id, NOW()
         )',
        $payload + ['file_path' => $filePath]
    );

    $mediaId = (int) db()->lastInsertId();
    audit_log('create_media_item', 'media_gallery', $mediaId, null, $payload + ['file_path' => $filePath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Media item uploaded successfully.']);
    redirect('app/modules/media/view-gallery.php?id=' . $mediaId);
}

if ($action === 'update_media') {
    $mediaId = (int) ($_POST['id'] ?? 0);
    $existingItem = $findMediaItemOrAbort($mediaId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateMediaPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the gallery form errors.']);
        redirect('app/modules/media/edit-gallery.php?id=' . $mediaId);
    }

    $filePath = $existingItem['file_path'];
    if (isset($_FILES['media_file']) && ($_FILES['media_file']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $uploadOptions = $payload['media_type'] === 'video'
                ? [
                    'directory' => 'media',
                    'max_size' => 20 * 1024 * 1024,
                    'allowed_mime_types' => ['video/mp4', 'video/webm'],
                    'allowed_extensions' => ['mp4', 'webm'],
                ]
                : [
                    'directory' => 'media',
                    'max_size' => 6 * 1024 * 1024,
                    'allowed_mime_types' => ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
                    'allowed_extensions' => ['jpg', 'jpeg', 'png', 'webp', 'gif'],
                ];
            $filePath = upload_file($_FILES['media_file'], $uploadOptions);
            delete_uploaded_file($existingItem['file_path']);
        } catch (RuntimeException $exception) {
            flash('errors', ['media_file' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/media/edit-gallery.php?id=' . $mediaId);
        }
    }

    db_query(
        'UPDATE media_gallery
         SET title = :title,
             file_path = :file_path,
             media_type = :media_type,
             fixture_id = :fixture_id,
             club_id = :club_id
         WHERE id = :id',
        $payload + ['file_path' => $filePath, 'id' => $mediaId]
    );

    audit_log('update_media_item', 'media_gallery', $mediaId, $existingItem, $payload + ['file_path' => $filePath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Media item updated successfully.']);
    redirect('app/modules/media/view-gallery.php?id=' . $mediaId);
}

if ($action === 'delete_media') {
    $mediaId = (int) ($_POST['id'] ?? 0);
    $existingItem = $findMediaItemOrAbort($mediaId);
    db_query('DELETE FROM media_gallery WHERE id = :id', ['id' => $mediaId]);
    delete_uploaded_file($existingItem['file_path']);
    audit_log('delete_media_item', 'media_gallery', $mediaId, $existingItem, null);
    flash('success', ['type' => 'success', 'message' => 'Media item deleted successfully.']);
    redirect('app/modules/media/index.php');
}

redirect('app/modules/media/index.php');
