<?php

namespace Salesloo\Notification;

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

use \Salesloo\Abstracts\Notification;
use \Salesloo\Libraries\Mail;
use \Salesloo\Models\Commission;

/**
 * Email Notification classes
 */
class Email extends Notification
{
    private $from = '';
    /**
     * construct
     *
     * @return void
     */
    public function __construct()
    {
        $this->id = 'email';
        $this->title = 'Email';

        $this->from = sprintf('%s <%s>', \salesloo_get_option('notification_email_from_name'), \salesloo_get_option('notification_email_from_email'));
    }

    /**
     * on_place_order
     *
     * @param  array $args
     * @return void
     * 
     * Available $args shortcode
     * 
     * 'number'         => Invoice Number
     * 'payment_method' => Payment method title,
     * 'products'       => Invoice Products,
     * 'summary'        => Invoice Summary,
     * 'due_date'       => Invoice due date,
     * 'customer_name'  => Customer name,
     * 'customer_email' => Customer email,
     * 'status'         => Invoice status,
     * 'payment_url'    => Payment / Invoice url,
     * 'invoice_url'    => payment url on admin area
     */

    public function on_place_order($args)
    {

        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;
        $invoice = salesloo_get_invoice($invoice_id);

        if (!$invoice) return;

        $orders = $invoice->orders();

        $customer_args = [
            'customer_name'  => $args['customer_name'],
            'customer_email'  => $args['customer_email'],
            'summary' => [
                'number'         => $args['number'],
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($args['payment_method'])->get_title(),
                'due_date_at'    => date('Y-M-d H:i', strtotime($args['due_date'])),
                'status'         => salesloo_get_invoice_statuses($args['status']),
                'products'       => $args['products'],
                'summary'        => $args['summary'],
                'invoice_url'    => $args['payment_url'],
            ]
        ];

        /**
         * send email to customer
         */
        salesloo_email('customer_place_order')
            ->to($args['customer_email'])
            ->content($customer_args)
            ->send();

        $affiliated_by = '';

        /**
         * send email to affiliate
         */
        foreach ($orders as $order) {
            $affiliate      = get_userdata($order->get_affiliate_id());

            /**
             * skip if order has no affiliate
             */
            if (!$affiliate) continue;

            $commission = Commission::query('WHERE user_id = %d AND invoice_id = %d AND order_id = %d', $affiliate->ID, $invoice_id, $order->ID)
                ->first();

            /**
             * skip if has nor commissions
             */
            if ($commission->ID <= 0) continue;

            $affiliated_by = $affiliate->user_login;

            $product = salesloo_get_product($order->product_id);

            $affiliate_args = [
                'affiliate_name'  => salesloo_user_get_name($affiliate),
                'summary' => [
                    'number'         => $args['number'],
                    'customer_name'  => $args['customer_name'],
                    'customer_email' => $args['customer_email'],
                    'product_name'   => $product->title,
                    'commission'     => salesloo_convert_money($commission->amount)
                ]
            ];

            salesloo_email('affiliate_new_lead')
                ->to($affiliate->user_email)
                ->content($affiliate_args)
                ->send();
        }

        $admin_args                  = $customer_args;
        $admin_args['invoice_number']            = $args['number'];
        $admin_args['summary']['affiliated_by']  = $affiliated_by;
        $admin_args['summary']['customer_name']  = $args['customer_name'];
        $admin_args['summary']['customer_email'] = $args['customer_email'];

        salesloo_email('admin_place_order')
            ->content($admin_args)
            ->send();

        return;
    }

    public function on_invoice_unpaid_reminder($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;
        $invoice = salesloo_get_invoice($invoice_id);

        if (!$invoice) return;

        $day = intval($args['days_to']);

        $customer = get_userdata($invoice->user_id);
        $summary = $invoice->summary;

        $products = $summary['products'];
        unset($summary['products']);
        $encoded_invoice_id = salesloo_encrypt($invoice->ID);

        $customer_args = [
            'customer_name'  => salesloo_user_get_name($customer),
            'invoice_due_date' => $invoice->due_date_at,
            'summary' => [
                'number'         => $invoice->number,
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($invoice->payment_method)->get_title(),
                'due_date_at'    => $invoice->due_date_at,
                'status'         => salesloo_get_invoice_statuses($invoice->status),
                'products'       => $products,
                'summary'        => $summary,
                'invoice_url'    => salesloo_url_payment($encoded_invoice_id),
            ]
        ];

        salesloo_email('customer_invoice_unpaid_reminder')
            ->set_day($day)
            ->to($customer->user_email)
            ->content($customer_args)
            ->send();
    }


    /**
     * on checking payment event
     *
     * @return void
     */
    public function on_invoice_checking_payment($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;
        $invoice = salesloo_get_invoice($invoice_id);

        if (!$invoice) return;

        $customer           = get_userdata($invoice->user_id);

        $customer_args = [
            'customer_name' => salesloo_user_get_name($customer),
            'summary' => [
                'number'         => $invoice->number,
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($invoice->payment_method)->get_title(),
                'amount'         => salesloo_convert_money($invoice->total)
            ]
        ];

        salesloo_email('customer_invoice_checking_payment')
            ->to($customer->user_email)
            ->content($customer_args)
            ->send();

        $admin_args = [
            'invoice_number'         => $invoice->number,
            'summary' => [
                'customer_name' => salesloo_user_get_name($customer),
                'customer_email' => $customer->user_email,
                'number'         => $invoice->number,
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($invoice->payment_method)->get_title(),
                'amount'         => salesloo_convert_money($invoice->total),
                'invoice_url'    => admin_url('admin.php?page=salesloo-payment')
            ]
        ];

        salesloo_email('admin_invoice_checking_payment')
            ->content($admin_args)
            ->send();

        return;
    }

    /**
     * on_invoice_completed event
     *
     * @param  array $args
     * @return void
     */
    public function on_invoice_completed($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;

        if (!$invoice_id) return;

        $invoice = salesloo_get_invoice($invoice_id);
        $summary = $invoice->summary;
        $orders = $invoice->orders();

        $products = $summary['products'];
        unset($summary['products']);
        $customer           = get_userdata($invoice->user_id);

        $customer_args = [
            'customer_name' => salesloo_user_get_name($customer),
            'invoice_number' => $invoice->number,
            'summary' => [
                'number'         => $invoice->number,
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($invoice->payment_method)->get_title(),
                'products'       => $products,
                'summary'        => $summary,
                'due_date_at'       => date('Y-m-d H:i', strtotime($invoice->due_date_at)),
                'status'         => salesloo_get_invoice_statuses($invoice->status),
            ]
        ];

        salesloo_email('customer_invoice_completed')
            ->to($customer->user_email)
            ->content($customer_args)
            ->send();

        $affiliated_by = '';

        foreach ($orders as $order) {
            $affiliate      = get_userdata($order->get_affiliate_id());
            if (!$affiliate) continue;

            $commission = Commission::where('user_id', $affiliate->ID, '=')
                ->andWhere('invoice_id', $invoice_id, '=')
                ->first();

            if ($commission->ID <= 0) continue;

            $affiliated_by = $affiliate->user_login;

            $product = salesloo_get_product($order->product_id);

            $affiliate_args = [
                'affiliate_name'  => salesloo_user_get_name($affiliate),
                'summary'   => [
                    'customer_name'  => salesloo_user_get_name($customer),
                    'customer_email' => $customer->user_email,
                    'product_name'   => $product->title,
                    'commission'     => salesloo_convert_money($commission->amount)
                ]
            ];

            salesloo_email('affiliate_new_sales')
                ->to($affiliate->user_email)
                ->content($affiliate_args)
                ->send();

            $affiliate_manager_args = [
                'affiliate_username'  => $affiliate->user_login,
                'product_name'   => $product->title,
                'summary' => [
                    'customer_name'  => salesloo_user_get_name($customer),
                    'customer_email' => $customer->user_email,
                    'number'         => $invoice->number,
                    'product_name'   => $product->title,
                    'commission'     => salesloo_convert_money($commission->amount)
                ]
            ];
            salesloo_email('admin_affiliate_commission')
                ->content($affiliate_manager_args)
                ->send();
        }

        $admin_args = [
            'invoice_number' => $invoice->number,
            'affiliated_by'  => $affiliated_by,
            'customer_name'  => salesloo_user_get_name($customer),
            'customer_email' => $customer->user_email,
            'summary' => [
                'customer_name'  => salesloo_user_get_name($customer),
                'customer_email' => $customer->user_email,
                'number'         => $invoice->number,
                'payment_method' => \Salesloo\Plugin::instance()->payment_method->get($invoice->payment_method)->get_title(),
                'products'       => $products,
                'summary'        => $summary,
                'due_date_at'       => date('Y-m-d H:i', strtotime($invoice->due_date_at)),
                'status'         => salesloo_get_invoice_statuses($invoice->status),
            ]
        ];
        salesloo_email('admin_invoice_completed')
            ->content($admin_args)
            ->send();

        return;
    }

    public function on_invoice_refunded($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;

        if (!$invoice_id) return;

        $invoice = salesloo_get_invoice($invoice_id);
        $summary = $invoice->summary;

        $products = $summary['products'];
        unset($summary['products']);
        $customer           = get_userdata($invoice->user_id);

        $product_titles = [];
        foreach ($products as $p) {
            $product_titles[] = $p['label'];
        }

        $customer_args = [
            'customer_name' => salesloo_user_get_name($customer),
            'invoice_number' => $invoice->number,
            'invoice_amount' => salesloo_convert_money($invoice->total),
            'product_name' => implode(', ', $product_titles),
        ];

        salesloo_email('customer_invoice_refunded')
            ->to($customer->user_email)
            ->content($customer_args)
            ->send();
    }

    public function on_invoice_cancelled($args)
    {
        $invoice_id = isset($args['invoice_id']) ? intval($args['invoice_id']) : 0;

        if (!$invoice_id) return;

        $invoice = salesloo_get_invoice($invoice_id);
        $summary = $invoice->summary;

        $products = $summary['products'];
        unset($summary['products']);
        $customer           = get_userdata($invoice->user_id);

        $product_titles = [];
        foreach ($products as $p) {
            $product_titles[] = $p['label'];
        }

        $customer_args = [
            'customer_name' => salesloo_user_get_name($customer),
            'invoice_number' => $invoice->number,
            'invoice_amount' => salesloo_convert_money($invoice->total),
            'product_name' => implode(', ', $product_titles),
        ];

        salesloo_email('customer_invoice_cancelled')
            ->to($customer->user_email)
            ->content($customer_args)
            ->send();
    }

    /**
     * on_commission_paid event
     *
     * @param  array $args
     * @return void
     */
    public function on_commission_paid($args)
    {
        $withdrawal_id = isset($args['withdrawal_id']) ? intval($args['withdrawal_id']) : 0;

        if (!$withdrawal_id) return;

        $withdrawal = salesloo_get_commission_withdrawal($withdrawal_id);
        if (false === $withdrawal) return;

        $affiliate = get_userdata($withdrawal->user_id);

        $affiliate_args = [
            'affiliate_name'    => salesloo_user_get_name($affiliate),
            'commission_amount' => salesloo_convert_money($withdrawal->amount),
            'summary'           => [
                'amount'           => salesloo_convert_money($withdrawal->amount),
                'method'           => $withdrawal->method,
                'note'             => $withdrawal->note,
                'proof_of_payment' => $withdrawal->proof_of_payment,
            ]
        ];

        salesloo_email('affiliate_commission_paid')
            ->to($affiliate->user_email)
            ->content($affiliate_args)
            ->send();

        return;
    }

    /**
     * on_order_expired event
     *
     * @param  array $args
     * @return mixed
     */
    public function on_order_expired_reminder($args)
    {
        $order_id = isset($args['order_id']) ? intval($args['order_id']) : 0;
        $order = salesloo_get_order($order_id);
        if (!$order) return;

        $day = intval($args['days_before']);

        $customer           = get_userdata($order->user_id);
        $product = salesloo_get_product($order->product_id);
        $encoded_order_id = salesloo_encrypt($order->ID);

        $args = [
            'customer_name'      => salesloo_user_get_name($customer),
            'product_name'       => $product->title,
            'order_expired_date' => $order->expired_at,
            'renew_button'       => [
                'product_name' => $product->title,
                'renew_url' => salesloo_url_renew($encoded_order_id)
            ]
        ];

        salesloo_email('customer_order_expired_reminder')
            ->set_day($day)
            ->to($customer->user_email)
            ->content($args)
            ->send();

        return;
    }


    /**
     * on_order_expired event
     *
     * @param  array $args
     * @return mixed
     */
    public function on_order_expired($args)
    {
        $order_id = isset($args['order_id']) ? intval($args['order_id']) : 0;
        $order = salesloo_get_order($order_id);
        if (!$order) return;

        $customer           = get_userdata($order->user_id);
        $product = salesloo_get_product($order->product_id);
        $encoded_order_id = salesloo_encrypt($order->ID);

        $args = [
            'customer_name'      => salesloo_user_get_name($customer),
            'product_name'       => $product->title,
            'order_expired_date' => $order->expired_at,
            'renew_button'       => [
                'product_name' => $product->title,
                'renew_url' => salesloo_url_renew($encoded_order_id)
            ]
        ];

        salesloo_email('customer_order_expired')
            ->to($customer->user_email)
            ->content($args)
            ->send();

        return;
    }

    /**
     * on_register
     *
     * @param  mixed $args
     * @return void
     */
    public function on_register($args)
    {
        $user_id = isset($args['user_id']) ? intval($args['user_id']) : 0;

        if (!$user_id) return;

        $user = get_userdata($user_id);

        $args = [
            'user_name'         => salesloo_user_get_name($user),
            'account_detail' => [
                'user_name'         => salesloo_user_get_name($user),
                'username' => $user->user_login,
                'email' => $user->user_email,
                'phone' => get_user_meta($user->ID, 'phone', true),
            ]
        ];

        if (isset($args['passwd'])) {
            $args['account_detail']['passwd'] = $args['passwd'];
        }

        salesloo_email('customer_register')
            ->to($user->user_email)
            ->content($args)
            ->send();

        salesloo_email('admin_register')
            ->content($args)
            ->send();

        return;
    }
}
