<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;
use App\Models\BooksPublished;
use Illuminate\Support\Facades\Storage;

class BooksPublishedController extends Controller
{
    public function edit($id)
    {
        $booksPublished = BooksPublished::findOrFail($id);

        return view('pages.booksPublished.edit', compact('booksPublished'));
    }

    public function update(Request $request, $id)
    {
        try {
            $booksPublished = BooksPublished::findOrFail($id);

            // Validate the request data
            $validated = $request->validate([
                'author' => 'required|string',
                'title' => 'required|string',
                'publisher' => 'required|string',
                'issn' => [
                    'nullable',
                    'string',
                    'regex:/^(\d{4}-\d{3}[\dX]|\d{8}|\d{4}\s\d{3}[\dX])$/'
                ],
                'date_of_publication' => 'required|date',
                'proof_file' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
            ], [
                'issn.regex' => 'The ISSN format is invalid. It should be in the format XXXX-XXXX or XXXXXXXX.'
            ]);

            // Handle the file upload if a new file is provided
            if ($request->hasFile('proof_file')) {
                // Delete old file if exists
                if ($booksPublished->proof && Storage::disk('public')->exists($booksPublished->proof)) {
                    Storage::disk('public')->delete($booksPublished->proof);
                }

                // Extract year from start_date
                $year = date('Y', strtotime($validated['date_of_publication']));
                $username = $booksPublished->user->name;

                $originalName = $request->file('proof_file')->getClientOriginalName();
                $fileName = $username . '_' . $originalName;

                // Create path structure: year/faculty_name/BooksPublished
                $folderPath = 'proofs/' . $year . '/' . $username . '/BooksPublished';

                // Store file in the specified path
                $paperFilePath = $request->file('proof_file')->storeAs($folderPath, $fileName, 'public');

                $booksPublished->proof = $paperFilePath;
            }

            // Update other fields
            $booksPublished->author = $validated['author'];
            $booksPublished->title = $validated['title'];
            $booksPublished->publisher = $validated['publisher'];
            $booksPublished->issn = $validated['issn'];
            $booksPublished->date_of_publication = $validated['date_of_publication'];

            $booksPublished->save();

            $userRole = auth()->user()->role->name;

            if ($userRole === 'Admin') {
                return redirect()->route('admin.BooksPublishedResponses')
                    ->with('status', 'Publication updated successfully');
            } elseif ($userRole === 'Coordinator') {
                return redirect()->route('coordinator.BooksPublishedResponses')
                    ->with('status', 'Publication updated successfully');
            } else {
                // For regular users
                return redirect()->route('faculty.BooksPublishedResponses')
                    ->with('status', 'Publication updated successfully');
            }
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return back()->withErrors(['error' => 'Publication not found.']);
        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()->withErrors($e->validator)->withInput();
        } catch (\Exception $e) {
            return back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()])->withInput();
        }
    }

    public function destroy($id)
    {
        $booksPublished = BooksPublished::findOrFail($id);

        // Delete the file if it exists
        if ($booksPublished->proof && Storage::disk('public')->exists($booksPublished->proof)) {
            Storage::disk('public')->delete($booksPublished->proof);
        }

        $booksPublished->delete();

        return response()->json(['success' => 'Publication deleted successfully']);
    }

    public function getBooksPublishedResponses(Request $request)
    {
        $user = auth()->user();
        $isAdmin = $user->role->name === 'Admin';
        $isCoordinator = $user->role->name === 'Coordinator';

        // Query based on role
        if ($isAdmin) {
            // Admin sees all records
            $booksPublisheds = BooksPublished::with('user', 'department');
        } elseif ($isCoordinator) {
            // Coordinator sees only their department's records
            $booksPublisheds = BooksPublished::with('user', 'department')
                ->whereHas('user', function ($query) use ($user) {
                    $query->where('department_id', $user->department_id);
                });
        } else {
            // Regular users see only their own records
            $booksPublisheds = BooksPublished::with('user', 'department')
                ->where('faculty_id', $user->id);
        }

        // Apply filters
        if ($request->has('department_id') && !empty($request->department_id)) {
            $booksPublisheds->whereHas('department', function ($query) use ($request) {
                $query->where('id', $request->department_id);
            });
        }

        if ($request->has('publisher') && !empty($request->publisher)) {
            $booksPublisheds->where('publisher', $request->publisher);
        }

        if ($request->has('date_of_publication') && !empty($request->date_of_publication)) {
            $booksPublisheds->where('date_of_publication', $request->date_of_publication);
        }

        return DataTables::of($booksPublisheds)
            ->addColumn('user_name', function ($booksPublished) {
                return $booksPublished->user->name ?? 'Unknown';
            })
            ->addColumn('department_name', function ($booksPublished) {
                return $booksPublished->department->name ?? 'Unknown';
            })
            ->addColumn('author', function ($booksPublished) {
                return $booksPublished->author ?? 'Unknown';
            })
            ->addColumn('title', function ($booksPublished) {
                return $booksPublished->title ?? 'Unknown';
            })
            ->addColumn('publisher', function ($booksPublished) {
                return $booksPublished->publisher ?? 'Unknown';
            })
            ->addColumn('issn', function ($booksPublished) {
                return $booksPublished->issn ?? 'NA';
            })
            ->addColumn('date_of_publication', function ($booksPublished) {
                return \Carbon\Carbon::parse($booksPublished->date_of_publication)->format('d-m-Y');
            })
            ->filterColumn('user_name', function($query, $keyword) {
                $query->whereHas('user', fn($q) => $q->where('name', 'like', "%{$keyword}%"));
            })
            ->filterColumn('author', fn($query, $keyword) =>
                $query->where('author', 'like', "%{$keyword}%")
            )
            ->filterColumn('title', fn($query, $keyword) =>
                $query->where('title', 'like', "%{$keyword}%")
            )
            ->filterColumn('issn', fn($query, $keyword) =>
                $query->where('issn', 'like', "%{$keyword}%")
            )
            ->addColumn('action', function ($booksPublished) {
                $actions = [];

                // View proof button for everyone
                if ($booksPublished->proof) {
                    $actions[] = '<a href="' . asset('storage/' . $booksPublished->proof) . '" target="_blank" class="btn btn-sm btn-primary mr-1"><i class="fas fa-eye"></i></a>';
                } else {
                    $actions[] = '<span class="text-muted"><i class="fas fa-times-circle"></i></span>';
                }

                // Edit button with role-appropriate route
                $userRole = auth()->user()->role->name;
                // Determine the appropriate route based on user role
                if ($userRole === 'Admin') {
                    $editRoute = route('admin.BooksPublished.edit', $booksPublished->id);
                } elseif ($userRole === 'Coordinator') {
                    $editRoute = route('coordinator.BooksPublished.edit', $booksPublished->id);
                } else {
                    $editRoute = route('faculty.BooksPublished.edit', $booksPublished->id);
                }

                $actions[] = '<a href="' . $editRoute . '" class="btn btn-sm btn-info mx-1"><i class="fas fa-edit"></i></a>';

                $deleteRoute = route('booksPublished.destroy', $booksPublished->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $booksPublished->id . '" data-url="' . $deleteRoute . '"><i class="fas fa-trash"></i></button>';

                return implode(' ', $actions);
            })
            ->rawColumns(['action'])
            ->make(true);
    }
}
