<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;
use \Salesloo\Models\Product as Model_Product;


/**
 * Product page
 */
class Product extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id       = 'product';
        $this->template = 'product.php';
        $this->target   = 'user';
        $this->title    = 'Products';
    }

    /**
     * handle action process
     */
    public function process_action($req)
    {
    }


    /**
     * handle load
     */
    public function load()
    {
        global $___salesloo;

        $query = "WHERE status = 'active'";

        if (salesloo_get_current_search()) {
            $keyword = salesloo_get_current_search();
            $query .= "AND title = '$keyword'";
        }
        $active_products = Model_Product::query($query)
            ->order('ID', 'DESC')
            ->paginate(20, salesloo_get_current_paged())
            ->get();

        $products = [];
        foreach ($active_products as $product) {

            $products[$product->ID] = (object)[
                'slug'        => $product->slug,
                'title'       => $product->title,
                'price'       => salesloo_convert_money($product->get_price()),
                'thumbnail'   => wp_get_attachment_url($product->thumbnail_id),
                'description' => wp_kses_post($product->description),
                'duration'    => salesloo_translate_product_duration($product->duration),
                'buy'         => salesloo_url_checkout($product->slug),
                'salespage'   => salesloo_get_product_meta($product->ID, 'salespage_url', true),
            ];
        }

        $___salesloo['collection'] = $active_products;
        $___salesloo['products'] = $products;
    }
}
