<?php

namespace App\Http\Controllers;

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;
use App\Services\ProofDownloadService;
use Illuminate\Http\Request;

class AdminController extends Controller
{
    // Admin dashboard (optional)
    public function index()
    {
        $departments = Department::all();

        // Collect distinct years from all relevant date fields
        $years = collect([
            ActivitiesAttended::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
            ActivitiesOrganised::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
            BooksPublished::selectRaw('YEAR(date_of_publication) as year')->distinct()->pluck('year'),
            ExternalEngagement::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
            IvOrganised::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
            OnlineCourse::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
            Patent::selectRaw('YEAR(date_of_submission) as year')->distinct()->pluck('year'),
            Publication::selectRaw('YEAR(end_date) as year')->distinct()->pluck('year'),
        ])->flatten()->unique()->sortDesc();

        return view('admin.dashboard', compact('departments', 'years'));
    }

    // View responses submitted by users
    public function viewActivitiesAttendedResponses()
    {
        $departments = Department::all();
        return view('pages.activities-attended.index', compact('departments'));
    }
    public function viewActivitiesOrganisedResponses()
    {
        $departments = Department::all();
        return view('pages.activities-organised.index', compact('departments'));
    }
    public function viewIvOrganisedResponses()
    {
        $departments = Department::all();
        return view('pages.iv-organised.index', compact('departments'));
    }
    public function viewPublicationsResponses()
    {
        $departments = Department::all();
        return view('pages.publications.index', compact('departments'));
    }
    public function viewBooksPublishedResponses()
    {
        $departments = Department::all();
        return view('pages.booksPublished.index', compact('departments'));
    }
    public function viewExternalEngagementResponses()
    {
        $departments = Department::all();
        return view('pages.externalEngagement.index', compact('departments'));
    }
    public function viewOnlineCoursesResponses()
    {
        $departments = Department::all();
        return view('pages.onlineCourses.index', compact('departments'));
    }
    public function viewPatentsResponses()
    {
        $departments = Department::all();
        return view('pages.patents.index', compact('departments'));
    }

public function downloadProofs(Request $request, ProofDownloadService $proofDownloadService)
    {
        // Validate the request
        $request->validate([
            'ids' => 'required|string',
            'model' => 'sometimes|string',
        ]);

        $ids = json_decode($request->input('ids'));
        $modelName = $request->input('model', 'ActivitiesAttended');
        
        // Model mapping
        $modelMap = [
            'ActivitiesAttended' => ActivitiesAttended::class,
            'ActivitiesOrganised' => ActivitiesOrganised::class,
            'IvOrganised' => IvOrganised::class,
            'Publication' => Publication::class,
            'BooksPublished' => BooksPublished::class,
            'ExternalEngagement' => ExternalEngagement::class,
            'OnlineCourse' => OnlineCourse::class,
            'Patent' => Patent::class,
        ];
        
        // Get the model class from the map or default to ActivitiesAttended
        $modelClass = $modelMap[$modelName] ?? ActivitiesAttended::class;

        $result = $proofDownloadService->downloadProofs($modelClass, $ids);

        if (isset($result['error'])) {
            return back()->with('error', $result['error']);
        }

        // Return the zip file as a download
        return response()->download($result['filePath'], $result['fileName'])->deleteFileAfterSend(true);
    }

    public function analyticsActivitiesAttended()
    {
        $data = ActivitiesAttended::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'activities_attendeds.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsActivitiesOrganised()
    {
        $data = ActivitiesOrganised::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'activities_organiseds.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsIvOrganised()
    {
        $data = IvOrganised::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'iv_organiseds.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }
    
    public function analyticsPaperPublished()
    {
        $data = Publication::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'publications.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsBooksPublished()
    {
        $data = BooksPublished::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'books_published.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsExternalEngagement()
    {
        $data = ExternalEngagement::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'external_engagements.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsOnlineCourse()
    {
        $data = OnlineCourse::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'online_courses.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }
    public function analyticsPatent()
    {
        $data = Patent::selectRaw('departments.name as department, COUNT(*) as count')
            ->join('departments', 'patents.department_id', '=', 'departments.id')
            ->groupBy('departments.name')
            ->get();

        $total = $data->sum('count');

        return response()->json([
            'labels' => $data->pluck('department'),
            'values' => $data->pluck('count'),
            'total' => $total,
        ]);
    }

    public function analyticsComparison(Request $request)
    {
        $departmentId = $request->query('department_id');
        $year = $request->query('year');

        $models = [
            'ActivitiesAttended' => ['class' => ActivitiesAttended::class, 'date_field' => 'end_date'],
            'ActivitiesOrganised' => ['class' => ActivitiesOrganised::class, 'date_field' => 'end_date'],
            'BooksPublished' => ['class' => BooksPublished::class, 'date_field' => 'date_of_publication'],
            'ExternalEngagement' => ['class' => ExternalEngagement::class, 'date_field' => 'end_date'],
            'IvOrganised' => ['class' => IvOrganised::class, 'date_field' => 'end_date'],
            'OnlineCourse' => ['class' => OnlineCourse::class, 'date_field' => 'end_date'],
            'Patent' => ['class' => Patent::class, 'date_field' => 'date_of_submission'],
            'Publication' => ['class' => Publication::class, 'date_field' => 'end_date'],
        ];

        $data = [];

        foreach ($models as $label => $modelConfig) {
            $query = $modelConfig['class']::where('department_id', $departmentId);
            if ($year && $year !== 'all') {
                $query->whereYear($modelConfig['date_field'], $year);
            }
            $count = $query->count();
            if ($count > 0) { // Only include data with non-zero count
                $data[] = [
                    'label' => $label,
                    'count' => $count,
                ];
            }
        }

        $total = array_sum(array_column($data, 'count'));

        return response()->json([
            'labels' => array_column($data, 'label'),
            'values' => array_column($data, 'count'),
            'total' => $total
        ]);
    }

    public function analyticsContribution(Request $request)
    {
        $model = $request->query('model', 'all');
        $year = $request->query('year');

        $models = [
            'ActivitiesAttended' => ['class' => ActivitiesAttended::class, 'date_field' => 'end_date'],
            'ActivitiesOrganised' => ['class' => ActivitiesOrganised::class, 'date_field' => 'end_date'],
            'BooksPublished' => ['class' => BooksPublished::class, 'date_field' => 'date_of_publication'],
            'ExternalEngagement' => ['class' => ExternalEngagement::class, 'date_field' => 'end_date'],
            'IvOrganised' => ['class' => IvOrganised::class, 'date_field' => 'end_date'],
            'OnlineCourse' => ['class' => OnlineCourse::class, 'date_field' => 'end_date'],
            'Patent' => ['class' => Patent::class, 'date_field' => 'date_of_submission'],
            'Publication' => ['class' => Publication::class, 'date_field' => 'end_date'],
        ];

        $data = [];

        if ($model === 'all') {
            $departments = Department::all();

            foreach ($departments as $department) {
                $count = 0;
                foreach ($models as $modelConfig) {
                    $query = $modelConfig['class']::where('department_id', $department->id);
                    if ($year && $year !== 'all') {
                        $query->whereYear($modelConfig['date_field'], $year);
                    }
                    $count += $query->count();
                }
                if ($count > 0) { // Only include data with non-zero count
                    $data[] = [
                        'label' => $department->name,
                        'count' => $count,
                    ];
                }
            }
        } else {
            $modelConfig = $models[$model];
            $query = $modelConfig['class']::selectRaw('departments.name as label, COUNT(*) as count')
                ->join('departments', 'department_id', '=', 'departments.id')
                ->groupBy('departments.name');

            if ($year && $year !== 'all') {
                $query->whereYear($modelConfig['date_field'], $year);
            }

            $data = $query->get()->filter(function ($item) {
                return $item['count'] > 0; // Filter out data with zero count
            })->toArray();
        }

        $total = array_sum(array_column($data, 'count'));

        return response()->json([
            'labels' => array_column($data, 'label'),
            'values' => array_column($data, 'count'),
            'total' => $total
        ]);
    }
}
