<?php

namespace Salesloo\Frontend;

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

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

/**
 * Order
 */
class Order extends Frontend
{

    public $order;

    public $product;

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

        $order_id = salesloo_get_current_order_id();
        $order = salesloo_get_order($order_id);

        if (false == $order) {
            wp_die('invalid request', 'salesloo');
        }

        $this->order = $order;
    }

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

        $___salesloo['order'] = $this->order;

        if ($this->order->status != 'expired') {
            $access = [];
            $query_access = Access::query('WHERE order_id = %d', $this->order->ID)
                ->get();

            foreach ($query_access as $acc) {
                $post = get_post($acc->item_id);

                if (!$post) continue;

                $code = '';
                $label = 'Access';
                if ($post->post_type == 'salesloo-file') {
                    $code = $this->order->code;
                    $label = 'Download';
                }

                $access[] = [
                    'link' => get_the_permalink($acc->item_id) . $code,
                    'name' => $post->post_title,
                    'label' => apply_filters('salesloo/frontend/access/label', $label)
                ];
            }

            $___salesloo['access'] = $access;
        }

        $data = [
            'code'    => $this->order->code,
            'renewed' => salesloo_order_is_renewed($this->order->ID),
            'product' => [
                'title' => $this->order->get_product()->title,
            ],
            'affiliated_by' => $this->order->get_affiliate_id() ? get_userdata($this->order->get_affiliate_id())->user_login : 'none',
            'expired_at'    => $this->order->expired_at ? date('Y-m-d', strtotime($this->order->expired_at)) : '~'
        ];

        $___salesloo['data'] = $data;
    }
}
