<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Models\Publication;
use App\Models\ActivityAttended;
use App\Models\ActivityOrganised;
use App\Models\IVOrganised;
use App\Models\BookPublished;
use App\Models\ExternalEngagement;
use App\Models\OnlineCourse;
use App\Models\PatentCopyright;
use App\Models\User;
use App\Mail\MissingProofsMail;
use App\Models\ActivitiesAttended;
use App\Models\ActivitiesOrganised;
use App\Models\BooksPublished;
use App\Models\Patent;

class MissingProofsController extends Controller
{
    public function checkAndSendEmails(Request $request)
    {
        $selectedCategories = $request->input('categories', []);
        
        if (empty($selectedCategories)) {
            return redirect()->back()->with('error', 'Please select at least one category.');
        }
        
        // Array to store missing proofs by faculty
        $missingProofsByFaculty = [];
        
        // Check each selected category
        foreach ($selectedCategories as $category) {
            switch ($category) {
                case 'publications':
                    $this->checkPublications($missingProofsByFaculty);
                    break;
                case 'activities_attended':
                    $this->checkActivitiesAttended($missingProofsByFaculty);
                    break;
                case 'activities_organised':
                    $this->checkActivitiesOrganised($missingProofsByFaculty);
                    break;
                case 'iv_organised':
                    $this->checkIVOrganised($missingProofsByFaculty);
                    break;
                case 'books_published':
                    $this->checkBooksPublished($missingProofsByFaculty);
                    break;
                case 'external_engagement':
                    $this->checkExternalEngagement($missingProofsByFaculty);
                    break;
                case 'online_courses':
                    $this->checkOnlineCourses($missingProofsByFaculty);
                    break;
                case 'patents_copyrights':
                    $this->checkPatentsCopyrights($missingProofsByFaculty);
                    break;
            }
        }
        
        // Send emails to faculty members
        $this->sendMissingProofEmails($missingProofsByFaculty);
        
        return redirect()->back()->with('success', 'Emails sent successfully to faculty members with missing proofs.');
    }
    
    private function checkPublications(&$missingProofsByFaculty)
    {
        // Find publications with missing proofs (paper_file is null)
        $missingProofs = Publication::whereNull('paper_file')->get();
        
        foreach ($missingProofs as $publication) {
            $facultyId = $publication->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Publication',
                'id' => $publication->id,
                'primary_name' => $publication->title,
                'details' => [
                    'Affiliation' => $publication->affiliation,
                    'Start Date' => $publication->start_date->format('d-m-Y'),
                    'End Date' => $publication->end_date->format('d-m-Y'),
                    'First Author' => $publication->first_author_name
                ]
            ];
        }
    }
    
    private function checkActivitiesAttended(&$missingProofsByFaculty)
    {
        $missingProofs = ActivitiesAttended::whereNull('proof')->get();
        
        foreach ($missingProofs as $activity) {
            $facultyId = $activity->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Activity Attended',
                'id' => $activity->id,
                'primary_name' => $activity->title,
                'details' => [
                    'Organising Institute' => $activity->organising_institute,
                    'Start Date' => $activity->start_date->format('d-m-Y'),
                    'End Date' => $activity->end_date->format('d-m-Y')
                ]
            ];
        }
    }
    
    private function checkActivitiesOrganised(&$missingProofsByFaculty)
    {
        $missingProofs = ActivitiesOrganised::whereNull('proof')->get();
        
        foreach ($missingProofs as $activity) {
            $facultyId = $activity->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Activity Organised',
                'id' => $activity->id,
                'primary_name' => $activity->title,
                'details' => [
                    'Objective' => $activity->objective,
                    'Outcomes' => $activity->outcomes,
                    'Start Date' => $activity->start_date->format('d-m-Y'),
                    'End Date' => $activity->end_date->format('d-m-Y')
                ]
            ];
        }
    }
    
    private function checkIVOrganised(&$missingProofsByFaculty)
    {
        $missingProofs = IvOrganised::whereNull('proof')->get();
        
        foreach ($missingProofs as $activity) {
            $facultyId = $activity->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Industrial Visit Organised',
                'id' => $activity->id,
                'primary_name' => $activity->company_name,
                'details' => [
                    'Company Address' => $activity->company_address,
                    'Objective' => $activity->objective,
                    'Outcomes' => $activity->outcomes,
                    'Start Date' => $activity->start_date->format('d-m-Y'),
                    'End Date' => $activity->end_date->format('d-m-Y')
                ]
            ];
        }
    }
    
    private function checkBooksPublished(&$missingProofsByFaculty)
    {
        $missingProofs = BooksPublished::whereNull('proof')->get();
        
        foreach ($missingProofs as $book) {
            $facultyId = $book->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Book Published',
                'id' => $book->id,
                'primary_name' => $book->title,
                'details' => [
                    'Author' => $book->author,
                    'Publisher' => $book->publisher,
                    'ISSN' => $book->issn,
                    'Date Of Publication' => $book->date_of_publication->format('d-m-Y'),
                ]
            ];
        }
    }
    
    private function checkExternalEngagement(&$missingProofsByFaculty)
    {
        $missingProofs = ExternalEngagement::whereNull('proof')->get();
        
        foreach ($missingProofs as $engagement) {
            $facultyId = $engagement->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'External Engagement',
                'id' => $engagement->id,
                'primary_name' => $engagement->activity,
                'details' => [
                    'Activity Description' => $engagement->activity_description,
                    'Inviting Organization' => $engagement->inviting_organization,
                    'Start Date' => $engagement->start_date->format('d-m-Y'),
                    'End Date' => $engagement->end_date->format('d-m-Y')
                ]
            ];
        }
    }
    
    private function checkOnlineCourses(&$missingProofsByFaculty)
    {
        $missingProofs = OnlineCourse::whereNull('proof')->get();
        
        foreach ($missingProofs as $course) {
            $facultyId = $course->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Online Course',
                'id' => $course->id,
                'primary_name' => $course->course,
                'details' => [
                    'Offered By' => $course->offered_by,
                    'Publisher' => $course->publisher,
                    'Start Date' => $course->start_date->format('d-m-Y'),
                    'End Date' => $course->end_date->format('d-m-Y')
                ]
            ];
        }
    }
    
    private function checkPatentsCopyrights(&$missingProofsByFaculty)
    {
        $missingProofs = Patent::whereNull('proof')->get();
        
        foreach ($missingProofs as $patent) {
            $facultyId = $patent->faculty_id;
            
            if (!isset($missingProofsByFaculty[$facultyId])) {
                $missingProofsByFaculty[$facultyId] = [
                    'faculty' => User::find($facultyId),
                    'items' => []
                ];
            }
            
            $missingProofsByFaculty[$facultyId]['items'][] = [
                'type' => 'Patent/Copyright',
                'id' => $patent->id,
                'primary_name' => $patent->title,
                'details' => [
                    'Investigator' => $patent->investigator,
                    'Application No' => $patent->application_no,
                    'Status' => $patent->status,
                    'Date Of Submission' => $patent->date_of_submission->format('d-m-Y'),
                    'Date Of Filling' => $patent->date_of_filling->format('d-m-Y'),
                ]
            ];
        }
    }
    
    private function sendMissingProofEmails($missingProofsByFaculty)
    {
        foreach ($missingProofsByFaculty as $facultyData) {
            $faculty = $facultyData['faculty'];
            $items = $facultyData['items'];
            
            // Send email
            try {
                Mail::to($faculty->email)->send(new MissingProofsMail($faculty, $items));
            } catch (\Exception $e) {
                // Handle the exception (log or report)
                \Log::error('Failed to send email: ' . $e->getMessage());
                // You could flash a message for admin if this is run from an admin panel
            }
        }
    }
}