<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;
use \Salesloo\Models\Invoice;
use \Salesloo\Models\Access;
use \Salesloo\Models\Order;

/**
 * Salesloo Dashboard
 */
class Dashboard extends Frontend
{
    private $user_id;

    /**
     * construction
     */
    public function __construct()
    {
        $this->id = 'dashboard';
        $this->template = 'dashboard.php';
        $this->target = 'user';
        $this->title = __('Dashboard', 'salesloo');

        $this->user_id = get_current_user_id();
    }

    /**
     * load
     *
     * @return void
     */
    public function load()
    {
        global $___salesloo;

        $user_id = get_current_user_id();
        $unpaid_invoices = Invoice::query('WHERE user_id = %d AND status = %s', $user_id, 'unpaid')->get();

        $invoices = [];
        foreach ($unpaid_invoices as $unpaid_invoice) {

            if ($unpaid_invoice->due_date_at && strtotime($unpaid_invoice->due_date_at) <= strtotime('now')) {
                salesloo_update_invoice_status($unpaid_invoice->ID, 'cancelled');
                continue;
            }
            $encoded_invoice_id = salesloo_encrypt($unpaid_invoice->ID);
            $payment_method = \Salesloo\Plugin::instance()->payment_method->get($unpaid_invoice->payment_method);

            $summary = $unpaid_invoice->summary;

            if ($summary['total']['converted']) {
                $total_price = [
                    'value' => salesloo_convert_price($summary['total']['converted']['value']),
                    'print' => $summary['total']['converted']['print']
                ];
            } else {
                $total_price = [
                    'value' => salesloo_convert_price($summary['total']['value']),
                    'print' => salesloo_convert_money($summary['total']['value'])
                ];
            }

            $products = [];
            foreach ($summary['products'] as $item) {
                $products[] = $item['label'];
            }

            $invoices[$unpaid_invoice->ID] = (object)[
                'number'      => $unpaid_invoice->number,
                'created_at'  => $unpaid_invoice->created_at,
                'due_date_at' => $unpaid_invoice->due_date_at,
                'total'       => $total_price,
                'products' => implode(',', $products),
                'payment'     => [
                    'link'   => salesloo_url_payment($encoded_invoice_id),
                    'method' => $payment_method->get_title()
                ]
            ];
        }

        $___salesloo['unpaid_invoices'] = $invoices;

        $query_orders = Order::query('WHERE user_id = %s AND status != %s', get_current_user_id(), 'inactive')
            ->order('ID', 'DESC')->paginate(20, salesloo_get_current_paged())
            ->get();
        $orders = [];
        if ($query_orders->found() > 0) {
            foreach ($query_orders as $order) {
                $product = salesloo_get_product($order->product_id);

                $orders[] = (object)[
                    'id' => $order->ID,
                    'code' => $order->code,
                    'product' => [
                        'thumbnail' => wp_get_attachment_image_url($product->thumbnail_id),
                        'title' => $product->title,
                    ],
                    'duration' => $product->duration,
                    'expired_at' => $order->expired_at ? date('Y-m-d', strtotime($order->expired_at)) : '~',
                    'status' => $order->status,
                    'renew' => salesloo_order_is_renewed($order->ID),
                    'access' => salesloo_url_order(salesloo_encrypt($order->ID))
                ];
            }
        }

        $___salesloo['access'] = $orders;
        $___salesloo['access_pagination'] = $query_orders->pagination(salesloo_url_dashboard());
    }
}
