<?php

namespace App\Http\Controllers;

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

class PublicationsController extends Controller
{
    public function edit($id)
    {
        $publication = Publication::findOrFail($id);
        $organisingInstitutes = Publication::select('organizing_institute')
            ->distinct()
            ->pluck('organizing_institute');

        return view('pages.publications.edit', compact('publication', 'organisingInstitutes'));
    }

    public function update(Request $request, $id)
    {
        $publication = Publication::findOrFail($id);

        // Validate the request data
        $validated = $request->validate([
            'first_author_name' => 'required|string',
            'co_authors' => 'nullable|string',
            'start_date' => 'required|date',
            'start_time' => 'required|date_format:H:i',
            'end_date' => 'required|date',
            'end_time' => 'required|date_format:H:i',
            'num_days' => 'required|integer',
            'activity_type' => 'required|string',
            'title' => 'required|string',
            'affiliation' => 'required|string',
            'organizing_institute' => 'required|string',
            'venue_address' => 'required|string',
            'is_peer_reviewed' => 'required|in:yes,no',
            'scopus_link' => 'nullable|url',
            'sci_link' => 'nullable|url',
            'paper_file' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
        ]);

        // Combine start date and time
        $startDateTime = date('Y-m-d H:i:s', strtotime("{$validated['start_date']} {$validated['start_time']}"));
        $endDateTime = date('Y-m-d H:i:s', strtotime("{$validated['end_date']} {$validated['end_time']}"));

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

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

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

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

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

            $publication->paper_file = $paperFilePath;
        }

        // Update other fields
        $publication->first_author_name = $validated['first_author_name'];
        $publication->co_authors = $validated['co_authors'];
        $publication->start_date = $startDateTime;
        $publication->end_date = $endDateTime;
        $publication->num_days = $validated['num_days'];
        $publication->activity_type = $validated['activity_type'];
        $publication->title = $validated['title'];
        $publication->affiliation = $validated['affiliation'];
        $publication->organizing_institute = $validated['organizing_institute'];
        $publication->venue_address = $validated['venue_address'];
        $publication->is_peer_reviewed = $validated['is_peer_reviewed'];
        $publication->scopus_link = $validated['scopus_link'];
        $publication->sci_link = $validated['sci_link'];

        $publication->save();

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

        if ($userRole === 'Admin') {
            return redirect()->route('admin.PublicationsResponses')
                ->with('status', 'Publication updated successfully');
        } elseif ($userRole === 'Coordinator') {
            return redirect()->route('coordinator.PublicationsResponses')
                ->with('status', 'Publication updated successfully');
        } else {
            // For regular users
            return redirect()->route('faculty.PublicationsResponses')
                ->with('status', 'Publication updated successfully');
        }
    }

    public function destroy($id)
    {
        $publication = Publication::findOrFail($id);

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

        $publication->delete();

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

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

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

        return DataTables::of($publications)
            ->addColumn('user_name', function ($publication) {
                return $publication->user->name ?? 'Unknown';
            })
            ->addColumn('department_name', function ($publication) {
                return $publication->department->name ?? 'Unknown';
            })
            ->addColumn('start_date', function ($publication) {
                return \Carbon\Carbon::parse($publication->start_date)->format('d-m-Y');
            })
            ->addColumn('start_time', function ($publication) {
                return \Carbon\Carbon::parse($publication->start_date)->format('h:i A');
            })
            ->addColumn('end_date', function ($publication) {
                return \Carbon\Carbon::parse($publication->end_date)->format('d-m-Y');
            })
            ->addColumn('end_time', function ($publication) {
                return \Carbon\Carbon::parse($publication->end_date)->format('h:i A');
            })
            ->addColumn('is_scopus_indexed', function ($publication) {
                return $publication->isScopusIndexed() ? 'Yes' : 'No';
            })
            ->addColumn('is_sci_indexed', function ($publication) {
                return $publication->isSciIndexed() ? 'Yes' : 'No';
            })
            ->addColumn('action', function ($publication) {
                $actions = [];

                // View paper_file button for everyone
                if ($publication->paper_file) {
                    $actions[] = '<a href="' . asset('storage/' . $publication->paper_file) . '" target="_blank" class="btn btn-sm btn-primary mr-1">View Paper</a>';
                } else {
                    $actions[] = 'No Paper';
                }

                // 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.Publications.edit', $publication->id);
                } elseif ($userRole === 'Coordinator') {
                    $editRoute = route('coordinator.Publications.edit', $publication->id);
                } else {
                    $editRoute = route('faculty.Publications.edit', $publication->id);
                }

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

                $deleteRoute = route('publications.destroy', $publication->id);
                $actions[] = '<button type="button" class="btn btn-sm btn-danger delete-btn" data-id="' . $publication->id . '" data-url="' . $deleteRoute . '">Delete</button>';

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