<?php

namespace Ignite\Core\Http\Controllers\Api;

use Exception;
use Illuminate\Http\Request;
use Ignite\Core\Http\Controllers\Controller;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Fluent;
use Illuminate\Support\Str;
use Ignite\Core\Contracts\Repositories\PageRepository;

class PageController extends Controller
{
    /**
     * @var PageRepository
     */
    protected $pageRepository;

    /**
     * Create a new controller instance.
     *
     * @param PageRepository $pageRepository
     */
    public function __construct(PageRepository $pageRepository)
    {
        $this->pageRepository = $pageRepository;
    }

    /**
     * List all pages.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index()
    {
        $pages = $this->pageRepository->findAll();

        return response()->json($pages->toArray());
    }

    /**
     * Reorder page positions.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function reorder()
    {
        try {
            $this->pageRepository->reorder(request()->json()->all());
            $status = 'success';
            $message = sprintf('Updated page positions successfully.');
        } catch (Exception $e) {
            $status = 'error';
            $message = $e->getMessage();
        }

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

    /**
     * Toggle an attribute.
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function toggle($id)
    {
        usleep(2000);
        try {
            $name = request()->json('name');
            $value = request()->json('value');

            $value = $this->pageRepository->toggle($id, $name, $value);

            return response()->json([
                'status' => 'success',
                'message' => sprintf('`%s` attribute updated successfully.', $name),
                'value' => $value
            ]);
        } catch (Exception $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
                'value' => null
            ]);
        }
    }
}
