<?php
/* Created by ♞ Raffael Willems */
namespace Grav\Plugin;
use Grav\Common\Plugin;
use RocketTheme\Toolbox\Event\Event;

class SpotiplayPlugin extends Plugin {
    public static function getSubscribedEvents() {
        return [
            'onPagesInitialized' => ['onPagesInitialized', 0],
            'onTwigExtensions'   => ['onTwigExtensions', 0],
            'onShortcodeHandlers' => ['onShortcodeHandlers', 0],
            'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0]
        ]; 
    } 
    public function onTwigTemplatePaths()
    {
        $this->grav['twig']->twig_paths[] = __DIR__ . '/templates';
    }
    public function onTwigExtensions() { 
        require_once(__DIR__ . '/twig/SpotiplayTwigExtension.php');
        $this->grav['twig']->twig->addExtension(new \SpotiplayTwigExtension($this->grav));
    } 

    public function onShortcodeHandlers() {
        $this->grav['shortcode']->registerAllShortcodes(__DIR__ . '/shortcodes');
    }

    public function onPagesInitialized() {
        $uri = $_SERVER['REQUEST_URI'] ?? '';
        $base = '/spotiplay';
        if (stripos($uri, $base) === 0) {
            $this->handleSpotiplayEndpoint(); 
        } 
    } 

    protected function handleSpotiplayEndpoint() {
        $dataFile = GRAV_ROOT . '/user/data/spotiplay.json';
        $dir = dirname($dataFile);
        if (!is_dir($dir)) { 
            mkdir($dir, 0777, true);
        }
        $secret = $this->config->get('plugins.spotiplay.secret', '');

        // POST: write JSON payload
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if ($secret) {
                $provided = $_SERVER['HTTP_SPOTIPLAY_SECRET'] ?? '';
                if ($provided !== $secret) {
                    http_response_code(403);
                    header('Content-Type: application/json');
                    echo json_encode(['error' => 'Forbidden']);
                    exit;
                }
            }
            $input = file_get_contents('php://input');
            $payload = json_decode($input, true);
            if (is_array($payload)) {
                file_put_contents($dataFile, json_encode($payload, JSON_PRETTY_PRINT));
                header('Content-Type: application/json');
                echo json_encode(['status' => 'ok', 'saved' => $payload]);
                $this->grav['cache']->clearCache();
                exit;
            } else {
                http_response_code(400);
                header('Content-Type: application/json');
                echo json_encode(['error' => 'Invalid JSON']);
                exit;
            }
        }

        // GET: retrieve payload
        if ($_SERVER['REQUEST_METHOD'] === 'GET') { 
            header('Content-Type: application/json');
            if (file_exists($dataFile)) { 
                echo file_get_contents($dataFile);
            } else {
                echo json_encode(['status' => 'empty']);
            }
            exit;
        } 

        http_response_code(405);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Method not allowed']);
        exit;
    }
}
