<?php

namespace App\Http\Controllers;

use App\Category;
use App\Http\Resources\FaqResource;
use App\Photo;
use App\ProjectUser;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Validator;

class FaqController extends Controller
{
    const ITEM_PER_PAGE = 20;
    private $user;

    public function __construct()
    {
        $this->user = auth('api')->user();
    }

    public function index(Request $request)
    {
        $params = $request->all();
        $list = Photo::select('*');
        $limit = Arr::get($params, 'limit', static::ITEM_PER_PAGE);
        $id = Arr::get($params, 'id', '');
        $projectId = Arr::get($params, 'projectId', '');
        $status = Arr::get($params, 'status', '');
        $keyword = Arr::get($params, 'keyword', '');

        if ($this->user->hasRole(['customer'])) {
            $projectIds = Category::where('is_activated', true)->where('is_deleted', false)->where('user_id', $this->user->id)->pluck('id');
            $list->whereIn('project_id', $projectIds);
        }

        if ($this->user->hasRole(['user'])) {
            $list->where('assigned_id', $this->user->id);
        }

        if ($id != null && $id != "") {
            $list->where('id', $id);
        }

        if ($projectId != null && $projectId != "") {
            $list->where('project_id', $projectId);
        }

        if ($keyword != null && $keyword != "") {
            $projectRsIds = Category::where('is_activated', true)->where('is_deleted', false)->where('name', 'like', "%$keyword%")->pluck('id')->toArray();
            $list->where(function ($query) use ($keyword, $projectRsIds) {
                $query->where('name', 'like', "%$keyword%")
                    ->orWhereIn('project_id', $projectRsIds);
            });
        }

        if ($status != null && $status != "") {
            if ($status == 5 || $status == "5") {
                $list->where(function ($query) use ($status) {
                    $query->where('status', 0)
                        ->orWhere('status', 3);
                });
            } else {
                $list->where('status', $status);
            }
        }

        $list->orderBy('project_id', 'DESC')->orderBy('name', 'ASC');

        return FaqResource::collection($list->paginate($limit));
    }

    public function statistic()
    {
        //{ 0: 'Progressing', 1: 'Confirm', 2: 'Done', 3: 'Error' };
        $progressing = Photo::where('status', 0);
        $confirm = Photo::where('status', 1);
        $done = Photo::where('status', 2);
        $error = Photo::where('status', 3);

        if ($this->user->hasRole(['customer'])) {
            $projectIds = Category::where('is_activated', true)->where('is_deleted', false)->where('user_id', $this->user->id)->pluck('id');
            $progressing->whereIn('project_id', $projectIds);
            $confirm->whereIn('project_id', $projectIds);
            $done->whereIn('project_id', $projectIds);
            $error->whereIn('project_id', $projectIds);
        }

        if ($this->user->hasRole(['user'])) {
            $progressing->where('assigned_id', $this->user->id);
            $confirm->where('assigned_id', $this->user->id);
            $done->where('assigned_id', $this->user->id);
            $error->where('assigned_id', $this->user->id);
        }

        $progressing = $progressing->count();
        $confirm = $confirm->count();
        $done = $done->count();
        $error = $error->count();
        $total = $progressing + $confirm + $done + $error;

        return response()->json([
            'total'       => $total,
            'progressing' => $progressing,
            'confirm'     => $confirm,
            'done'        => $done,
            'error'       => $error,
        ], 200);
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), ['projectId' => ['required']]);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);
        $params = $request->all();
        $userId = $params['user_id'];

        $countMax = Photo::where('project_id', $params['projectId'])->count();
        $name = "No." . ($countMax + 1);
        if ($userId == null || $userId == "") {
            $userListIds = ProjectUser::where('category_id', $params['projectId'])->pluck('user_id')->toArray();
            if (count($userListIds) > 0) {
                $randKey = array_rand($userListIds, 1);
                $userId = $userListIds[$randKey];
            }
        }

        $status = 0;
        if ($this->user->hasRole(['user']) && $params['image'] != null && $params['image'] != "") {
            $status = 1;
        }

        Photo::create([
            'code'        => rand(9999, 9999999),
            'project_id'  => $params['projectId'],
            'name'        => $name,
            'address'     => $params['address'],
            'image'       => $params['image'],
            'assigned_id' => $userId,
            'user_id'     => auth('api')->user()->id,
            'status'      => $status,
            'created_at'  => date('Y-m-d H:i:s'),
            'updated_at'  => date('Y-m-d H:i:s'),
        ]);

        return response()->json(null, 200);
    }

    public function update(Request $request, $id = 0)
    {
        $validator = Validator::make($request->all(), ['image' => ['required']]);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);

        $faq = Photo::where('id', $id)->first();
        if (!isset($faq)) return response()->json(['errors' => 'Poster is not valid'], 403);

        $params = $request->all();
        $status = $faq->status;
        if ($status == 0 || $status == '0' || $status == 3 || $status == "3") $status = 1;

        $faq->update([
            'image'      => $params['image'],
            'status'     => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        return response()->json(null, 204);
    }

    public function updateStatus(Request $request, $id = 0)
    {
        $validator = Validator::make($request->all(), ['status' => ['required']]);
        if ($validator->fails()) return response()->json(['errors' => $validator->errors()], 403);

        $faq = Photo::where('id', $id)->first();
        if (!isset($faq)) return response()->json(['errors' => 'Poster is not valid'], 403);
        $status = $request->get('status');

        $faq->update([
            'status'     => $status,
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        return response()->json(['status' => 'success', 'message' => ''], 200);
    }

    public function updateReset($id = 0)
    {
        $faq = Photo::where('id', $id)->first();
        if (!isset($faq)) return response()->json(['errors' => 'Photo is not valid'], 403);

        $faq->update([
            'assigned_id' => null,
            'rs_status'   => 1,
            'updated_at'  => date('Y-m-d H:i:s')
        ]);

        return response()->json(['status' => 'success', 'message' => ''], 200);
    }

    public function base64_to_png($base64_string, $output_file)
    {
        $ifp = fopen($output_file, 'wb');
        $data = explode(',', $base64_string);
        fwrite($ifp, base64_decode($data[1]));
        fclose($ifp);

        return $output_file;
    }
}
