<?php

namespace App\Http\Controllers\Student;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Log;
use Illuminate\Database\QueryException;
use Illuminate\Validation\Rules\Password;
use App\Models\Enrollment;
use App\Models\FeePayment;
use App\Models\Course;
use App\Mail\PaymentNotificationMail;

class ProfileController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'role:student']);
    }

    /**
     * Display the student profile page.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        try {
            $user = Auth::user();
            
            // Get enrolled courses
            $enrollments = Enrollment::where('student_id', $user->id)
                ->with(['course', 'courseOffering'])
                ->get();
            
            // Calculate fee information
            $feeData = [];
            $totalFees = 0;
            $totalPaid = 0;
            
            foreach ($enrollments as $enrollment) {
                if ($enrollment->course) {
                    $courseFee = $enrollment->course->fees;
                    $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;
                    $totalFees += $courseFee;
                    $totalPaid += $paidAmount;
                    
                    $feeData[] = [
                        'course' => $enrollment->course,
                        'offering' => $enrollment->courseOffering,
                        'fee' => $courseFee,
                        'paid' => $paidAmount,
                        'balance' => $balance,
                    ];
                }
            }
            
            $totalBalance = $totalFees - $totalPaid;
            
            return view('student.profile.index', compact('user', 'feeData', 'totalFees', 'totalPaid', 'totalBalance'));
        } catch (\Exception $e) {
            Log::error('Student Profile Index Error: ' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine() . ' | Trace: ' . $e->getTraceAsString());
            
            // Return view with empty data if there's an error
            return view('student.profile.index', [
                'user' => Auth::user(),
                'feeData' => [],
                'totalFees' => 0,
                'totalPaid' => 0,
                'totalBalance' => 0,
            ])->with('error', 'An error occurred while loading your profile. Please refresh the page.');
        }
    }

    /**
     * Update the student profile.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        try {
            $user = Auth::user();
            
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'email' => 'required|string|email|max:255|unique:users,email,' . $user->id,
                'phone' => 'nullable|string|max:20',
                'address' => 'nullable|string|max:500',
                'delivery_address' => 'nullable|string',
                't_shirt_size' => 'nullable|in:XS,S,M,L,XL,XXL,XXXL',
                'profile_picture' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:1024', // Reduced to 1MB
            ]);
            
            // Handle profile picture upload - encrypt and store in database
            if ($request->hasFile('profile_picture')) {
                $file = $request->file('profile_picture');
                
                // Validate file exists and is readable
                if (!$file->isValid()) {
                    return back()->withErrors(['profile_picture' => 'The uploaded file is not valid.'])->withInput();
                }
                
                // Check file size (additional validation)
                if ($file->getSize() > 1024 * 1024) { // 1MB
                    return back()->withErrors(['profile_picture' => 'The image must not be larger than 1MB.'])->withInput();
                }
                
                try {
                    // Get file contents and convert to base64
                    $imageData = file_get_contents($file->getRealPath());
                    
                    if ($imageData === false) {
                        return back()->withErrors(['profile_picture' => 'Failed to read the image file.'])->withInput();
                    }
                    
                    $base64 = base64_encode($imageData);
                    
                    // Get MIME type
                    $mimeType = $file->getMimeType();
                    
                    // Create data URI format: data:image/jpeg;base64,...
                    $dataUri = 'data:' . $mimeType . ';base64,' . $base64;
                    
                    // Encrypt the data URI
                    $encrypted = Crypt::encryptString($dataUri);
                    
                    $validated['profile_picture'] = $encrypted;
                } catch (\Exception $e) {
                    Log::error('Profile picture encryption error: ' . $e->getMessage());
                    return back()->withErrors(['profile_picture' => 'Failed to process the image. Please try a smaller file.'])->withInput();
                }
            }
            
            // Only update fields that are in the validated array
            $user->name = $validated['name'];
            $user->email = $validated['email'];
            
            if (isset($validated['phone'])) {
                $user->phone = $validated['phone'];
            }
            
            if (isset($validated['address'])) {
                $user->address = $validated['address'];
            }
            
            if (isset($validated['delivery_address'])) {
                $user->delivery_address = $validated['delivery_address'];
            }
            
            if (isset($validated['t_shirt_size'])) {
                $user->t_shirt_size = $validated['t_shirt_size'];
            }
            
            if (isset($validated['profile_picture'])) {
                $user->profile_picture = $validated['profile_picture'];
            }
            
            $user->save();
            
            return redirect()->route('student.profile.index')
                ->with('success', 'Profile updated successfully!');
        } catch (\Illuminate\Validation\ValidationException $e) {
            return back()->withErrors($e->errors())->withInput();
        } catch (\Illuminate\Database\QueryException $e) {
            Log::error('Profile update database error: ' . $e->getMessage() . ' | SQL: ' . ($e->getSql() ?? 'N/A'));
            return back()->withErrors(['error' => 'Database error occurred. Please check logs.'])->withInput();
        } catch (\Exception $e) {
            Log::error('Profile update error: ' . $e->getMessage() . ' | File: ' . $e->getFile() . ' | Line: ' . $e->getLine() . ' | Trace: ' . $e->getTraceAsString());
            return back()->withErrors(['error' => 'Error: ' . $e->getMessage()])->withInput();
        }
    }

    /**
     * Send payment notification to admin.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function notifyPayment(Request $request)
    {
        $request->validate([
            'transaction_id' => 'required|string|max:255',
            'amount' => 'required|numeric|min:0.01',
            'payment_method' => 'nullable|string|max:255',
        ]);

        $user = Auth::user();
        $adminEmail = 'aduamahdaniel16@gmail.com';

        try {
            Mail::to($adminEmail)->send(new PaymentNotificationMail(
                $user,
                $request->transaction_id,
                $request->amount,
                $request->payment_method
            ));

            return response()->json([
                'success' => true,
                'message' => 'Payment notification sent successfully! Admin will verify your payment shortly.'
            ]);
        } catch (\Exception $e) {
            \Log::error('Failed to send payment notification: ' . $e->getMessage());
            
            return response()->json([
                'success' => false,
                'message' => 'Failed to send notification. Please try again or contact support.'
            ], 500);
        }
    }

    /**
     * Update the student password.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => 'required',
            'password' => ['required', 'confirmed', Password::defaults()],
        ]);
        
        $user = Auth::user();
        
        if (!Hash::check($request->current_password, $user->password)) {
            return back()->withErrors(['current_password' => 'The current password is incorrect.']);
        }
        
        $user->update([
            'password' => Hash::make($request->password),
        ]);
        
        return redirect()->route('student.profile.index')
            ->with('success', 'Password updated successfully!');
    }
}

