<?php
namespace OxygenApp\Controllers;

if ( ! defined( 'ABSPATH' ) ) exit;

use OxygenApp\Common\Guards\Guards;
use OxygenApp\Common\Guards\CreatePlaylistGuard;
use OxygenApp\Common\Guards\GetPlaylistsGuard;
use OxygenApp\Common\Guards\DeletePlaylistGuard;
use OxygenApp\Common\Guards\UpdatePlaylistGuard;
use OxygenApp\Models\User;
use OxygenApp\Utils\UserUtil;
use OxygenApp\Utils\Utils;
use OxygenApp\Utils\Sanitizer;

class PlaylistCtrl {

    static function create(\WP_REST_Request $request): \WP_REST_Response {

        $guardResult = Guards::use($request, CreatePlaylistGuard::class);
        if ($guardResult !== true) {
            return $guardResult;
        }

        $playlist = $request->get_param('playlist');
        $playlistClean = [
            'name' => $playlist['name'] ?? '',
            'backgroundId' => $playlist['backgroundId'] ?? -1,
            'id' => Utils::generateUniqueId(),
            'sounds' => $playlist['sounds'],
        ];

        $userSessionData = UserUtil::getInstance()->getUserFromSession();
        $user_id = $userSessionData['user_id'] ?? '';
        $user = new User();
        $existingPlaylists = $user->getUserMetaByKey($user_id, 'playlists', []);
        $newPlaylists = [$playlistClean, ...$existingPlaylists];
        $user->updateUserMeta($user_id, 'playlists', Sanitizer::sanitize_data($newPlaylists));

        return new \WP_REST_Response(['status' => 'success', 'playlist' => $playlistClean], 200);
    }

    static function getPlaylists(\WP_REST_Request $request): \WP_REST_Response {

        $guardResult = Guards::use($request, GetPlaylistsGuard::class);
        if ($guardResult !== true) {
            return $guardResult;
        }

        $userSessionData = UserUtil::getInstance()->getUserFromSession();
        $user_id = $userSessionData['user_id'] ?? '';
        $user = new User();
        $userData = $user->findById($user_id);
        if (!$userData) {
            return new \WP_REST_Response(['message' => esc_html__('User does not exist.', 'oxyleaf-app-working-and-relaxing-app')], 403);
        }

        $playlists = $user->getUserMetaByKey($user_id, 'playlists', []);
        
        $escapedPlaylists = array_map(function($playlist) {
            if (isset($playlist['name'])) {
                $playlist['name'] = esc_html($playlist['name']);
            }
            return $playlist;
        }, $playlists);
        
        return new \WP_REST_Response(['status' => 'success', 'playlists' => $escapedPlaylists], 200);
    }

    static function delete(\WP_REST_Request $request): \WP_REST_Response {

        $guardResult = Guards::use($request, DeletePlaylistGuard::class);
        if ($guardResult !== true) {
            return $guardResult;
        }

        $playlistData = $request->get_param('playlistData');

        $userSessionData = UserUtil::getInstance()->getUserFromSession();
        $user_id = $userSessionData['user_id'] ?? '';
        $user = new User();
        $existingPlaylists = $user->getUserMetaByKey($user_id, 'playlists', []);

        $playlistId = $playlistData['playlistId'];


        foreach ($existingPlaylists as $key => $playlist) {
            if (isset($playlist['id']) && $playlist['id'] === $playlistId) {
                unset($existingPlaylists[$key]);
                break;
            }
        }
        $existingPlaylists = array_values($existingPlaylists);
        $user->updateUserMeta($user_id, 'playlists', Sanitizer::sanitize_data($existingPlaylists));


        return new \WP_REST_Response(['status' => 'success'], 200);
    }

    static function update(\WP_REST_Request $request): \WP_REST_Response {

        $guardResult = Guards::use($request, UpdatePlaylistGuard::class);
        if ($guardResult !== true) {
            return $guardResult;
        }

        $playlist = $request->get_param('playlist');
        $playlistClean = [
            'name' => $playlist['name'] ?? '',
            'backgroundId' => $playlist['backgroundId'] ?? -1,
            'id' => $playlist['id'],
            'sounds' => $playlist['sounds'],
        ];

        $userSessionData = UserUtil::getInstance()->getUserFromSession();
        $user_id = $userSessionData['user_id'] ?? '';
        $user = new User();

        $existingPlaylists = $user->getUserMetaByKey($user_id, 'playlists', []);
        $ids = array_column($existingPlaylists, 'id');
        $index = array_search($playlist['id'], $ids);

        if ($index === false) {
            return new \WP_REST_Response(['status' => 'fail', 'message' => esc_html__('Missing playlist', 'oxyleaf-app-working-and-relaxing-app')], 500);
        }

        $existingPlaylists[$index] = Sanitizer::sanitize_data($playlistClean);
        $user->updateUserMeta($user_id, 'playlists', $existingPlaylists);


        return new \WP_REST_Response(['status' => 'success', 'playlist' => $playlistClean], 200);
    }
}