<?php

namespace App\Http\Controllers;

use App\Models\Books;
use App\Models\Borrow;
use App\Models\Category;
use App\Exports\BooksExport;
use App\Imports\BooksImport;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Gate;
use Carbon\Carbon;


class BooksController extends Controller
{
    public function index()
    {
        $title = '';
        $books = Books::where('title', 'like', '%' . request('search') . '%')
            ->orWhere('penulis', 'like', '%' . request('search') . '%')
            ->get();

        if (request('search')) {
            $title = 'Hasil pencarian dari ' . request('search') . ' | ';
        }
        if (Gate::allows('isUser')) {
            $title .= 'Overview';
        }
        if (Gate::allows('isAdmin')) {
            $title .= 'All Book';
        }
        return view('book.books', [
            'title' => $title,
            'books' => $books
        ]);
    }

    public function create()
    {
        return view('book.create', [
            'title' => 'Add a new book',
            'categories' => Category::all(),
        ]);
    }

    public function store(Request $request)
    {
        $request['user_id'] = auth()->user()->id;
        $request['slug'] = Str::of($request->title)->slug('-');
        $validateData = $request->validate([
            'title' => 'required|max:255',
            'slug' => 'required|unique:books',
            'kode_buku' => 'required|unique:books',
            'category_id' => 'required',
            'user_id' => 'required',
            'penulis' => 'required',
            'description' => 'required',
            'image' => 'required|image',
            'pdf' => 'nullable|mimes:pdf|max:10000',
            'penerbit' => 'required',
            'stok' => 'required',
            'thn_terbit' => 'required',
            'edisi' => 'nullable|string',
            'tempat_terbit' => 'nullable|string',
        ]);

        $fileName = time() . '_' . $request->file('image')->getClientOriginalName();
        $validateData['image'] = $request->file('image')->storeAs('image_post', $fileName, 'public');

        if ($request->file('pdf')) {
            $pdfName = time() . '_' . $request->file('pdf')->getClientOriginalName();
            $validateData['pdf'] = $request->file('pdf')->storeAs('app/pdf-path', $pdfName, 'public');
        }

        $store = Books::create($validateData);
        return $store ? redirect()->route('books.index')->with('success', 'New post has been added!')
                      : redirect()->route('books.index')->with('failed', 'New post failed to add!');
    }

    public function show(Books $book)
    {
        return view('book.show', [
            'title' => $book->title,
            'book' => $book
        ]);
    }

    public function edit(Books $book)
    {
        return view('book.edit', [
            'title' => $book->title,
            'book' => $book,
            'categories' => Category::all(),
        ]);
    }

    public function update(Request $request, Books $book)
    {
        $request['user_id'] = auth()->user()->id;
        $validate = [
            'title' => 'sometimes|required|max:255',
            'slug' => 'sometimes|required',
            'kode_buku' => 'sometimes|required',
            'category_id' => 'sometimes|required',
            'user_id' => 'sometimes|required',
            'penulis' => 'sometimes|required',
            'description' => 'sometimes|required',
            'image' => 'sometimes|image',
            'pdf' => 'nullable|mimes:pdf|max:10000',
            'penerbit' => 'sometimes|required',
            'stok' => 'sometimes|required',
            'thn_terbit' => 'sometimes|required',
            'edisi' => 'nullable|string',
            'tempat_terbit' => 'nullable|string',
        ];

        $slug = Str::of($request->title)->slug('-');
        if ($slug != $book->slug) {
            $validate['slug'] = 'sometimes|required|unique:books';
            $request['slug'] = $slug;
        }
        if ($request['kode_buku'] != $book->kode_buku) {
            $validate['kode_buku'] = 'sometimes|required|unique:books';
        }
        $validateData = $request->validate($validate);

        if ($request->file('image')) {
            $fileName = time() . '_' . $request->file('image')->getClientOriginalName();
            $validateData['image'] = $request->file('image')->storeAs('image_post', $fileName, 'public');
        }

        if ($request->file('pdf')) {
            $pdfName = time() . '_' . $request->file('pdf')->getClientOriginalName();
            $validateData['pdf'] = $request->file('pdf')->storeAs('app/pdf-path', $pdfName, 'public');
        }

        $update = $book->update($validateData);
        return $update ? redirect()->route('books.index')->with('success', 'Book has been updated!')
                      : redirect()->route('books.index')->with('failed', 'Book update failed!');
    }

    public function destroy($id)
    {
        Books::destroy($id);
        Borrow::where('book_id', $id)->delete();
        return redirect()->route('books.index')->with('successDelete', 'Book has been deleted!');
    }

    public function pdfView($id)
    {
        $book = Books::findOrFail($id);

        if ($book->pdf && Storage::disk('public')->exists($book->pdf)) {
            return view('book.pdf_viewer', [
                'pdfUrl' => Storage::url($book->pdf),
                'title' => $book->title
            ]);
        }

        return redirect()->route('books.index')->with('failed', 'PDF not found!');
    }

    public function readPdf(Books $book)
    {
        return view('book.readPdf', [
            'title' => 'Read PDF - ' . $book->title,
            'book' => $book
        ]);
    }

    // Metode untuk mengekspor buku ke CSV
    public function exportCsv()
    {
        $books = Books::all();
        $csvFileName = 'books_' . date('Y-m-d_H-i-s') . '.csv';
        
        // Membuat file CSV
        $handle = fopen(storage_path('app/' . $csvFileName), 'w+');
        
        // Menulis header CSV
        fputcsv($handle, ['ID', 'Kode Buku', 'Title', 'Penulis', 'Penerbit', 'Category', 'Jumlah Buku', 'Thn Terbit', 'Tempat Terbit', 'Edisi', 'Deskripsi', 'File PDF', 'Sampul', 'User ID']);
        
        // Menulis data buku ke CSV
        foreach ($books as $book) {
            fputcsv($handle, [
                $book->id,
                $book->kode_buku,
                $book->title,
                $book->penulis,
                $book->penerbit,
                $book->category_id,
                $book->stok,
                $book->thn_terbit,
                $book->tempat_terbit,
                $book->edisi,
                $book->description,
                $book->pdf,
                $book->image,
                $book->user_id,
            ]);
        }
        
        fclose($handle);
        
        return response()->download(storage_path('app/' . $csvFileName));
    }

    public function importCsv(Request $request)
{
    // Validasi file agar hanya menerima CSV
    $request->validate([
        'file' => 'required|mimes:csv,txt'
    ]);

    try {
        // Mendapatkan path file dan memeriksa keberadaan file
        $path = $request->file('file')->getRealPath();
        if (!file_exists($path)) {
            return redirect()->route('books.index')->with('failed', 'File not found.');
        }

        // Membaca data CSV
        $data = array_map('str_getcsv', file($path));

        // Hapus header CSV
        $header = array_shift($data);

        // Pengecekan jumlah kolom yang sesuai
        if (count($header) < 10) {
            return redirect()->route('books.index')->with('failed', 'CSV format is incorrect.');
        }

        // Menggunakan transaksi untuk menghindari kegagalan parsial
        \DB::beginTransaction();

        // Loop untuk memasukkan data ke dalam database
        foreach ($data as $row) {
            if (count($row) < 10) {
                continue; // Lewati baris yang tidak memenuhi jumlah kolom
            }

            // Coba simpan setiap entri buku
            Books::create([
                'kode_buku' => $row[1] ?? null,
                'title' => $row[2] ?? null,
                'penulis' => $row[3] ?? null,
                'penerbit' => $row[4] ?? null,
                'category_id' => $row[5] ?? null,
                'stok' => $row[6] ?? 0,
                'thn_terbit' => $row[7] ?? null,
                'tempat_terbit' => $row[8] ?? null,
                'edisi' => $row[9] ?? null,
                'slug' => Str::slug($row[1] ?? ''),
                'description' => $row[10] ?? null,
                'pdf' => $row[11] ?? null,
                'image' => $row[12] ?? 'default.jpg',
                'user_id' => auth()->id() ?? 1,
            ]);
        }

        \DB::commit();

        return redirect()->route('books.index')->with('success', 'Books imported successfully.');
    } catch (\Exception $e) {
        \DB::rollBack();

        // Logging error untuk debugging
        \Log::error("Error importing books: " . $e->getMessage());

        return redirect()->route('books.index')->with('failed', 'An error occurred during import.');
    }
}


}
