<?php

namespace App\Http\Controllers;

use App\Models\Course;
use App\Models\Setting;
use App\Models\Enrollment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Http;
use App\Mail\EnrollmentConfirmation;
use App\Mail\AdminEnrollmentNotification;

class EnrollmentController extends Controller
{
        public function index()
    {
        $enrollments = Enrollment::with('course')->latest()->get();
        return view('admin.enrollments.index', compact('enrollments'));
    }

    // Resource method - show single enrollment
  public function show($id)
{
    $enrollment = Enrollment::with('course')->findOrFail($id);
    return view('admin.enrollments.show', compact('enrollment'));
}
public function edit($id)
{
    $enrollment = Enrollment::with('course')->findOrFail($id);
    return view('admin.enrollments.edit', compact('enrollment'));
}
  public function update(Request $request, $id)
{
    $enrollment = Enrollment::findOrFail($id);
    $enrollment->update(['status' => $request->status]);

    return redirect()->route('admin.enrollments.index')
        ->with('success', 'Enrollment status updated successfully!');
}

    public function showEnrollmentForm($slug)
    {
    $course = Course::where('slug', $slug)->firstOrFail();
        return view('enroll', compact('course')); 
    }

    public function processEnrollment(Request $request, $courseId)
    {
        $course = Course::findOrFail($courseId);

        $validated = $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email',
            'phone' => 'required|string',
            'education_level' => 'nullable|string',
            'experience_level' => 'nullable|string',
            'motivation' => 'nullable|string',
            'preferred_schedule' => 'required|string',
            'terms' => 'required|accepted'
        ]);

        // Create enrollment
        $enrollment = Enrollment::create([
            'course_id' => $course->id,
            'first_name' => $validated['first_name'],
            'last_name' => $validated['last_name'],
            'email' => $validated['email'],
            'phone' => $validated['phone'],
            'education_level' => $validated['education_level'],
            'experience_level' => $validated['experience_level'],
            'motivation' => $validated['motivation'],
            'preferred_schedule' => $validated['preferred_schedule'],
            'newsletter_optin' => $request->has('newsletter'),
            'status' => 'pending'
        ]);

        // Get settings
        $setting = Setting::first();

        // Send email to customer
        Mail::to($enrollment->email)->send(new EnrollmentConfirmation($enrollment, $setting));

        // Send email to admin
        $adminEmail = config('mail.admin_email', 'nadeemmm815@gmail.com');
        Mail::to($adminEmail)->send(new AdminEnrollmentNotification($enrollment, $setting));

        // Send WhatsApp notification
        $this->sendWhatsAppNotification($enrollment);

        return response()->json([
            'success' => true,
            'message' => 'Enrollment successful! Check your email for confirmation.',
            'enrollment_code' => $enrollment->enrollment_code
        ]);
    }

   private function sendWhatsAppNotification($enrollment)
{
    try {
        $phone = '923059741380'; // Your WhatsApp number
        
        // Different carriers ke email-to-SMS gateways
        $carrierGateways = [
            'mobilink' => 'jazz.com.pk',
            'telenor' => 'telenor.com.pk', 
            'ufone' => 'ufone.com',
            'zong' => 'zong.com.pk',
            'whatsapp' => 'whatsapp.com'
        ];
        
        $message = "📚 NEW COURSE ENROLLMENT\n\n" .
                  "Student: {$enrollment->first_name} {$enrollment->last_name}\n" .
                  "Email: {$enrollment->email}\n" .
                  "Phone: {$enrollment->phone}\n" .
                  "Course: {$enrollment->course->title}\n" .
                  "Enrollment Code: {$enrollment->enrollment_code}\n" .
                  "Time: " . $enrollment->created_at->format('M d, Y h:i A');
        
        // Try different carriers
        foreach ($carrierGateways as $carrier => $gateway) {
            $to = $phone . '@' . $gateway;
            $subject = "New Enrollment - {$enrollment->enrollment_code}";
            
            if (mail($to, $subject, $message)) {
                \Log::info("WhatsApp sent via {$carrier} gateway");
                return true;
            }
        }
        
        return false;
        
    } catch (\Exception $e) {
        \Log::error('Email gateway failed: ' . $e->getMessage());
        return false;
    }
}
    public function getEnrollments()
    {
        $enrollments = Enrollment::with('course')->latest()->get();
        return view('admin.enrollments.index', compact('enrollments'));
    }

    public function getEnrollmentDetails($id)
    {
        $enrollment = Enrollment::with('course')->findOrFail($id);
        return response()->json($enrollment);
    }

    public function updateStatus(Request $request, $id)
    {
        $enrollment = Enrollment::findOrFail($id);
        $enrollment->update(['status' => $request->status]);

        return response()->json([
            'success' => true,
            'message' => 'Enrollment status updated successfully'
        ]);
    }















}