<?php

namespace App\Http\Controllers;

use App\Models\Classe;
use App\Models\Fee_structure;
use App\Models\Section;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Models\NewStudentApplication;
use App\Models\NewStudentApplicationGuardian;
use Barryvdh\DomPDF\Facade\Pdf;
class StudentAppController extends Controller
{

    public function index(Request $request)
    {
        $query = NewStudentApplication::with(['classes', 'NewStudentApplicationGuardian'])
            ->orderBy('created_at', 'desc');

        $allCount = NewStudentApplication::count();
        $accept = NewStudentApplication::where('status', '2')->count();
        $pending = NewStudentApplication::where('status', '1')->count();
        $reject = NewStudentApplication::where('status', '3')->count();
        $class = Classe::get();

        // Apply search filter
        if ($request->filled('search')) {
            $searchTerm = '%' . $request->search . '%';
            $query->where(function ($q) use ($searchTerm) {
                $q->where('full_name', 'like', $searchTerm)
                    ->orWhere('cnic', 'like', $searchTerm)
                    ->orWhere('dob', 'like', $searchTerm)
                    ->orWhere('class_applying', '=', $searchTerm);
            });
        }
        if ($request->filled('class_search')) {
            $searchTerm = trim($request->class_search);
            
            $query->where(function ($q) use ($searchTerm) {
                $q->where('class_applying', '=', $searchTerm);
             });
        }

        // Entries per page (default to 10)
        $perPage = $request->input('entries', 10);

        // Paginate and keep other query params (like search & entries)
        $students = $query->paginate($perPage)->appends($request->all());
         // Handle AJAX request for partial updates
        if ($request->ajax()) {
            return view('stdApplication.partialApp', compact('students'))->render();
        }

        // Regular full page load
        return view('stdApplication.allApp', compact('students', 'class', 'allCount', 'accept', 'pending', 'reject'));
    }


    public function pdfStudentApplicationAll(Request $request)
    {
        $query = NewStudentApplication::with(['classes', 'NewStudentApplicationGuardian'])->orderBy('created_at', 'desc');

        // Filter by class if selected
        if ($request->filled('class_filter')) {
            $query->where('class_applying', $request->class_filter);
        }

        $students = $query->get(); // ✅ NO PAGINATION here
        $class = Classe::get();

        // Return PDF
        $pdf = PDF::loadView('stdApplication.pdfStudentApplicationAll', compact('students', 'class'));
        return $pdf->download('student_applications_all.pdf');
    }


    public function form()
    {
        $classes = Classe::all();
        $sections = Section::all();
        return view('stdApplication.newStdApp', compact('classes', 'sections'));
    }
    public function store(Request $request)
    {
        // Validate the form data
        $validatedData = $request->validate([
            'full_name' => 'required|string|min:3',
            'father_name' => 'required|string|min:3',
            'dob' => 'required|date',
            'gender' => 'required|string',
            'cnic' => 'required|digits:13|unique:new_student_applications,cnic',
            'class_applying' => 'required|string',
            'address' => 'required|string',
            'guardian_name' => 'required|string|min:3',
            'guardian_relationship' => 'required|string',
            'guardian_cnic' => 'required|digits:13|unique:new_student_application_guardians,guardian_cnic',
            'primary_contact' => 'required|digits:11',
            'alternate_contact' => 'nullable|digits:11',
            'email' => 'nullable|email',
        ]);

        // Start a database transaction
        DB::beginTransaction();

        try {
            // Insert into new_student_applications table
            $student = NewStudentApplication::create([
                'full_name' => $validatedData['full_name'],
                'father_name' => $validatedData['father_name'],
                'dob' => $validatedData['dob'],
                'gender' => $validatedData['gender'],
                'cnic' => $validatedData['cnic'],
                'class_applying' => $validatedData['class_applying'],
                'address' => $validatedData['address'],
            ]);

            // Insert into new_student_application_guardians table
            NewStudentApplicationGuardian::create([
                'student_id' => $student->id,
                'guardian_name' => $validatedData['guardian_name'],
                'guardian_relationship' => $validatedData['guardian_relationship'],
                'guardian_cnic' => $validatedData['guardian_cnic'],
                'primary_contact' => $validatedData['primary_contact'],
                'alternate_contact' => $validatedData['alternate_contact'],
                'email' => $validatedData['email'],
            ]);

            // Commit transaction if everything is successful
            DB::commit();

            return redirect()->back()->with('success', 'Application submitted successfully!');
        } catch (\Exception $e) {
            // Rollback transaction if an error occurs
            DB::rollBack();

            // Log the error
            Log::error('Application submission failed: ' . $e->getMessage());

            return redirect()->back()->with('error', 'Something went wrong! Please try again.');
        }
    }

    public function updateStatus(Request $request, $id)
    {
        // Find the student by ID
        $student = NewStudentApplication::findOrFail($id);

        // Validate the status input
        if (!$request->has('status')) {
            return response()->json(['error' => 'Status is required'], 400);
        }

        // Update the status
        $student->status = $request->status;
        $student->save();

        // Return success response
        return response()->json(['success' => true, 'status' => $student->status]);
    }

    public function profile($id)
    {
        $student = NewStudentApplication::where('id', $id)
            ->with(['classes', 'NewStudentApplicationGuardian'])
            ->orderBy('created_at', 'desc')
            ->firstOrFail(); // Use firstOrFail() to get a single model instance or throw an exception if not found

        return view('stdApplication.profile', compact('student'));
    }

    public function passData($id)
    {
        $classes        = DB::table('classes')->get();
        $sections       = DB::table('sections')->get();
        $fee_structures = Fee_structure::all();

        $passData = NewStudentApplication::where('id', $id)
            ->with(['classes', 'NewStudentApplicationGuardian'])
            ->orderBy('created_at', 'desc')
            ->firstOrFail();

        return view('stdAdmission.admForm', compact('classes', 'sections', 'fee_structures', 'passData'));
    }
}
