<?php

namespace App\Http\Controllers\Api\V1\Student;

use App\Http\Controllers\Api\V1\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Enrollment;
use App\Models\Assignment;
use App\Models\AssignmentSubmission;
use App\Models\FeePayment;
use App\Models\Quiz;
use App\Models\Book;

class DashboardController extends BaseController
{
    /**
     * Get student dashboard data.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        try {
            $user = Auth::user();
            
            // Get enrolled courses
            $enrollments = Enrollment::where('student_id', $user->id)
                ->with(['course', 'courseOffering'])
                ->get();
            
            $totalCourses = $enrollments->count();
            
            // Get assignments
            $assignments = Assignment::whereHas('course', function($q) use ($user) {
                $q->whereHas('enrollments', function($eq) use ($user) {
                    $eq->where('student_id', $user->id);
                });
            })->with(['course'])->get();
            
            $totalAssignments = $assignments->count();
            $pendingAssignments = $assignments->filter(function($assignment) use ($user) {
                $submission = AssignmentSubmission::where('assignment_id', $assignment->id)
                    ->where('student_id', $user->id)
                    ->first();
                return !$submission || !$submission->score;
            })->count();
            
            $gradedAssignments = $assignments->filter(function($assignment) use ($user) {
                $submission = AssignmentSubmission::where('assignment_id', $assignment->id)
                    ->where('student_id', $user->id)
                    ->whereNotNull('score')
                    ->first();
                return $submission !== null;
            })->count();
            
            // Get recent courses (limit 5)
            $recentCourses = $enrollments->take(5)->map(function($enrollment) {
                return [
                    'id' => $enrollment->course->id ?? null,
                    'title' => $enrollment->course->name ?? 'N/A',
                    'description' => $enrollment->course->description ?? null,
                    'thumbnail' => null, // Add if you have thumbnails
                    'progress' => 0, // Calculate progress if you track it
                    'enrolled_at' => $enrollment->enrollment_date ?? $enrollment->created_at,
                ];
            })->values();
            
            // Get recent assignments (limit 5)
            $recentAssignments = $assignments->take(5)->map(function($assignment) use ($user) {
                $submission = AssignmentSubmission::where('assignment_id', $assignment->id)
                    ->where('student_id', $user->id)
                    ->first();
                
                return [
                    'id' => $assignment->id,
                    'title' => $assignment->title,
                    'course' => [
                        'id' => $assignment->course->id ?? null,
                        'title' => $assignment->course->name ?? 'N/A',
                    ],
                    'due_date' => $assignment->due_date,
                    'status' => $submission ? ($submission->status ?? ($submission->score ? 'graded' : 'submitted')) : 'pending',
                    'submitted_at' => $submission->submitted_at ?? null,
                    'score' => $submission->score ?? null,
                    'grade_percentage' => $submission->grade_percentage ?? null,
                ];
            })->values();
            
            // Calculate fee alerts
            $feeAlerts = [];
            foreach ($enrollments as $enrollment) {
                if ($enrollment->course) {
                    $courseFee = $enrollment->course->fees ?? 0;
                    $paidAmount = FeePayment::where('student_id', $user->id)
                        ->where(function($q) use ($enrollment) {
                            $q->where('course_id', $enrollment->course_id);
                            if ($enrollment->course_offering_id) {
                                $q->orWhere('course_offering_id', $enrollment->course_offering_id);
                            }
                        })
                        ->sum('amount');
                    
                    $balance = $courseFee - $paidAmount;
                    
                    if ($balance > 0) {
                        $feeAlerts[] = [
                            'course' => [
                                'id' => $enrollment->course->id,
                                'title' => $enrollment->course->name,
                            ],
                            'balance' => round($balance, 2),
                            'balance_formatted' => number_format($balance, 2),
                            'paid' => round($paidAmount, 2),
                            'paid_formatted' => number_format($paidAmount, 2),
                            'total' => round($courseFee, 2),
                            'total_formatted' => number_format($courseFee, 2),
                        ];
                    }
                }
            }
            
            // Get quizzes stats
            $totalQuizzes = Quiz::where('is_active', true)->count();
            
            // Get books stats
            $totalBooks = Book::where('is_active', true)->count();
            
            // Quick actions for mobile app
            $quickActions = [
                [
                    'type' => 'books',
                    'title' => 'Books',
                    'subtitle' => 'Explore interactive learning materials',
                ],
                [
                    'type' => 'quizzes',
                    'title' => 'Quizzes',
                    'subtitle' => 'Test your knowledge and track progress',
                ],
                [
                    'type' => 'assignments',
                    'title' => 'Assignments',
                    'subtitle' => 'View and submit your assignments',
                ],
                [
                    'type' => 'courses',
                    'title' => 'Courses',
                    'subtitle' => 'Browse your enrolled courses',
                ],
                [
                    'type' => 'videos',
                    'title' => 'Videos',
                    'subtitle' => 'Watch class videos',
                ],
                [
                    'type' => 'profile',
                    'title' => 'Profile',
                    'subtitle' => 'Manage your account settings',
                ],
            ];
            
            // Calculate total outstanding balance
            $totalOutstandingBalance = array_sum(array_column($feeAlerts, 'balance'));
            
            return $this->success([
                'stats' => [
                    'total_courses' => $totalCourses,
                    'total_assignments' => $totalAssignments,
                    'pending_assignments' => $pendingAssignments,
                    'graded_assignments' => $gradedAssignments,
                    'total_quizzes' => $totalQuizzes,
                    'total_books' => $totalBooks,
                ],
                'recent_courses' => $recentCourses,
                'recent_assignments' => $recentAssignments,
                'fee_alerts' => $feeAlerts,
                'total_outstanding_balance' => round($totalOutstandingBalance, 2),
                'quick_actions' => $quickActions,
            ]);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Student Dashboard API error: ' . $e->getMessage());
            return $this->error('An error occurred while fetching dashboard data.', null, 500);
        }
    }
}

