<?php


namespace App\Http\Controllers;

use App\Models\Book;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Http;

class BookController extends Controller
{
    // Show all books
    public function index()
    {
        $books = Book::with('category')->get();
        return view('dashboard.books.index', compact('books'));
    }

    // Show the form for creating a new book
    public function create()
    {
        $categories = Category::all();
        return view('dashboard.books.create', compact('categories'));
    }

    // Store a new book
  public function store(Request $request)
{
    $request->validate([
        'title' => 'required|string|max:255',
        'author' => 'required|string|max:255',
        'publisher' => 'required|string|max:255',
        'file' => 'required|mimes:pdf|max:102400', // PDF file, max 100MB
        'cover_image' => 'required|image|mimes:jpeg,png,jpg|max:2048', // Image, max 2MB
        'category_id' => 'required|exists:categories,id',
    ]);

    // Create directories if they don't exist
    $publicPath = public_path();
    $filesDir = $publicPath.'/uploads/books/files';
    $imagesDir = $publicPath.'/uploads/books/cover_images';
    
    if (!file_exists($filesDir)) {
        mkdir($filesDir, 0755, true);
    }
    
    if (!file_exists($imagesDir)) {
        mkdir($imagesDir, 0755, true);
    }

    // Upload PDF file
    $file = $request->file('file');
    $fileName = time().'_'.$file->getClientOriginalName();
    $file->move($filesDir, $fileName);
    $filePath = '/uploads/books/files/'.$fileName;

    // Upload cover image
    $image = $request->file('cover_image');
    $imageName = time().'_'.$image->getClientOriginalName();
    $image->move($imagesDir, $imageName);
    $coverImagePath = '/uploads/books/cover_images/'.$imageName;

    // Create book
    Book::create([
        'title' => $request->title,
        'author' => $request->author,
        'publisher' => $request->publisher,
        'file' => $filePath,
        'cover_image' => $coverImagePath,
        'category_id' => $request->category_id,
    ]);

    return redirect()->route('books.index')->with('success', 'Book created successfully!');
}
    // Show the form for editing a book
    public function edit(Book $book)
    {
        $categories = Category::all();
        return view('dashboard.books.edit', compact('book', 'categories'));
    }

    // Update a book
  public function update(Request $request, Book $book)
{
    $request->validate([
        'title' => 'required|string|max:255',
        'author' => 'required|string|max:255',
        'publisher' => 'required|string|max:255',
        'file' => 'nullable|mimes:pdf|max:102400', // Optional PDF file, max 100MB
        'cover_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048', // Optional image, max 2MB
        'category_id' => 'required|exists:categories,id',
    ]);

    // Update PDF file if provided
    if ($request->hasFile('file')) {
        // Delete old file if exists
        if ($book->file && file_exists(public_path($book->file))) {
            unlink(public_path($book->file));
        }
        
        // Upload new file
        $file = $request->file('file');
        $fileName = time().'_'.$file->getClientOriginalName();
        $file->move(public_path('uploads/books/files'), $fileName);
        $book->file = '/uploads/books/files/'.$fileName;
    }

    // Update cover image if provided
    if ($request->hasFile('cover_image')) {
        // Delete old image if exists
        if ($book->cover_image && file_exists(public_path($book->cover_image))) {
            unlink(public_path($book->cover_image));
        }
        
        // Upload new image
        $image = $request->file('cover_image');
        $imageName = time().'_'.$image->getClientOriginalName();
        $image->move(public_path('uploads/books/cover_images'), $imageName);
        $book->cover_image = '/uploads/books/cover_images/'.$imageName;
    }

    // Update book details
    $book->update([
        'title' => $request->title,
        'author' => $request->author,
        'publisher' => $request->publisher,
        'category_id' => $request->category_id,
        // File paths are updated directly on the model above
    ]);

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

    // Delete a book
    public function destroy(Book $book)
    {
        // Delete files from storage
        Storage::disk('public')->delete($book->file);
        Storage::disk('public')->delete($book->cover_image);

        // Delete book
        $book->delete();

        return redirect()->route('books.index')->with('success', 'Book deleted successfully!');
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
public function sendRequest(Request $request)
    {
        $data = [
            'CID'          => $request->CID,
            'ZipCode'      => $request->ZipCode,
            'firstname'    => $request->firstname,
            'lastname'     => $request->lastname,
            'email'        => $request->email,
            'trusted_id'   => $request->trusted_id,
            'state'        => $request->state,
            'exposeCallerId' => $request->exposeCallerId ?? 'yes',
        ];

        $url = "https://rtb.ringba.com/v1/production/bcf09814d1864373a74a3600e88ae847.json";

        try {
            $response = Http::get($url, $data);

            // If you don’t want to show response:
            // return redirect('/mva')->with('success', 'Request sent successfully.');
            return $response;

            // If you just want to debug, uncomment:
            // dd($response->json());

        } catch (\Exception $e) {
            dd( $e);
            return redirect('/mva')->with('error', 'Something went wrong: '.$e->getMessage());
        }
    }
    
    
    
    
    
    
    
    
    
    
    
}