<?php

namespace MovieEngine\Emails\Types;

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

use MovieEngine\Emails\EmailBase;

class ReceiptEmail extends EmailBase {
    public function trigger($user, $transaction, $custom_to = '') {
        $subject = sprintf(
            /* translators: 1: site name */
            __('Your Receipt from %1$s', 'cine-movie-engine'),
            get_bloginfo('name')
        );

        $item_name = get_the_title($transaction->item_id);
        $currency_symbol = $transaction->currency === 'USD' ? '$' : $transaction->currency;

        $design_options = get_option('movie_engine_design_settings', []);
        $dashboard_id = !empty($design_options['dashboard_page']) ? $design_options['dashboard_page'] : 0;
        $dashboard_url = $dashboard_id ? get_permalink($dashboard_id) : home_url('/');

        $item_type = get_post_type($transaction->item_id);
        $watch_url = get_permalink($transaction->item_id);

        if (!$watch_url || is_wp_error($watch_url)) {
            $watch_url = home_url('/');
        }

        if ($item_type === 'movie_engine_plan') {
            $watch_url = $dashboard_url;
        }

        $data = [
            'user_name'      => $user->display_name,
            'item_name'      => $item_name,
            'amount'         => $currency_symbol . $transaction->amount,
            'transaction_id' => $transaction->transaction_id,
            'date'           => date_i18n(get_option('date_format'), strtotime($transaction->created_at)),
            'watch_url'      => $watch_url,
            'dashboard_url'  => $dashboard_url,
            'site_name'      => get_bloginfo('name')
        ];

        $to = !empty($custom_to) ? $custom_to : $user->user_email;
        return $this->send($to, $subject, 'receipt', $data);
    }
}
