<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use App\Models\Category;
use App\Models\Student;
use App\Models\Property;
use App\Models\Image;
use App\Models\Wallet;
use Illuminate\Support\Facades\Mail;
use App\Mail\RegMail;
use App\Mail\PasswordMail;
use App\Mail\ResetPasswordMail;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\Parents;

class PagesController extends Controller
{
    public function login(){

        return view('login');
    }


    public static function getImage($id){
        $image = Image::where('property_id',$id)->first();
        // return response()->json(['image' => $image]);
        return $image;
    }

    public function enroll(){
        return view('enroll');
    }

    public function gallery(Request $request){
        return view('gallery');
    }

    public function login_user(Request $request)
    {
        // Validate incoming data
        $request->validate([
            'phone' => 'required',
            'password' => 'required'
        ]);

        // Attempt to find parent by phone number
        $parent = Parents::where('phone', $request->phone)->first();

        // Check if parent exists and password is correct
        if ($parent && Hash::check($request->password, $parent->password)) {
            
            // Put parent data in session
            session([
                'parent_logged_in' => true,
                'parent_id' => $parent->id,
                'parent_name' => $parent->fullname,
                'parent_email' => $parent->email,
                'parent_phone' => $parent->phone,
                'parent_occupation' => $parent->occupation
            ]);

            return redirect('dashboard'); // Use route name if available
        }

        // Authentication failed
        return back()->with('error', 'Invalid phone number or password.');
    }

        public function logout_parent(Request $request){
        // Clear only parent-related session data
        // $request->session()->forget([
        //     'parent_logged_in',
        //     'parent_id',
        //     'parent_name',
        //     'parent_email',
        //     'parent_phone',
        //     'parent_occupation'
        // ]);

        // OR: to clear all session data (optional)
        $request->session()->flush();

        return redirect('login')->with('success', 'You have successfully logged out.');
    }


    public function dashboard(Request $request){
        $students = Student::where('parent_phone',session('parent_phone'))->get();
        return view('dashboard',compact('students'));
    }

    public function results($id){
       $student = Student::find($id);
        $nursery_result = DB::table('nursery_result')->where('student_id',$id)->get();
        $primary_result = DB::table('primary_result')->where('student_id',$id)->get();
        $jss_result = DB::table('juniorsecondary_result')->where('student_id',$id)->get();
        $ss_result = DB::table('seniorsecondary_result')->where('student_id',$id)->get();

        return view("results",compact("student","nursery_result","primary_result","jss_result","ss_result")); 
    }

    public function make_payment(Request $request){
        return view('make_payment');
    }

    public function add_student(Request $request){
        $last = Student::orderBy('id', 'desc')->first();

        if (!$last) {
            $number = 1;
        } else {
            $number = $last->id + 1;
        }

        // Create unique student number
        $student_no = "SCH-" . str_pad($number, 4, '0', STR_PAD_LEFT);

        $student = Student::create([
            'stud_no' => $student_no,
            'lastname' => $request->lastname,
            'firstname' => $request->firstname,
            'middlename' => $request->middlename,
            'dob' => $request->dob,
            'gender' => $request->gender,
            'state' => $request->state,
            'lga' => $request->lga,
            'address' => $request->address,
            'nationality' => $request->nationality,
            'religion' => $request->religion,
            'genotype' => $request->genotype,
            'weight' => $request->weight,
            'height' => $request->height,
            'transferred' => $request->transferred,
            'previous_school' => $request->previous_school,
            'previous_class' => $request->previous_class,
            'intended_class' => $request->intended_class,
            'school' => $request->school,


            'parent_name' => $request->parent_name,
            'parent_phone' => $request->parent_phone,
            'parent_address' => $request->parent_address,
            'parent_email' => $request->parent_email,
            'occupation' => $request->occupation,
            'sponsorship' => $request->sponsorship,
            'relationship' => $request->relationship,

            'genotype' => $request->genotype,
            'blood_group' => $request->blood_group,
            'notice' => $request->notice,
        ]);


        if (!Parents::where('phone', $request->parent_phone)->exists()) {

            $parents = Parents::create([
                'fullname' => $request->parent_name,
                'phone' => $request->parent_phone,
                'address' => $request->parent_address,
                'email' => $request->parent_email,
                'occupation' => $request->occupation,
                'password' => Hash::make("0000"),  // default password
            ]);
        }
        // Redirect back with success message
        return back()->with('success', 'Student record submitted successfully!');
    }

    public function contact_us(){
        return view('contact');
    }

    public function result_checker(){
        return view('result_checker');
    }



    public function fetch_result(Request $request){

        $stud_no = $request->serial_no;
        $student = Student::where('stud_no',$stud_no)->first();
        $student_id = $student->id;
        $term = $request->term;
        $session = $request->session;
        switch ($request->school) {
            case 'Nursery':
                $result = DB::table('nursery_result')
                        ->where('student_id',$student_id)
                        ->where('term',$term)
                        ->where('session',$session)
                        ->first();
                return back()->with([
                    'result' => $result,
                    'school' => $request->school
                ]);
                break;
            case 'Primary':
                $result = DB::table('primary_result')
                        ->where('student_id',$student_id)
                        ->where('term',$term)
                        ->where('session',$session)
                        ->first();
                return back()->with([
                    'result' => $result,
                    'school' => $request->school
                ]);
                break;
            case 'Junior Secondary':
                $result = DB::table('juniorsecondary_result')
                        ->where('student_id',$student_id)
                        ->where('term',$term)
                        ->where('session',$session)
                        ->first();
                return back()->with([
                    'result' => $result,
                    'school' => $request->school
                ]);
                break;
            case 'Senior Secondary':
                $result = DB::table('seniorsecondary_result')
                        ->where('student_id',$student_id)
                        ->where('term',$term)
                        ->where('session',$session)
                        ->first();
                return back()->with([
                    'result' => $result,
                    'school' => $request->school
                ]);
                // print_r($result);
                break;
            default:
                # code...
                break;
        }
    }

    public function download($id,$school){
        switch ($school) {
            case 'Nursery':
                $result = DB::table('nursery_result')
                        ->where('id',$id)
                        ->first();
                
                break;
            case 'Primary':
                $result = DB::table('primary_result')
                        ->where('id',$id)
                        ->first();
                break;
            case 'Junior Secondary':
                $result = DB::table('juniorsecondary_result')
                        ->where('id',$id)
                        ->first();
                break;
            case 'Senior Secondary':
                $result = DB::table('seniorsecondary_result')
                        ->where('id',$id)
                        ->first();
                // print_r($result);
                break;
            default:
                # code...
                break;
        }
        $student = Student::find($result->student_id);
        $class = Student::find($result->class_id);
        $pdf = Pdf::loadView('result_pdf', compact('result','student','class','school'));
        return $pdf->download('student_result_'.$result->id.'.pdf');
    }

    public function requests(Request $request){
        $requests = new Requests;
        $requests->fullname = $request->fullname;
        $requests->email = $request->email;
        $requests->phone = $request->phone;
        $requests->category = $request->category;
        $requests->comment = $request->comment;
        $requests->budget = $request->budget;
        $requests->location = $request->location;
        $requests->state = $request->state;
        $requests->property_type = $request->property_type;

        $requests->save();
        return back();
    }



    public function policy(){
        return view('privacypolicy');
    }

    public function forgot_password(){
        return view('forgot-password');
    }

    public function recover_email(Request $request){
        $user = User::where('email',$request->email)->first();
        Mail::to($user->email)->send(new ResetPasswordMail($user));
        return redirect('login');
    }

    public function reset($id,$code){
        if (User::where('id',$id)->where('otp',$code)->exists()) {
            $user = User::find($id);
            return view('new-password')->with('user',$user);
        }else{
            return redirect('login')->with('message','Link to reset password not recognised. Try again'); 
        }
        
    }

    public function set_new_password(Request $request){
        $user = User::find($request->user_id);
        $user->password = Hash::make($request->password);
        if ($user->save()) {
            Mail::to($user->email)->send(new PasswordMail($user));
            return back()->with("New Password has been set");
        }else{
            return back()->with("Could not reset password");

        }
    }


    public function about(){
        return view('about');
    }
    public function signup(){
        return view('signup');
    }

    public function add_user(Request $request){
        if(User::where('email',$request->email)->exists()){
               $message = "Your Email has been used already. Try another one!";
               return back()->with('message',$message);
        }else{
            $user = new User;
            $user->fullname = $request->fullname;
            $user->phone = $request->phone;
            $user->email = $request->email;
            $user->password = Hash::make($request->password);
            $user->user_type = "Admin";
            $user->status = 0;
            
            if ($user->save()) {
            //    $usr = User::where('email',$user->email)->first();
               
               
            //    Mail::to($user->email)->send(new RegMail($usr,$strval));
               $message = "Account has been created!";
               return back()->with('message',$message);

            }else{
                $message = "Something went wrong. Try Again!";
                return back()->with('message',$message);
            }

        }
    }

    public function verifyme($id,$code){
        $user = User::find($id);
        $user->status = 1;
        $user->email_verified_at = now();
        $user->save();
        $message="Your email has been verified. Login!";
        return redirect('login')->with("message",$message);
    }



}
