<?php

namespace App\Http\Controllers;

use Edwin404\Base\Support\ModelHelper;
use Edwin404\Base\Support\PageHelper;
use Edwin404\Base\Support\Response;
use Edwin404\Forum\Services\ForumService;
use Illuminate\Support\Facades\Input;

class ProductController extends BaseController
{
    public function index()
    {
        return $this->category(0);
    }

    public function category($categoryId)
    {
        $categoryId = intval($categoryId);

        $page = Input::get('page');
        $pageSize = 10;

        $categories = ModelHelper::model('product_category')->orderBy('sort', 'asc')->get()->toArray();
        $currentCategory = null;
        foreach ($categories as $category) {
            if ($category['id'] == $categoryId) {
                $currentCategory = $category;
                break;
            }
        }

        $option = [];
        $option['order'] = ['id', 'desc'];
        if ($categoryId) {
            $option['where'] = ['categoryId' => $categoryId];
        }
        $productPaginate = ModelHelper::modelPaginate('product', $page, $pageSize, $option);

        $products = $productPaginate['records'];
        $pageHtml = PageHelper::render($productPaginate['total'], $pageSize, $page, '/product/category/' . $categoryId . '?page={page}');

        $viewData = [];
        $viewData['categories'] = $categories;
        $viewData['currentCategory'] = $currentCategory;
        $viewData['products'] = $products;
        $viewData['pageHtml'] = $pageHtml;
        $viewData['background'] = ModelHelper::load('background', ['type' => 'product_list']);
        return $this->_view('productCategory', $viewData);
    }

    public function view($productId)
    {
        $productId = intval($productId);
        $product = ModelHelper::load('product', ['id' => $productId]);
        if (empty($product)) {
            return Response::send(-1, '产品未找到');
        }

        $categories = ModelHelper::model('product_category')->orderBy('sort', 'asc')->get()->toArray();
        $currentCategory = null;
        foreach ($categories as $category) {
            if ($category['id'] == $product['categoryId']) {
                $currentCategory = $category;
                break;
            }
        }

        $viewData = [];
        $viewData['categories'] = $categories;
        $viewData['product'] = $product;
        $viewData['currentCategory'] = $currentCategory;
        $viewData['background'] = ModelHelper::load('background', ['type' => 'product_view']);
        return $this->_view('productView', $viewData);
    }

}
