<?php

namespace App\Http\Controllers\SelfPaced\Dashboard;

use App\Http\Requests\SelfPaced\StoreCourseBookRequest;
use App\Http\Controllers\Controller;
use App\Models\SelfPaced\Course;
use App\Services\BookService;
use Illuminate\Http\RedirectResponse;

/**
 * BookController (Dashboard)
 *
 * Manages course book uploads and management.
 * Middleware: permission:manage self-paced book
 *
 * Requirements: 9.2, 9.3, 9.4
 */
class BookController extends Controller
{
    public function __construct(
        protected BookService $bookService
    ) {
        $this->middleware('auth');
        $this->middleware('permission:manage self-paced book');
    }

    /**
     * Upload course book
     *
     * @param StoreCourseBookRequest $request
     * @param Course $course
     * @return RedirectResponse
     */
    public function upload(StoreCourseBookRequest $request, Course $course): RedirectResponse
    {
        try {
            $this->bookService->uploadBook($course, $request->file('book'));

            // Update book fee if provided
            if ($request->has('book_fee')) {
                $course->update(['book_fee' => $request->input('book_fee')]);
            }

            return redirect()->back()->with('success', 'Course book uploaded successfully');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * Delete course book
     *
     * @param Course $course
     * @return RedirectResponse
     */
    public function destroy(Course $course): RedirectResponse
    {
        try {
            $this->bookService->deleteBook($course);
            return redirect()->back()->with('success', 'Course book deleted');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
