<?php
/**
 * Web2Print Plugin
 *
 * Routes for web-to-print functionality including custom CSS management
 */

use Kirby\Cms\Response;

Kirby::plugin('geoproject/web2print', [
    'routes' => [
        // POST: Save custom CSS
        [
            'pattern' => 'narratives/(:all)/css',
            'method' => 'POST',
            'action' => function ($pagePath) {
                // Check authentication
                if (!kirby()->user()) {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Authentication required'
                    ], 401);
                }

                // Verify CSRF token from header
                $csrfToken = kirby()->request()->header('X-CSRF');
                if (!csrf($csrfToken)) {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Invalid CSRF token'
                    ], 403);
                }

                // Get page
                $page = page($pagePath);

                if (!$page || $page->intendedTemplate()->name() !== 'narrative') {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Narrative not found'
                    ], 404);
                }

                // Get POST data
                $data = kirby()->request()->data();
                $customCss = $data['customCss'] ?? null;

                if ($customCss === null) {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'No CSS content provided'
                    ], 400);
                }

                try {
                    // Update page with new custom CSS
                    $page->update([
                        'customCss' => $customCss
                    ]);

                    // Reload page to get updated modification time
                    $page = page($pagePath);

                    // Return success with updated modified timestamp
                    return Response::json([
                        'status' => 'success',
                        'data' => [
                            'modified' => $page->modified(),
                            'modifiedFormatted' => $page->modified('d/m/Y H:i')
                        ]
                    ]);
                } catch (Exception $e) {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Failed to save CSS: ' . $e->getMessage()
                    ], 500);
                }
            }
        ],

        // GET: Load custom CSS and last modified time
        [
            'pattern' => 'narratives/(:all)/css',
            'method' => 'GET',
            'action' => function ($pagePath) {
                // Check authentication
                if (!kirby()->user()) {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Authentication required'
                    ], 401);
                }

                // Get page
                $page = page($pagePath);

                if (!$page || $page->intendedTemplate()->name() !== 'narrative') {
                    return Response::json([
                        'status' => 'error',
                        'message' => 'Narrative not found'
                    ], 404);
                }

                // Return custom CSS content and modified timestamp
                return Response::json([
                    'status' => 'success',
                    'data' => [
                        'customCss' => $page->customCss()->value() ?? '',
                        'modified' => $page->modified(),
                        'modifiedFormatted' => $page->modified('d/m/Y H:i')
                    ]
                ]);
            }
        ]
    ]
]);
