<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ActivitiesAttended;
use App\Models\ActivitiesOrganised;
use App\Models\BooksPublished;
use App\Models\Department;
use App\Models\ExternalEngagement;
use App\Models\IvOrganised;
use App\Models\OnlineCourse;
use App\Models\Patent;
use App\Models\Publication;

class FacultyController extends Controller
{
    // Faculty dashboard (optional)
    public function index()
    {
        return view('faculty.dashboard');
    }

    // Faculty response form
    public function ActivitiesAttendedForm()
    {
        // Fetch unique organising institutes
        $organisingInstitutes = ActivitiesAttended::select('organising_institute')
            ->distinct()
            ->pluck('organising_institute');

        // Pass the data to the view
        return view('faculty.activities-attended-form', compact('organisingInstitutes'));
    }

    public function viewActivitiesAttendedResponses()
    {
        $departments = Department::all();
        return view('pages.activities-attended.index', compact('departments'));
    }
    public function ActivitiesOrganisedForm()
    {
        // Logic to show the response form
        return view('faculty.activities-organised-form');
    }

    public function viewActivitiesOrganisedResponses()
    {
        $departments = Department::all();
        return view('pages.activities-organised.index', compact('departments'));
    }

    public function IvOrganisedForm()
    {
        // Logic to show the response form
        return view('faculty.iv-organised-form');
    }

    public function viewIvOrganisedResponses()
    {
        $departments = Department::all();
        return view('pages.iv-organised.index', compact('departments'));
    }

    public function PublicationsForm()
    {
        $organisingInstitutes = Publication::select('organizing_institute')
            ->distinct()
            ->pluck('organizing_institute');
        // Logic to show the response form
        return view('faculty.publications-form', compact('organisingInstitutes'));
    }

    public function viewPublicationsResponses()
    {
        $user = auth()->user();

        \Log::info('FacultyController: scholar_url = ' . ($user->scholar_url ?? 'NULL'));

        return view('pages.publications.index', [
            'scholarUrl' => $user->scholar_url,
        ]);

    }

    public function BooksPublishedForm()
    {
        // Logic to show the response form
        return view('faculty.booksPublished-form');
    }

    public function viewBooksPublishedResponses()
    {
        $departments = Department::all();
        return view('pages.booksPublished.index', compact('departments'));
    }

    public function ExternalEngagementForm()
    {
        // Logic to show the response form
        return view('faculty.externalEngagement-form');
    }

    public function viewExternalEngagementResponses()
    {
        $departments = Department::all();
        return view('pages.externalEngagement.index', compact('departments'));
    }

    public function OnlineCoursesForm()
    {
        // Logic to show the response form
        return view('faculty.onlineCourses-form');
    }

    public function viewOnlineCoursesResponses()
    {
        $departments = Department::all();
        return view('pages.onlineCourses.index', compact('departments'));
    }

    public function PatentsForm()
    {
        // Logic to show the response form
        return view('faculty.patents-form');
    }

    public function viewPatentsResponses()
    {
        $departments = Department::all();
        return view('pages.patents.index', compact('departments'));
    }



    public function ActivitiesAttendedFormResponse(Request $request)
    {
        try {
            // Validate the request data
            $validated = $request->validate([
                'title' => 'required|string',
                'organising_institute' => 'required|string',
                'address' => 'required|string',
                // 'department' => 'required|string',
                // 'faculty_name' => 'required|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',
                'category' => 'required|string',
                'level' => 'required|string',
                'proof' => '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
            $proofPath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

                // Create path structure: year/faculty_name
                $folderPath = 'proofs/' . $year . '/' . $userId . '_' . $username . '/Activities-Attended';

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

            // Save the response to the database
            // dd($validated['organising_institute']);
            ActivitiesAttended::create([
                'title' => $validated['title'],
                'organising_institute' => $validated['organising_institute'],
                'address' => $validated['address'],
                'department_id' => auth()->user()->department->id,
                'faculty_id' => auth()->user()->id,
                // 'faculty_name' => $validated['faculty_name'],
                'start_date' => $startDateTime,
                'end_date' => $endDateTime,
                'num_days' => $validated['num_days'],
                'activity_type' => $validated['activity_type'],
                'category' => $validated['category'],
                'level' => $validated['level'],
                'proof' => $proofPath,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Response submitted successfully');
        } catch (\Exception $e) {
            // Handle the exception and provide an error message
            dd($e);
            return back()->withErrors('An error occurred while submitting your response: ' . $e->getMessage());
        }
    }

    public function ActivitiesOrganisedFormResponse(Request $request)
    {
        try {
            // Validate the request data
            $validated = $request->validate([
                'title' => 'required|string',
                'resource_person_name' => 'required|string',
                'resource_person_organization' => 'required|string',
                'target_audience' => 'required|string',
                'number_of_participants' => 'required|integer',
                'objective' => 'required|string',
                'outcomes' => 'required|string',
                'venue' => 'required|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',
                'category' => 'required|string',
                'level' => 'required|string',
                'proof' => '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
            $proofPath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

                // Create path structure: year/faculty_name
                $folderPath = 'proofs/' . $year . '/' . $userId . '_' . $username . '/Activities-Organised';

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

            // Save the response to the database
            ActivitiesOrganised::create([
                'title' => $validated['title'],
                'resource_person_name' => $validated['resource_person_name'],
                'resource_person_organization' => $validated['resource_person_organization'],
                'target_audience' => $validated['target_audience'],
                'number_of_participants' => $validated['number_of_participants'],
                'objective' => $validated['objective'],
                'outcomes' => $validated['outcomes'],
                'department_id' => auth()->user()->department->id,
                'faculty_id' => auth()->user()->id,
                'venue' => $validated['venue'],
                'start_date' => $startDateTime,
                'end_date' => $endDateTime,
                'num_days' => $validated['num_days'],
                'activity_type' => $validated['activity_type'],
                'category' => $validated['category'],
                'level' => $validated['level'],
                'proof' => $proofPath,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Response submitted successfully');
        } catch (\Exception $e) {
            // Handle the exception and provide an error message
            return back()->withErrors('An error occurred while submitting your response: ' . $e->getMessage());
        }
    }

    public function IvOrganisedFormResponse(Request $request)
    {
        try {
            // Validate the request data
            $validated = $request->validate([
                'faculty_id' => 'required|exists:users,id',
                'start_date' => 'required|date',
                'start_time' => 'required|date_format:H:i',
                'end_date' => 'required|date',
                'end_time' => 'required|date_format:H:i',
                'company_name' => 'required|string',
                'company_address' => 'required|string',
                'resource_person_name' => 'required|string',
                'resource_person_contact_details' => 'required|string',
                'target_audience' => 'required|string',
                'student_year' => 'nullable|string',
                'number_of_participants' => 'required|integer',
                'objective' => 'required|string',
                'outcomes' => 'required|string',
                'proof' => '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
            $proofPath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

                // Create path structure: year/faculty_name
                $folderPath = 'proofs/' . $year . '/' . $userId . '_' . $username . '/Iv_organised';

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

            // Save the response to the database
            IvOrganised::create([
                'faculty_id' => auth()->user()->id,
                'start_date' => $startDateTime,
                'end_date' => $endDateTime,
                'company_name' => $validated['company_name'],
                'company_address' => $validated['company_address'],
                'resource_person_name' => $validated['resource_person_name'],
                'resource_person_contact_details' => $validated['resource_person_contact_details'],
                'target_audience' => $validated['target_audience'],
                'student_year' => $validated['student_year'],
                'number_of_participants' => $validated['number_of_participants'],
                'objective' => $validated['objective'],
                'outcomes' => $validated['outcomes'],
                'department_id' => auth()->user()->department->id,
                'proof' => $proofPath,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Industrial Visit details submitted successfully');
        } catch (\Exception $e) {
            // Handle the exception and provide an error message
            return back()->withErrors('An error occurred while submitting your response: ' . $e->getMessage());
        }
    }

    public function PublicationsFormResponse(Request $request)
    {
        try {
            // 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
            $paperFilePath = null;
            if ($request->hasFile('paper_file')) {
                $originalName = $request->file('paper_file')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

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

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

            // Save the response to the database
            Publication::create([
                'department_id' => auth()->user()->department->id,
                'first_author_name' => $validated['first_author_name'],
                'co_authors' => $validated['co_authors'],
                'start_date' => $startDateTime,
                'end_date' => $endDateTime,
                'num_days' => $validated['num_days'],
                'activity_type' => $validated['activity_type'],
                'title' => $validated['title'],
                'affiliation' => $validated['affiliation'],
                'organizing_institute' => $validated['organizing_institute'],
                'venue_address' => $validated['venue_address'],
                'is_peer_reviewed' => $validated['is_peer_reviewed'],
                'scopus_link' => $validated['scopus_link'],
                'sci_link' => $validated['sci_link'],
                'paper_file' => $paperFilePath,
                'faculty_id' => auth()->user()->id,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Publication details submitted successfully');
        } catch (\Exception $e) {
            // Handle the exception and provide an error message
            return back()->withErrors('An error occurred while submitting your publication: ' . $e->getMessage());
        }
    }
    public function BooksPublishedFormResponse(Request $request)
    {
        // dd($request->all());
        try {
            // 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
            $proofFilePath = null;
            if ($request->hasFile('proof_file')) {
                $originalName = $request->file('proof_file')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['date_of_publication']));

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

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

            // Save the response to the database
            BooksPublished::create([
                'department_id' => auth()->user()->department->id,
                'author' => $validated['author'],
                'title' => $validated['title'],
                'publisher' => $validated['publisher'],
                'issn' => $validated['issn'],
                'date_of_publication' => $validated['date_of_publication'],
                'proof' => $proofFilePath,
                'faculty_id' => auth()->user()->id,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Publication details submitted 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 ExternalEngagementFormResponse(Request $request)
    {
        // dd($request->all());
        try {
            // Validate the request data
            $validated = $request->validate([
                'activity' => 'required|string',
                'activity_description' => 'required|string',
                'inviting_organization' => 'required|string',
                'start_date' => 'required|date',
                'end_date' => 'required|date',
                'num_days' => 'required|integer',
                'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip'
            ]);

            // Handle the file upload
            $proofFilePath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

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

                // Store file in the specified path
                $proofFilePath = $request->file('proof')->storeAs($folderPath, $fileName, 'public');
            }
            // dd($proofFilePath);

            // Save the response to the database
            ExternalEngagement::create([
                'department_id' => auth()->user()->department->id,
                'activity' => $validated['activity'],
                'activity_description' => $validated['activity_description'],
                'inviting_organization' => $validated['inviting_organization'],
                'start_date' => $validated['start_date'],
                'end_date' => $validated['end_date'],
                'num_days' => $validated['num_days'],
                'proof' => $proofFilePath,
                'faculty_id' => auth()->user()->id,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'External Engagement details submitted successfully');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return back()->withErrors(['error' => 'External Engagement 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 OnlineCoursesFormResponse(Request $request)
    {
        // dd($request->all());
        try {
            // Validate the request data
            $validated = $request->validate([
                'course' => 'required|string',
                'offered_by' => 'required|string',
                'start_date' => 'required|date',
                'end_date' => 'required|date',
                'num_days' => 'required|integer',
                'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
            ]);

            // Handle the file upload
            $proofFilePath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['start_date']));

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

                // Store file in the specified path
                $proofFilePath = $request->file('proof')->storeAs($folderPath, $fileName, 'public');
            }
            // dd($proofFilePath);

            // Save the response to the database
            OnlineCourse::create([
                'department_id' => auth()->user()->department->id,
                'course' => $validated['course'],
                'offered_by' => $validated['offered_by'],
                'start_date' => $validated['start_date'],
                'end_date' => $validated['end_date'],
                'num_days' => $validated['num_days'],
                'proof' => $proofFilePath,
                'faculty_id' => auth()->user()->id,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Online Course details submitted successfully');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return back()->withErrors(['error' => 'Online Course 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 PatentsFormResponse(Request $request)
    {
        // dd($request->all());
        try {
            // Validate the request data
            $validated = $request->validate([
                'title' => 'required|string',
                'investigator' => 'required|string',
                'application_no' => 'required|string',
                'type' => 'required|string',
                'date_of_submission' => 'required|date',
                'date_of_filling' => 'required|date',
                'status' => 'required|string',
                'proof' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,docx,zip',
            ]);

            // Handle the file upload
            $proofFilePath = null;
            if ($request->hasFile('proof')) {
                $originalName = $request->file('proof')->getClientOriginalName();
                $username = auth()->user()->name;
                $userId = auth()->user()->id;
                $fileName = $username . '_' . $originalName;

                // Extract year from start_date
                $year = date('Y', strtotime($validated['date_of_submission']));

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

                // Store file in the specified path
                $proofFilePath = $request->file('proof')->storeAs($folderPath, $fileName, 'public');
            }
            // dd($proofFilePath);


            // Save the response to the database
            Patent::create([
                'department_id' => auth()->user()->department->id,
                'title' => $validated['title'],
                'investigator' => $validated['investigator'],
                'application_no' => $validated['application_no'],
                'type' => $validated['type'],
                'date_of_submission' => $validated['date_of_submission'],
                'date_of_filling' => $validated['date_of_filling'],
                'status' => $validated['status'],
                'proof' => $proofFilePath,
                'faculty_id' => auth()->user()->id,
            ]);

            return redirect()->route('faculty.dashboard')->with('status', 'Patent/Copyright details submitted successfully');
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            return back()->withErrors(['error' => 'Patent/Copyright 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();
        }
    }
}
