<?php

namespace App\Http\Controllers;

use App\Models\Book;
use App\Models\Category;
use Illuminate\Http\Request;
use LaravelExtendedValidation\Rules\General\OrRule;
use LaravelExtendedValidation\Rules\Barcode\ISBN10;
use LaravelExtendedValidation\Rules\Barcode\ISBN13;

class BookController extends Controller {

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index() {
        $books = Book::paginate(12);
        return view('books.index', compact('books'));
    }

    /**
     * Display a search listing of the resource.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function search(Request $request) {
        $oldSearch = $request->search;
        $books = Book::where('title', 'like', '%' . $request->search . '%')
                ->orWhere('authors', 'like', '%' . $request->search . '%')
                ->orWhere('editorial', 'like', '%' . $request->search . '%')
                ->paginate(12);
        return view('books.index', compact('oldSearch', 'books'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create() {
        $categories = Category::all();
        return view('books.create', compact('categories'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request) {
        $input = $request->validate([
            'isbn' => ['required', 'string',
                new OrRule([new ISBN10(), new ISBN13()]), 'unique:books,isbn'],
            'title' => 'required|string|max:255',
            'authors' => 'required|string|max:1024',
            'year' => 'nullable|numeric|integer|digits_between:1,5',
            'editorial' => 'nullable|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,jpg,gif,png,svg,webp|max:2048',
            'document' => 'nullable|mimes:pdf|max:102400',
            'category_id' => 'nullable|numeric|integer|exists:categories,id'
        ]);

        if ($request->file('image')) {
            $image = $request->file('image');
            $imageDestinationPath = 'data/images/books/';
            $bookImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imageDestinationPath, $bookImage);
            $input['image'] = '/' . $imageDestinationPath . $bookImage;
        } else {
            unset($input['image']);
        }

        if ($request->file('document')) {
            $document = $request->file('document');
            $documentDestinationPath = 'data/documents/';
            $bookDocument = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $document->move($documentDestinationPath, $bookDocument);
            $input['document'] = '/' . $documentDestinationPath . $bookDocument;
        } else {
            unset($input['document']);
        }

        Book::create($input);

        return redirect()->route('books.index')
                        ->with('success', 'Book added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function show(Book $book) {
        return view('books.show', compact('book'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function edit(Book $book) {
        $categories = Category::all();
        return view('books.edit', compact('book', 'categories'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Book $book) {
        $input = $request->validate([
            'isbn' => ['required', 'string',
                new OrRule([new ISBN10(), new ISBN13()]),
                'unique:books,isbn,' . $book->id],
            'title' => 'required|string|max:255',
            'authors' => 'required|string|max:1024',
            'year' => 'nullable|numeric|integer|digits_between:1,5',
            'editorial' => 'nullable|string|max:255',
            'image' => 'nullable|image|mimes:jpeg,jpg,gif,png,svg,webp|max:2048',
            'document' => 'nullable|mimes:pdf|max:102400',
            'category_id' => 'nullable|numeric|integer|exists:categories,id'
        ]);

        if ($request->file('image')) {
            $image = $request->file('image');
            $imageDestinationPath = 'data/images/books/';
            $bookImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($imageDestinationPath, $bookImage);
            $input['image'] = '/' . $imageDestinationPath . $bookImage;
        } else {
            unset($input['image']);
        }

        if ($request->file('document')) {
            $document = $request->file('document');
            $documentDestinationPath = 'data/documents/';
            $bookDocument = date('YmdHis') . "."
                    . $document->getClientOriginalExtension();
            $document->move($documentDestinationPath, $bookDocument);
            $input['document'] = '/' . $documentDestinationPath . $bookDocument;
        } else {
            unset($input['document']);
        }

        $book->update($input);

        return redirect()->route('books.index')
                        ->with('success', 'Book modified successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Book  $book
     * @return \Illuminate\Http\Response
     */
    public function destroy(Book $book) {
        $book->delete();
        return redirect()->route('books.index')
                        ->with('success', 'Book removed successfully.');
    }

}
