<?php

include "../../db.php"; // Database connection



if ($_SERVER["REQUEST_METHOD"] === "POST") {

    if (!isset($_POST['st_no']) || empty(trim($_POST['st_no']))) {

        die("Error: Invalid Request! Student number is missing.");

    }



    $st_no = mysqli_real_escape_string($con, $_POST['st_no']);

    $utype = "Student";



    // Fetch student details

    $query = "SELECT * FROM student_details WHERE st_no = '$st_no'";

    $result = mysqli_query($con, $query);



    if (!$result) {

        die("Error fetching student details: " . mysqli_error($con));

    }



    if ($row = mysqli_fetch_assoc($result)) {

        $state = $row["st_city"];

        $dist = $row["st_dist"];

        $email = $row["st_email"];

        $contact = $row["st_ph"];

        $wapp = $row["st_wp_no"];

        $address = $row["st_address"];

        $qualification = $row["st_qualification"];

        $about1 = $row["st_about"];

        $about2 = $row["st_about2"];

        $about3 = $row["st_about3"];

        $about4 = $row["st_about4"];

        $about5 = $row["st_about5"];

        $about6 = $row["st_about6"];

        $about7 = $row["st_about7"];

        $about8 = $row["st_about8"];

        $about = implode(', ', array_filter([$about2, $about3, $about4, $about5, $about6, $about7, $about8]));



        $upass = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT);

        $type = "Student";

        $ref_code = rand() . strtoupper(substr(uniqid(), 0, 4)) . time();

        $uref = rand() . '_' . time();

        $uState = '1';



        // Unique ID for Client

        $reffer_code = generateUniqueIdClient($state, $dist, $con);



        $st_by = $row["st_by"];

        $admin_ref = "";

        $adm_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$st_by' ");

        if ($adm_sql && $adm_row = mysqli_fetch_assoc($adm_sql)) {

            $admin_ref = $adm_row["uref_code"];

        }



        $insertQuery = "INSERT INTO users (uname, utype, uref, uref_code, ucontact, saddress, ucountry, state, dist, uqualification, uemail, uwhatsapp, uabout, uOabout, uphone, upass, uadmin, admin_ref, uStatus, udisplay, referal_code) 

                        VALUES ('$row[st_name]', '$utype', '$uref', '$ref_code', '$contact', '$address', '101', '$state', '$dist', '$qualification', '$email', '$wapp', '$about1', '$about', '$contact', '$upass', '', '$admin_ref', '$uState', '', '$reffer_code' )";



        if (mysqli_query($con, $insertQuery)) {

            $updateSql = mysqli_query($con, "UPDATE student_details SET st_current_status = 'Promote' WHERE st_no = '$st_no' ");

            echo "Student accepted successfully!";

        } else {

            echo "Error inserting student: " . mysqli_error($con);

        }

    } else {

        echo "Error: Student not found!";

    }

} else {

    echo "Error: Invalid request method!";

}



// Function to generate unique referral code

function generateUniqueIdClient($state, $dist, $con) {

    // Pad the state and district values

    $state1 = str_pad($state, 2, '0', STR_PAD_LEFT);

    $dist1 = str_pad($dist, 3, '0', STR_PAD_LEFT);



    // Generate random alphabets and numbers

    $random_alphabets = chr(rand(65, 90)) . chr(rand(65, 90));

    $random_number = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);



    // Concatenate components to form the referral code

    $reff_code = $state1 . $dist1 . $random_alphabets . $random_number;



    // Check if the generated referral code already exists in the database

    $query = "SELECT COUNT(*) AS count FROM users WHERE referal_code = ?";

    $stmt = mysqli_prepare($con, $query);

    mysqli_stmt_bind_param($stmt, 's', $reff_code);

    mysqli_stmt_execute($stmt);

    $result = mysqli_stmt_get_result($stmt);

    $row = mysqli_fetch_assoc($result);



    // If the referral code exists, regenerate it until it is unique

    while ($row['count'] > 0) {

        $random_alphabets = chr(rand(65, 90)) . chr(rand(65, 90));

        $random_number = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

        $reff_code = $state1 . $dist1 . $random_alphabets . $random_number;



        // Check again if the new code exists

        mysqli_stmt_execute($stmt);

        $result = mysqli_stmt_get_result($stmt);

        $row = mysqli_fetch_assoc($result);

    }



    // Return the unique referral code

    return $reff_code;

}

?>