<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class WatchHistory {

    public function __construct() {
        add_action('wp_ajax_movie_engine_record_watch_history', [$this, 'ajax_record_history']);
        add_action('wp_ajax_movie_engine_update_playback_progress', [$this, 'ajax_update_playback_progress']);
        add_action('wp_ajax_movie_engine_get_history_page', [$this, 'ajax_get_history_page']);
        add_shortcode('movie_engine_history', [$this, 'render_history_shortcode']);
        add_shortcode('movie_engine_full_history', [$this, 'render_full_history']);
    }


    public function ajax_update_playback_progress() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error();
        }

        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
        $progress = isset($_POST['progress']) ? floatval($_POST['progress']) : 0;
        $duration = isset($_POST['duration']) ? floatval($_POST['duration']) : 0;

        if (!$post_id) {
            wp_send_json_error();
        }

        $user_id = get_current_user_id();
        $this->save_progress($user_id, $post_id, $progress, $duration);

        wp_send_json_success();
    }

    public function save_progress($user_id, $post_id, $progress, $duration = 0) {
        $meta_key = '_movie_engine_progress_' . $post_id;
        update_user_meta($user_id, $meta_key, $progress);

        if ($duration > 0) {
            $existing_duration = get_post_meta($post_id, '_movie_engine_runtime', true);
            if (!$existing_duration) {
                update_post_meta($post_id, '_movie_engine_runtime', round($duration / 60));
            }
            update_post_meta($post_id, '_movie_engine_duration_seconds', $duration);
        }
    }

    public function ajax_get_history_page() {
        check_ajax_referer('movie_engine_nonce', 'nonce');
        $paged = isset($_REQUEST['paged']) ? absint($_REQUEST['paged']) : 1;
        $limit = isset($_REQUEST['limit']) ? absint($_REQUEST['limit']) : 12;

        echo $this->render_full_history(['limit' => $limit, 'ajax_paged' => $paged]); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        wp_die();
    }

    public static function get_progress($user_id, $post_id) {
        $meta_key = '_movie_engine_progress_' . $post_id;
        return get_user_meta($user_id, $meta_key, true);
    }


    public function ajax_record_history() {
        check_ajax_referer('movie_engine_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => esc_html__('User not logged in.', 'cine-movie-engine')]);
        }

        $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
        if (!$post_id) {
            wp_send_json_error(['message' => esc_html__('Invalid content.', 'cine-movie-engine')]);
        }

        $user_id = get_current_user_id();
        $this->add_to_history($user_id, $post_id);

        wp_send_json_success(['message' => esc_html__('History updated.', 'cine-movie-engine')]);
    }


    public function add_to_history($user_id, $post_id) {
        $history = get_user_meta($user_id, '_movie_engine_watch_history', true);
        if (!is_array($history)) {
            $history = [];
        }

        $history = array_diff($history, [$post_id]);


        array_unshift($history, $post_id);

        $history = array_slice($history, 0, 50);

        update_user_meta($user_id, '_movie_engine_watch_history', $history);
    }


    public static function get_history($user_id, $limit = 10) {
        $history = get_user_meta($user_id, '_movie_engine_watch_history', true);
        if (!is_array($history)) {
            return [];
        }

        if ($limit > 0) {
            return array_slice($history, 0, $limit);
        }

        return $history;
    }


    public static function get_watch_stats($user_id) {
        $history = get_user_meta($user_id, '_movie_engine_watch_history', true);

        $stats = [
            'episodes' => 0,
            'movies' => 0,
            'watchtime' => 0
        ];

        if (!is_array($history)) {
            $stats['watchtime_hours'] = 0;
            return $stats;
        }

        foreach ($history as $post_id) {
            $post = get_post($post_id);
            if (!$post) continue;

            if ($post->post_type === 'movie_engine_movie') {
                $stats['movies']++;

                $runtime = get_post_meta($post_id, '_movie_engine_runtime', true);
                $runtime = $runtime ? intval($runtime) : 120;
                $stats['watchtime'] += $runtime;
            } elseif ($post->post_type === 'movie_engine_episode') {
                $stats['episodes']++;

                $stats['watchtime'] += 45;
            }
        }


        $stats['watchtime_hours'] = round($stats['watchtime'] / 60, 1);

        return $stats;
    }


    public function render_history_shortcode($atts) {
        $design_settings = get_option('movie_engine_design_settings', []);
        $atts = shortcode_atts([
            'limit'          => 4,
            'title'          => esc_html__('Continue Watching', 'cine-movie-engine'),
            'view_all_link'  => '',
            'columns'        => $design_settings['archive_columns_desktop'] ?? 4,
            'columns_laptop' => $design_settings['archive_columns_laptop'] ?? 4,
            'columns_tablet' => $design_settings['archive_columns_tablet'] ?? 3,
            'columns_mobile' => $design_settings['archive_columns_mobile'] ?? 2,
        ], $atts);

        if (!is_user_logged_in()) {
            return '';
        }

        $user_id = get_current_user_id();
        $history = self::get_history($user_id, $atts['limit']);

        if (empty($history)) {
            return '';
        }

        $query = new \WP_Query([
            'post_type' => ['movie_engine_movie', 'movie_engine_episode', 'movie_engine_series'],
            'post__in' => $history,
            'posts_per_page' => $atts['limit'],
            'orderby' => 'post__in'
        ]);

        $grid_style = "style='--me-grid-columns-desktop: " . esc_attr($atts['columns']) . "; --me-grid-columns-laptop: " . esc_attr($atts['columns_laptop']) . "; --me-grid-columns-tablet: " . esc_attr($atts['columns_tablet']) . "; --me-grid-columns-mobile: " . esc_attr($atts['columns_mobile']) . "; --grid-columns: " . esc_attr($atts['columns']) . "; --grid-columns-laptop: " . esc_attr($atts['columns_laptop']) . "; --grid-columns-tablet: " . esc_attr($atts['columns_tablet']) . "; --grid-columns-mobile: " . esc_attr($atts['columns_mobile']) . ";'";

        ob_start();
?>
        <div class="movie-engine-history-section">
            <?php if ($atts['title'] || $atts['view_all_link']) : ?>
                <div class="movie-engine-section-header me-section-header">
                    <?php if ($atts['title']) : ?>
                        <h2 class="movie-engine-section-title me-section-title"><?php echo esc_html($atts['title']); ?></h2>
                    <?php endif; ?>
                    <?php if ($atts['view_all_link']) : ?>
                        <a href="<?php echo esc_url($atts['view_all_link']); ?>" class="movie-engine-view-all me-view-all">
                            <?php esc_html_e('View All', 'cine-movie-engine'); ?> <span class="fa-solid fa-angle-right"></span>
                        </a>
                    <?php endif; ?>
                </div>
            <?php endif; ?>

            <section class="movie-engine-section">
                <div class="movie-engine-items-grid movie-engine-movie-grid me-history-grid me-history-grid-dashboard" <?php echo $grid_style; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped 
                                                                                                                        ?>>
                    <?php
                    if ($query->have_posts()) {
                        while ($query->have_posts()) {
                            $query->the_post();
                            \MovieEngine\Utils\TemplateLoader::get_template_part('loop/content-movie');
                        }
                        wp_reset_postdata();
                    }
                    ?>
                </div>
            </section>
        </div>
<?php
        return ob_get_clean();
    }

    public function render_full_history($atts) {
        $design_settings = get_option('movie_engine_design_settings', []);
        $default_limit = isset($design_settings['archive_items_per_page']) ? intval($design_settings['archive_items_per_page']) : 12;

        $atts = shortcode_atts([
            'limit'          => $default_limit,
            'columns'        => $design_settings['archive_columns_desktop'] ?? 4,
            'columns_laptop' => $design_settings['archive_columns_laptop'] ?? 4,
            'columns_tablet' => $design_settings['archive_columns_tablet'] ?? 3,
            'columns_mobile' => $design_settings['archive_columns_mobile'] ?? 2,
            'ajax_paged'     => 0
        ], $atts);

        if (!is_user_logged_in()) {
            return '<p>' . esc_html__('Please login to view your history.', 'cine-movie-engine') . '</p>';
        }

        $user_id = get_current_user_id();
        $history = self::get_history($user_id, -1);

        if (empty($history)) {
            return '<div class="movie-engine-history-empty"><p>' . esc_html__('No watch history found.', 'cine-movie-engine') . '</p></div>';
        }


        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- GET pagination, nonce not used for shareable URLs
        $paged = $atts['ajax_paged'] > 0 ? $atts['ajax_paged'] : (isset($_GET['history_page']) ? absint($_GET['history_page']) : 1);

        $args = [
            'post_type' => ['movie_engine_movie', 'movie_engine_episode', 'movie_engine_series'],
            'post__in' => $history,
            'posts_per_page' => $atts['limit'],
            'paged' => $paged,
            'orderby' => 'post__in'
        ];

        $query = new \WP_Query($args);

        ob_start();
        if ($query->have_posts()) {
            if ($atts['ajax_paged'] == 0) {
                echo '<div id="movie-engine-history-container" class="movie-engine-ajax-container" data-action="movie_engine_get_history_page" data-limit="' . esc_attr($atts['limit']) . '">';
            }

            $columns        = intval($atts['columns']);
            $columns_laptop = intval($atts['columns_laptop']);
            $columns_tablet = intval($atts['columns_tablet']);
            $columns_mobile = intval($atts['columns_mobile']);
            $grid_style     = "style='--me-grid-columns-desktop: " . esc_attr($columns) . "; --me-grid-columns-laptop: " . esc_attr($columns_laptop) . "; --me-grid-columns-tablet: " . esc_attr($columns_tablet) . "; --me-grid-columns-mobile: " . esc_attr($columns_mobile) . "; --grid-columns: " . esc_attr($columns) . "; --grid-columns-laptop: " . esc_attr($columns_laptop) . "; --grid-columns-tablet: " . esc_attr($columns_tablet) . "; --grid-columns-mobile: " . esc_attr($columns_mobile) . ";'";

            echo '<div class="movie-engine-archive-wrapper"><section class="movie-engine-section"><div class="movie-engine-items-grid movie-engine-movie-grid me-history-grid me-history-grid-dashboard" ' . $grid_style . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            while ($query->have_posts()) {
                $query->the_post();
                \MovieEngine\Utils\TemplateLoader::get_template_part('loop/content-movie');
            }
            echo '</div></section>';

            echo \MovieEngine\Utils\Helpers::render_pagination($paged, $query->max_num_pages, 'history_page'); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            echo '</div>';

            if ($atts['ajax_paged'] == 0) {
                echo '</div>';
            }
            wp_reset_postdata();
        } else {
            echo '<p>' . esc_html__('No items found.', 'cine-movie-engine') . '</p>';
        }

        return ob_get_clean();
    }
}
