<?php

namespace App\Http\Controllers;

use App\Models\Book;
use App\Models\BookMeta;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class BookController extends Controller
{
    public function index()
    {
        $principal = 'principals/' . Auth::user()->email;

        $books = Book::query()
            ->join('addressbook_meta as meta', 'meta.addressbook_id', '=', 'addressbooks.id')
            ->where('principaluri', $principal)
            ->select('addressbooks.*', 'meta.color', 'meta.is_default')
            ->get();

        return view('book.index', compact('books'));
    }

    public function create()
    {
        return view('book.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'displayname' => 'required|string|max:100',
            'color' => 'nullable|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        $principal = 'principals/' . Auth::user()->email;

        $id = Book::insertGetId([
            'principaluri' => $principal,
            'uri' => (string) Str::uuid(),
            'displayname' => $data['displayname'],
        ]);

        BookMeta::create([
            'book_id' => $id,
            'color' => $data['color'] ?? '#cccccc',
            'is_default' => false,
        ]);

        return redirect()->route('book.index');
    }

    public function show(Book $book)
    {
        $this->authorize('view', $book);

        $book->load('meta', 'cards');

        return view('book.show', compact('book'));
    }

    public function edit(Book $book)
    {
        $book->load('meta');

        return view('book.edit', compact('book'));
    }

    public function update(Request $request, Book $book)
    {
        $data = $request->validate([
            'displayname' => 'required|string|max:100',
            'color' => 'nullable|regex:/^#[0-9A-Fa-f]{6}$/',
        ]);

        $book->update([
            'displayname' => $data['displayname'],
        ]);

        $book->meta()->updateOrCreate([], [
            'color' => $data['color'] ?? '#cccccc',
        ]);

        return redirect()->route('book.index')->with('toast', 'Address Book updated.');
    }
}
