<?php
if(isset($_POST['admission-complete'])){
    require_once("../php/dbconnect.php");
    include('../php/sms-send.php');
    $dir = "../stuImages/";
    $file = $_FILES['s_image'];
    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];

    $medical_info = $_POST['medical_info']??'';

 
    //image upload start
            // Create a unique file name using the current timestamp
            $timestamp = time();
            $new_file_name = $timestamp;
            
            $target_file = $dir . $new_file_name . '.' . strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            $uploadOk = 1;
            $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
            $student_image = $new_file_name . '.' . $imageFileType; //image name
            
            // Check if the file is an image
            if (file_exists($file_tmp)) {
                $check = getimagesize($file_tmp);
                if ($check !== false) {
                    // Get the image dimensions
                    list($width, $height) = getimagesize($file_tmp);
            
                    // Set the new width and height
                    $new_width = 150;
                    $new_height = 150;
            
                    // Create a new image from the file
                    $thumb = imagecreatetruecolor($new_width, $new_height);
            
                    // Check the image type and create an image from it accordingly
                    if ($imageFileType === 'jpeg' || $imageFileType === 'jpg') {
                        $source = imagecreatefromjpeg($file_tmp);
                    } elseif ($imageFileType === 'png') {
                        $source = imagecreatefrompng($file_tmp);
                    } else {
                        die('Unsupported image type.');
                    }
            
                    // Resize the image
                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            
                    // Save the resized image
                    if ($imageFileType === 'jpeg' || $imageFileType === 'jpg') {
                        imagejpeg($thumb, $target_file);
                    } elseif ($imageFileType === 'png') {
                        imagepng($thumb, $target_file);
                    } else {
                        die('Unsupported image type.');
                    }
            
                    echo "File is an image - " . $check["mime"] . ".";
                } else {
                    echo "File is not an image.";
                }
            } else {
                echo "File does not exist.";
            }
    //image upload end

    // Student signature upload
    $student_signature = null;
    if (isset($_FILES['student_signature']) && !empty($_FILES['student_signature']['name'])) {
        $sig_file = $_FILES['student_signature'];
        $sig_file_name = $sig_file['name'];
        $sig_file_tmp = $sig_file['tmp_name'];
        $sig_imageFileType = strtolower(pathinfo($sig_file_name, PATHINFO_EXTENSION));
        $sig_new_file_name = time() . '_sig_' . rand(1000,9999);
        $sig_target_file = $dir . $sig_new_file_name . '.' . $sig_imageFileType;
        $student_signature = $sig_new_file_name . '.' . $sig_imageFileType;
        if (file_exists($sig_file_tmp)) {
            $check = getimagesize($sig_file_tmp);
            if ($check !== false) {
                list($width, $height) = getimagesize($sig_file_tmp);
                $new_width = 150;
                $new_height = 50;
                $thumb = imagecreatetruecolor($new_width, $new_height);
                if ($sig_imageFileType === 'jpeg' || $sig_imageFileType === 'jpg') {
                    $source = imagecreatefromjpeg($sig_file_tmp);
                } elseif ($sig_imageFileType === 'png') {
                    $source = imagecreatefrompng($sig_file_tmp);
                } else {
                    $source = null;
                }
                if ($source) {
                    imagecopyresampled($thumb, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                    if ($sig_imageFileType === 'jpeg' || $sig_imageFileType === 'jpg') {
                        imagejpeg($thumb, $sig_target_file);
                    } elseif ($sig_imageFileType === 'png') {
                        imagepng($thumb, $sig_target_file);
                    }
                }
            }
        }
    }

    // student information
    $quotes = $_POST['quota_name'] ?? '';
    $institution_name_ex = $_POST['institution_name_ex'] ?? '';
    $trade_name = $_POST['trade_name'] ?? '';
    $name_en = $_POST['s_name_en'] ?? '';
    $name_bn = $_POST['s_name_bn'] ?? '';
    $mobile = $_POST['s_mobile'] ?? '';
    $email = $_POST['s_email'] ?? '';
    $birth_date = $_POST['s_birth_date'] ?? '';
    $id_type = $_POST['id_type'] ?? '';
    $birth_certificate = $_POST['s_birth_certificate'] ?? '';
    $gender = $_POST['s_gender'] ?? '';
    $religion = $_POST['religion'] ?? '';
    $bloodgroup = $_POST['bloodgroup'] ?? '';
    $present_school_name = $_POST['present_school_name'] ?? '';

    $guardian_name = $_POST['guardian_name'] ?? '';
    $relationship_parent = $_POST['relationship_parent'] ?? '';
    $parental_address = $_POST['parental_address'] ?? '';
    $guardian_mobile = $_POST['guardian_mobile'] ?? '';
    $whatsapp_no = $_POST['whatsapp_no'] ?? '';
    $previous_institute_name = $_POST['previous_institute_name'] ?? '';
    $previous_institute_class = $_POST['previous_institute_class'] ?? '';

    $p_ad_v = $_POST['p_ad_v'] ?? '';
    $p_ad_p = $_POST['p_ad_p'] ?? '';
    $p_ad_t = $_POST['p_ad_t'] ?? '';
    $p_ad_d = $_POST['p_ad_d'] ?? '';

    $shift_name = $_POST['shift'] ?? '';
    $admission_id = time();

    

    //address
    $s_village = $_POST['s_village'] ?? '';
    $s_post_office = $_POST['s_post_office'] ?? '';
    $s_police = $_POST['s_police'] ?? '';
    $s_district = $_POST['s_district'] ?? '';
    $p_s_village = $_POST['p_s_village'] ?? '';
    $p_s_post_office = $_POST['p_s_post_office'] ?? '';
    $p_s_police = $_POST['p_s_police'] ?? '';
    $p_s_district = $_POST['p_s_district'] ?? '';

    $address = array(
        's_village' => $_POST['s_village'] ?? '',
        's_post_office' => $_POST['s_post_office'] ?? '',
        's_police' => $_POST['s_police'] ?? '',
        's_district' => $_POST['s_district'] ?? '',
        'p_s_village' => $_POST['p_s_village'] ?? '',
        'p_s_post_office' => $_POST['p_s_post_office'] ?? '',
        'p_s_police' => $_POST['p_s_police'] ?? '',
        'p_s_district' => $_POST['p_s_district'] ?? ''
    );

$s_village = $_POST['s_village'];
$s_post_office = $_POST['s_post_office'];
$s_police = $_POST['s_police'];
$s_district = $_POST['s_district'];
$p_s_village = $_POST['p_s_village'];
$p_s_post_office = $_POST['p_s_post_office'];
$p_s_police = $_POST['p_s_police'];
$p_s_district = $_POST['p_s_district'];

    $address = json_encode($address);
    

    //parrents information
    $s_father_name_en = $_POST['s_father_name_en'] ?? '';
    $s_father_name_bn = $_POST['s_father_name_bn'] ?? '';
    $s_father_dob = $_POST['s_father_dob'] ?? '';
    $s_father_nid = $_POST['s_father_nid'] ?? '';
    $s_father_profession = $_POST['s_father_profession'] ?? '';
    $s_father_contact = $_POST['s_father_contact'] ?? '';
    $s_mother_name_en = $_POST['s_mother_name_en'] ?? '';
    $s_mother_name_bn = $_POST['s_mother_name_bn'] ?? '';
    $s_mother_dob = $_POST['s_mother_dob'] ?? '';
    $s_mother_nid = $_POST['s_mother_nid'] ?? '';
    $s_mother_profession = $_POST['s_mother_profession'] ?? '';
    $s_parents_income = $_POST['s_parents_income'] ?? '';

    $parents = array(
        'fname' => $_POST['s_father_name_en'] ?? '',
        'f_name_b' => $_POST['s_father_name_bn'] ?? '',
        'father_dob' => $_POST['s_father_dob'] ?? '',
        'father_nid' => $_POST['s_father_nid'] ?? '',
        'father_profession' => $_POST['s_father_profession'] ?? '',
        'father_contact' => $_POST['s_father_contact'] ?? '',
        'mName' => $_POST['s_mother_name_en'] ?? '',
        'm_name_b' => $_POST['s_mother_name_bn'] ?? '',
        'mother_dob' => $_POST['s_mother_dob'] ?? '',
        'mother_nid' => $_POST['s_mother_nid'] ?? '',
        'mother_profession' => $_POST['s_mother_profession'] ?? '',
        'parents_income' => $_POST['s_parents_income'] ?? ''
    );

    $parents = json_encode($parents);

    // admission information

    $class = $_POST['class'];
    $branch = $_POST['branch'];
    $section = $_POST['section'];
    $academic_year = date('Y');
    $academic_year_id =$_POST['academic_year'];
    
   // $j_date = date('d-M-Y:s:i');
    $j_date = date('d-m-Y:h:i A');
    //ssc information
        if(isset($_POST['ssc_school_name'])){
            $ssc_school = $_POST['ssc_school_name'];
            $ssc_exam = "ssc";
            $ssc_department = $_POST['ssc_depart'];
            $ssc_passing_year = $_POST['ssc_passing_year'];
            $ssc_board = $_POST['ssc_board'];
            $ssc_point = $_POST['ssc_gpa'];
            $ssc_roll = $_POST['ssc_roll'];
            $ssc_reg = $_POST['ssc_reg'];
            $ssc = array("school"=>$ssc_school,"exam"=>"ssc","passing_year"=>$ssc_passing_year,"department"=>$ssc_department,"board"=>$ssc_board,"point"=>$ssc_point);
            $ssc = json_encode($ssc);
        }else{
            $ssc ="none";
        }
    //hsc information
    if(isset($_POST['hsc_school_name'])){
        $hsc_school = $_POST['hsc_school_name'];
        $hsc_exam = "hsc";
        $hsc_passing_year = $_POST['hsc_passing_year'];
        $hsc_board = $_POST['hsc_board'];
        $hsc_department = $_POST['hsc_depart'];
        $hsc_point = $_POST['hsc_gpa'];
        $hsc_roll = $_POST['hsc_roll'];
        $hsc_reg = $_POST['hsc_reg'];
        $hsc = array("school"=>$ssc_school,"exam"=>"hsc","passing_year"=>$ssc_passing_year,"department"=>$department,"board"=>$ssc_board,"point"=>$ssc_point);
        $hsc = json_encode($hsc);
    }else{
        $hsc_school = "none";
        $hsc_exam = "none";
        $hsc_passing_year = "none";
        $hsc_board = "none";
        $hsc_department = "none";
        $hsc_point = "none";
        $hsc_roll = "none";
        $hsc_reg = "none";
        $hsc ="none";
    }
    //masters information

    // if(isset($_POST['master_school_name'])){
    //     $department = $_POST['master_depart'];
    //     $ssc_school = $_POST['master_school_name'];
    //     $ssc_exam = "masters";
    //     $ssc_passing_year = $_POST['master_passing_year'];
    //     $ssc_board = $_POST['master_board'];
    //     $ssc_point = $_POST['master_gpa'];
    //     $master_roll = $_POST['master_roll'];
    //     $master_reg = $_POST['master_reg'];
    //     $master = array("school"=>$ssc_school,"exam"=>"masters","passing_year"=>$ssc_passing_year,"department"=>$department,"board"=>$ssc_board,"point"=>$ssc_point);
    //     $master = json_encode($master);
    // }else{
    //     $master ="none";
    // }


    if(isset($_POST['jsc_school_name'])){
        $jsc_sc_name = $_POST['jsc_school_name'];
        $jsc_exam = "jsc";
        $jsc_passing_year = $_POST['jsc_passing_year'];
  
        $jsc_board = $_POST['jsc_board'];
        $jsc_point = $_POST['jsc_gpa'];
        $jsc_roll = $_POST['jsc_roll'];
        $jsc_reg = $_POST['jsc_reg'];
        $jscs = array("school"=>$jsc_sc_name,"exam"=>"jsc","passing_year"=>$jsc_passing_year,"reg"=>$jsc_reg,"roll"=>$jsc_roll,"board"=>$jsc_board,"point"=>$jsc_point);
        $jsc = json_encode($jscs);
    }else{
        $jsc = "none";
    }


    // master start
    if(isset($_POST['master_school_name'])){
        $jsc_sc_name = $_POST['master_school_name'];
        $jsc_exam = "master";
        $jsc_passing_year = $_POST['master_passing_year'];
        $master_depart = $_POST['master_depart'];
        $master_country = $_POST['master_country'];
        $jsc_point = $_POST['master_cgpa'];
        $jsc_roll = $_POST['master_roll'];
        $jsc_reg = $_POST['master_reg'];
        $jscs = array("school"=>$jsc_sc_name,"exam"=>"master","passing_year"=>$jsc_passing_year,"department"=>$master_depart,"reg"=>$jsc_reg,"roll"=>$jsc_roll,"country"=>$master_country,"point"=>$jsc_point);
        $masters = json_encode($jscs);
    }else{
        $masters = "none";
    }
    // master end



    $in = "INSERT INTO student (emailid, sname, std_name_b, fname, f_name_b, joindate, about_v,about_p, about_t, about_d,
     contact, branch, s_year, course, image, mName, m_name_b, gender,religion, birth_day, tmp_id, st_union_name, p_post_name, 
     guardian_year_income, st_guardian_profession, institution_Name_e_ssc, roll_no_ssc, regi_no_ssc, pass_year_ssc, group_trade_ssc,
      gpa_ssc, board_ssc, institution_Name_e_hsc, roll_no_hsc, regi_no_hsc, pass_year_hsc, group_trade_hsc, gpa_hsc, board_hsc, f_birth_day,
       m_birth_day, st_national_bir_id, f_national_bir_id, m_national_bir_id, blood_group_st,present_school_name,guardian_name,relationship_parent,parental_address,guardian_mobile,whatsapp_no,previous_institute_name,previous_institute_class,institution_name_ex, class_section_name, shift_name,p_ad_v,p_ad_p,p_ad_t,p_ad_d,f_contact_number,id_type,academic_year_name_bn,quota_student,trade_name,jsc,masters,medical_info,student_signature) 
       m_birth_day, st_national_bir_id, f_national_bir_id, m_national_bir_id, blood_group_st,present_school_name,guardian_name,relationship_parent,parental_address,guardian_mobile,whatsapp_no,previous_institute_name,previous_institute_class,institution_name_ex, class_section_name, shift_name,p_ad_v,p_ad_p,p_ad_t,p_ad_d,f_contact_number,id_type,academic_year_name_bn,quota_student,trade_name,jsc,masters,medical_info) 
       VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
    $insert = $con->prepare($in);
    if ($insert === false) {
        // Handle the error appropriately, for example:
        die('Error in preparing the statement: ' . $con->error);
    }
   $success = $insert->bind_param("ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss", $email, $name_en, $name_bn, $s_father_name_en, 
   $s_father_name_bn, $j_date, $s_village,$s_post_office, $s_police, $s_district, $mobile, $branch, $academic_year, $class, $student_image, $s_mother_name_en, 
   $s_mother_name_bn, $gender, $religion,$birth_date, $admission_id, $p_s_village, $p_s_post_office, $s_parents_income, $s_father_profession,
    $ssc_school, $ssc_roll, $ssc_reg, $ssc_passing_year, $ssc_department, $ssc_point, $ssc_board, $hsc_school, $hsc_roll, $hsc_reg,
     $hsc_passing_year, $hsc_department, $hsc_point, $hsc_board, $s_father_dob, $s_mother_dob, 
   $birth_certificate, $s_father_nid, $s_mother_nid, $bloodgroup,$present_school_name,$guardian_name,$relationship_parent,$parental_address,$guardian_mobile,$whatsapp_no,$previous_institute_name,$previous_institute_class,$institution_name_ex, $section, $shift_name,$p_ad_v,$p_ad_p,
   $p_ad_t,$p_ad_d,$s_father_contact,$id_type,$academic_year_id,$quotes,$trade_name,$jsc,$masters,$medical_info); //
   if ($success === false) {
    // Handle the error appropriately, for example:
    die('Error in binding parameters: ' . $insert->error);//
}
   // $insert->execute();
   $execute_success = $insert->execute();
if ($execute_success === false) {
    // Handle the error appropriately, for example:
    die('Error in executing query: ' . $insert->error);
}
    

    // insert new end
    $last_inserted_id = $con->insert_id;
    $fees_status =  1;
    // payment start condition start
    if(admission_switch('online-admission')=='on'){
                $f = admission_switch('admission-fee');
                if($f==404){
                    $fee = 200;
                }else{
                    $fee = $f;
                }
                $st_id= $last_inserted_id;
                $mobiles = !empty($mobile) ? $mobile : '0000000000'; // Set default mobile if empty
                $emails = !empty($email) ? $email : 'no-email@example.com'; // Set default email if empty
                $date_in = date('Y-m-d');
                $t = rand(11,99);
                $temp_id = $t.'A'.$last_inserted_id.'ZE';
                $password = rand(111111,999999);
                $submit_date = time();
                $expaire_date = time()+(admission_switch('max-time')*3600);
                $insert2 = $con->prepare("INSERT INTO student_admission_fee (s_t_id,fee_amount,fee_mobile,fee_email,fee_temp_id,fee_temp_pass,admission_submit_date,admission_expire_date,s_dates)VALUES(?,?,?,?,?,?,?,?,?)");
                $insert2 ->bind_param('iisssssss',$st_id,$fee,$mobiles,$emails,$temp_id,$password,$submit_date,$expaire_date,$date_in);
                $insert2 ->execute();
                $last_id_p = $con->insert_id;
                $sms = "<p>Your admission success <b>User ID :</b> $temp_id <br><b>Pass : </b> $password </p>
                Download admission form $bse_url"."online-admission/download-admission-form.php";
                // mobile_sms SEND START
                $mobile_sms = "Your admission success\nUser ID :  $temp_id \nPass :  $password  \nDownload admission form {$bse_url}online-admission/download-admission-form.php \n".$last_msg;
               
                // $message_data=[];
                // $message_data[]=array('mobile'=>$mobiles,"sms"=>$mobile_sms);
                // groupApiMsg($message_data);
                $selectsms_permission = "SELECT * FROM new_sms_permission";
                $compsms_permission = mysqli_query($con, $selectsms_permission);
                $sms_permission = mysqli_fetch_object($compsms_permission);

                if($sms_permission->admission_status == 1) {
                    $messageData = [
                        [
                            'mobile' => $mobiles,
                            'sms' => $mobile_sms,
                        ],
                    ];
            
                    $sms_response = send_sms(
                        $messageData
                    );
            
                    if (!$sms_response) {
                        // Log SMS error but don't roll back transaction
                        error_log("SMS sending failed: " . json_encode($sms_response));
                    }
                }
                // mobile_sms SEND END
                if(strlen($emails)>3){
                    //main function start
                    $sendmail = $emails;

                    require_once("../backend/email/email.php");
        
                    
                    //mail function end
                 $subject = "Your Admission User Password";
                 $msg = "<p> <b>User ID :</b> $temp_id <br><b>Pass : </b> $password  <br> Admission form download link <a href='$bse_url"."online-admission/download-admission-form.php'>Download Admission Form<a></p>";
                 function mailSend($sendmail,$subject,$msg){
                    $sendmail ="$sendmail";
                    $replymail="admin@webbazarbd.com";
                    $name = "Admission-website";
                    $subject = "$subject";
                    $msg = "$msg";
                    sendMail($sendmail,$replymail,$name,$subject,$msg);
                    }
        
                    mailSend($sendmail,$subject,$msg);
                
                }

                //EMAIL SEND END
              
                $_SESSION['payment_last_id'] = $last_id_p; 
                header("Location:$bse_url"."online-admission/download-admission-form.php");
            }else{
                $_SESSION['form']=$last_inserted_id;
                header("Location:$bse_url"."admission/admission-view.php");
            }
    //payment end condition end



    }

?>