<?php

namespace Modules\Cart\Controllers\Services;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Cart\Controllers\Controller;
use Modules\Cart\Models\ProductTrademarks;
use Modules\Cart\Models\Log;

class ProductTrademarksService extends Controller
{
    public function __construct()
    {
    }

    public function find(Request $request)
    {
        $filter = $this->buildFilter($request);
        $result = $this->getResult($filter);
        $this->decorResult($result);
        $pageId = $filter['page_id'];
        $pageSize = $filter['page_size'];
        unset($filter['page_id']);
        unset($filter['page_size']);
        $filter['metric'] = 'count';
        $total = $this->getResult($filter);
        $pagesCount = $this->recordsCountToPagesCount($total, $pageSize);
        $response = array(
            "status" => 'successful',
            "result" => $result,
            'pagesCount' => $pagesCount,
            'pageId' => $pageId
        );
        return response()->json($response);
    }

    protected function recordsCountToPagesCount($recordsCount, $pageSize) {
        $retVal = (int) ($recordsCount / $pageSize);
        if ($recordsCount % $pageSize > 0) {
            $retVal++;
        }
        return $retVal;
    }

    private function decorResult(&$items)
    {
    }

    private function getResult($filter)
    {
        $query = ProductTrademarks::query();
        if (isset($filter['id']) && $filter['id'] != '') {
            $query->where('id', '=', $filter['id']);
        }
        if (isset($filter['keyword']) && $filter['keyword'] != '') {
            $query->where('name', 'LIKE', '%' . $filter['keyword'] . '%');
        }
        if (isset($filter['type']) && $filter['type'] != '') {
            $query->where('type', $filter['type']);
        }
        if (isset($filter['site']) && $filter['site'] != '') {
            $query->where('site', $filter['site']);
        }
        if (isset($filter['status']) && $filter['status'] != '') {
            $query->where('status', '=', $filter['status']);
        }

        $query->orderBy('created_at', 'DESC');
        if (isset($filter['metric']) && $filter['metric'] == 'count') {
            return $query->count();
        } else {
            if (isset($filter['page_size']) && isset($filter['page_id'])) {
                $query->forPage($filter['page_id'] + 1, $filter['page_size']);
            }
            return $query->get();
        }
    }

    private function buildFilter($request)
    {
        $retVal = [];
        $columns = ['id', 'keyword', 'status', 'type', 'site'];
        foreach ($columns as $column) {
            if ($request->has($column)) {
                $retVal[$column] = $request->input($column);
            }
        }
        $retVal['page_size'] = 50;
        $retVal['page_id'] = $request->has('page_id') ? $request->input('page_id') : 0;
        return $retVal;
    }

    public function store(Request $request)
    {
        $data = $this->buildDataProductTrademarks($request);
        $email = $request->has('email') ? $request->get('email') : null;
        $log = [
            'actor_type' => 'staff',
            'actor_email' => $email,
            'target_type' => 'PRODUCT_TRADEMARKS',
            'created_at' => new \DateTime()
        ];
        $oldData = null;
        if (isset($data['id']) && !empty($data['id'])) {
            $oldData = ProductTrademarks::find($data['id']);
            ProductTrademarks::where('id', '=', $data['id'])
                ->update($data);
            $productTrademarks = ProductTrademarks::find($data['id']);
            $log['event_type'] = 'UPDATE';
        } else {
            $isExists = ProductTrademarks::where('keyword', '=', $data['keyword'])
                ->exists();
            if ($isExists) {
                $response = [
                    'status' => 'fail',
                    'message' => 'ProductTrademarks is already exists'
                ];
                return response()->json($response);
            }
            $productTrademarks = ProductTrademarks::create($data);
            $log['event_type'] = 'CREATE';
        }
        $log['target_id'] = $productTrademarks->id;
        $log['data'] = json_encode($request->all());
        Log::create($log);
        $response = [
            'status' => 'successful',
            'result' => $productTrademarks
        ];
        return response()->json($response);
    }

    private function buildDataProductTrademarks($request)
    {
        $columns = ['id', 'keyword', 'status', 'type', 'site'];
        $retVal = [];
        foreach ($columns as $column) {
            $retVal[$column] = ($request->has($column)) ? $request->get($column) : NULL;
        }
        return $retVal;
    }

    public function delete(Request $request)
    {
        $id = $request->has('id') ? $request->input('id') : [];
        $email = $request->has('email') ? $request->get('email') : null;
        $response = ['status' => 'fail'];
        if (!empty($id)) {
            $log = [
                'actor_type' => 'staff',
                'actor_email' => $email,
                'target_type' => 'PRODUCT_TRADEMARKS',
                'event_type' => 'DELETE',
                'created_at' => new \DateTime()
            ];
            ProductTrademarks::where('id', $id)
                ->delete();
            $log['target_id'] = $id;
            $log['data'] = json_encode($request->all());
            Log::create($log);
            $response['status'] = 'successful';
        }
        return response()->json($response);
    }
}
