<?php

namespace MovieEngine\Frontend\Users;

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

class Notifications {

    public function __construct() {
        add_action('movie_engine_payment_completed', [$this, 'handle_payment_completed'], 10, 2);
        add_action('wp_login', [$this, 'handle_wp_login'], 10, 2);
        add_action('transition_post_status', [$this, 'handle_new_release_notification'], 10, 3);
    }

    public function handle_wp_login($user_login, $user) {
        if (!is_object($user)) return;

        $ua = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'] ?? ''));
        $browser = 'Unknown Browser';
        if (strpos($ua, 'Chrome') !== false) $browser = 'Chrome';
        elseif (strpos($ua, 'Firefox') !== false) $browser = 'Firefox';
        elseif (strpos($ua, 'Safari') !== false) $browser = 'Safari';
        elseif (strpos($ua, 'Edge') !== false) $browser = 'Edge';

        $os = 'Unknown OS';
        if (strpos($ua, 'Mac') !== false) $os = 'macOS';
        elseif (strpos($ua, 'Windows') !== false) $os = 'Windows';
        elseif (strpos($ua, 'Android') !== false) $os = 'Android';
        elseif (strpos($ua, 'iPhone') !== false) $os = 'iOS';

        $title = esc_html__('New Login Detected', 'cine-movie-engine');
        $message = sprintf(
            /* translators: 1: browser name, 2: operating system name */
            __('A new login was detected from %1$s on %2$s.', 'cine-movie-engine'),
            $browser,
            $os
        );

        self::add($user->ID, $title, $message, 'security');
    }

    public function handle_new_release_notification($new_status, $old_status, $post) {
        if ($new_status !== 'publish' || $old_status === 'publish') return;
        if (!in_array($post->post_type, ['movie_engine_movie', 'movie_engine_series'])) return;

        $title = esc_html__('New Release Available', 'cine-movie-engine');
        $message = sprintf(
            /* translators: %s: post title */
            __('"%s" is now live. Start watching now!', 'cine-movie-engine'),
            $post->post_title
        );

        self::add(0, $title, $message, 'info', true);
    }

    public function handle_payment_completed($session_id, $metadata) {
        $user_id = intval($metadata['user_id'] ?? 0);
        $item_id = intval($metadata['item_id'] ?? 0);
        $type = $metadata['type'] ?? '';

        if (!$user_id || !$item_id) return;

        $title = esc_html__('Content Unlocked', 'cine-movie-engine');
        $item_name = get_the_title($item_id);

        if ($type === 'plan') {
            $title = esc_html__('Membership Activated', 'cine-movie-engine');
            $message = sprintf(
                /* translators: %s: item name */
                __('Congratulations! Your "%s" membership is now active. Enjoy unlimited streaming!', 'cine-movie-engine'),
                $item_name
            );
        } elseif ($type === 'rent') {
            $message = sprintf(
                /* translators: %s: item name */
                __('You have successfully rented "%s". It is now available in your Rental Collection.', 'cine-movie-engine'),
                $item_name
            );
        } else {
            $message = sprintf(
                /* translators: %s: item name */
                __('Purchase successful! "%s" has been added to your library.', 'cine-movie-engine'),
                $item_name
            );
        }

        self::add($user_id, $title, $message, 'success');
    }

    public static function get($user_id, $limit = 20) {
        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (!is_array($notifs)) {
            $notifs = [];
        }

        $global_notifs = get_option('_movie_engine_global_notifications', []);

        $merged = $notifs;
        $existing_ids = array_column($notifs, 'id');

        foreach ($global_notifs as $gn) {
            if (!in_array($gn['id'], $existing_ids)) {
                $hidden_global = get_user_meta($user_id, '_movie_engine_hidden_global_notifs', true) ?: [];
                if (in_array($gn['id'], $hidden_global)) {
                    continue;
                }

                $read_global = get_user_meta($user_id, '_movie_engine_read_global_notifs', true) ?: [];
                $gn['read'] = in_array($gn['id'], $read_global);
                $merged[] = $gn;
            }
        }

        usort($merged, function ($a, $b) {
            return $b['date'] - $a['date'];
        });

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

        return $merged;
    }

    public static function get_unread_count($user_id) {
        $count = 0;

        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (is_array($notifs)) {
            foreach ($notifs as $n) {
                if (!$n['read']) $count++;
            }
        }

        $global_notifs = get_option('_movie_engine_global_notifications', []);
        $read_global = get_user_meta($user_id, '_movie_engine_read_global_notifs', true) ?: [];
        $hidden_global = get_user_meta($user_id, '_movie_engine_hidden_global_notifs', true) ?: [];

        foreach ($global_notifs as $gn) {
            if (in_array($gn['id'], $read_global)) continue;
            if (in_array($gn['id'], $hidden_global)) continue;

            $count++;
        }

        return $count;
    }

    public static function add($user_id, $title, $message, $type = 'info', $is_global = false) {
        $new_notif = [
            'id'       => uniqid('movie_engine_'),
            'title'    => $title,
            'message'  => $message,
            'type'     => $type,
            'date'     => time(),
            'read'     => false,
            'is_global' => $is_global
        ];

        if ($is_global) {
            $global_notifs = get_option('_movie_engine_global_notifications', []);
            array_unshift($global_notifs, $new_notif);
            $global_notifs = array_slice($global_notifs, 0, 20);
            update_option('_movie_engine_global_notifications', $global_notifs);
        } else {
            $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
            if (!is_array($notifs)) $notifs = [];

            array_unshift($notifs, $new_notif);
            $notifs = array_slice($notifs, 0, 50);
            update_user_meta($user_id, '_movie_engine_notifications', $notifs);
        }

        return $new_notif['id'];
    }

    public static function mark_as_read($user_id, $notif_id) {
        if (strpos($notif_id, 'movie_engine_') === 0) {
            $global_notifs = get_option('_movie_engine_global_notifications', []);
            $is_global = false;
            foreach ($global_notifs as $gn) {
                if ($gn['id'] === $notif_id) {
                    $is_global = true;
                    break;
                }
            }
            if ($is_global) {
                $read_global = get_user_meta($user_id, '_movie_engine_read_global_notifs', true) ?: [];
                if (!in_array($notif_id, $read_global)) {
                    $read_global[] = $notif_id;
                    update_user_meta($user_id, '_movie_engine_read_global_notifs', $read_global);
                }
                return true;
            }
        }

        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (!is_array($notifs)) return false;

        $updated = false;
        foreach ($notifs as &$n) {
            if ($n['id'] == $notif_id) {
                $n['read'] = true;
                $updated = true;
                break;
            }
        }

        if ($updated) {
            update_user_meta($user_id, '_movie_engine_notifications', $notifs);
        }

        return $updated;
    }

    public static function delete($user_id, $notif_id) {
        if (strpos($notif_id, 'movie_engine_') === 0) {
            $global_notifs = get_option('_movie_engine_global_notifications', []);
            $is_global = false;
            foreach ($global_notifs as $gn) {
                if ($gn['id'] === $notif_id) {
                    $is_global = true;
                    break;
                }
            }
            if ($is_global) {
                $hidden_global = get_user_meta($user_id, '_movie_engine_hidden_global_notifs', true) ?: [];
                if (!in_array($notif_id, $hidden_global)) {
                    $hidden_global[] = $notif_id;
                    update_user_meta($user_id, '_movie_engine_hidden_global_notifs', $hidden_global);
                }
                return true;
            }
        }

        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (!is_array($notifs)) return false;

        $count_before = count($notifs);
        $notifs = array_filter($notifs, function ($n) use ($notif_id) {
            return $n['id'] != $notif_id;
        });

        if (count($notifs) !== $count_before) {
            update_user_meta($user_id, '_movie_engine_notifications', array_values($notifs));
            return true;
        }

        return false;
    }

    public static function mark_all_read($user_id) {
        $updated = false;

        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (is_array($notifs)) {
            foreach ($notifs as &$n) {
                $n['read'] = true;
            }
            update_user_meta($user_id, '_movie_engine_notifications', $notifs);
            $updated = true;
        }

        $global_notifs = get_option('_movie_engine_global_notifications', []);
        $read_global = get_user_meta($user_id, '_movie_engine_read_global_notifs', true) ?: [];
        $new_reads = [];

        foreach ($global_notifs as $gn) {
            if (!in_array($gn['id'], $read_global)) {
                $new_reads[] = $gn['id'];
            }
        }

        if (!empty($new_reads)) {
            $read_global = array_merge($read_global, $new_reads);
            update_user_meta($user_id, '_movie_engine_read_global_notifs', $read_global);
            $updated = true;
        }

        return $updated;
    }

    public static function seed_if_empty($user_id) {
        $notifs = get_user_meta($user_id, '_movie_engine_notifications', true);
        if (empty($notifs)) {
            $transactions = apply_filters('movie_engine_user_transactions', [], $user_id, 3);
            if (!empty($transactions)) {
                foreach ($transactions as $tx) {
                    if ($tx->status === 'completed') {
                        $item_name = get_the_title($tx->item_id);
                        $type_label = ($tx->type === 'plan') ? esc_html__('Subscription', 'cine-movie-engine') : (($tx->type === 'rent') ? esc_html__('Rental', 'cine-movie-engine') : esc_html__('Purchase', 'cine-movie-engine'));
                        self::add($user_id, sprintf(
                            /* translators: %s: type label */
                            __('%s Successful', 'cine-movie-engine'),
                            $type_label
                        ), sprintf(
                            /* translators: 1: type label, 2: item name */
                            __('Your %1$s for "%2$s" has been confirmed. You now have full access!', 'cine-movie-engine'),
                            strtolower($type_label),
                            $item_name
                        ), 'success');
                    }
                }
            }
            self::add($user_id, esc_html__('Welcome to MovieEngine', 'cine-movie-engine'), esc_html__('Thank you for joining our platform. Start exploring movies and series now!', 'cine-movie-engine'), 'success');
            self::add($user_id, esc_html__('Security Tip', 'cine-movie-engine'), esc_html__('Make sure to enable two-factor authentication for better security.', 'cine-movie-engine'), 'security');
            self::add($user_id, esc_html__('New Release Alert', 'cine-movie-engine'), esc_html__('"Breaking Bad" Season 5 is now available in 4K HDR. Watch now!', 'cine-movie-engine'), 'info');
        }
    }
}
