HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: /var/www/html/shootinschool/wp-content/plugins/shootin-school-plugin/add_instructor.php
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;

function render_add_siab_instructor()
{
    global $wpdb;
    //     $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS);
    $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE `is_deleted` = 0 AND (`platform` = 1 OR `platform` = 3)");
    $allSessions = $wpdb->get_results("SELECT * FROM " . DB_PACKAGE_SESSIONS);
    $weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    ?>

    <div class="wrap">
        <div class="css_loader">Loading&#8230;</div>

        <div class="alert alert-info" role="alert" style="border: 1px solid green;border-radius: 5px;">
            <h3> Create New Instructor </h3>
            <a class="add-new-h2 btn btn-success" href="admin.php?page=siab-instructors"> Back to Instructors Listing</a>
        </div>

        <form id="createinstructor">
            <div class="form-group">
                <label for="firstName">Instructor Name</label>
                <input type="text" name="name" class="form-control" placeholder="Enter Instructor Name" required="required">
            </div>
            <!-- <div class="form-group">
                <label for="lastName">Last Name</label>
                <input type="text" name="lname" class="form-control" required="required">
            </div> -->
            <!-- <div class="form-group">
                <label for="phone">Phone</label>
                <input type="text" name="phone" class="form-control" required="required">
            </div> -->
            <div class="form-group">
                <label for="emailText">Email</label>
                <input type="email" class="form-control" name="email" placeholder="Enter Email" required="required">
            </div>
            <div class="form-group">
                <label for="instructorPhone">Phone</label>
                <input type="text" class="form-control" name="instructor_phone" placeholder="Enter PhoneNumber"
                    required="required">
            </div>

            <div class="form-group">
                <br /><label for="">Availability</label>
            </div>

            <!-- Start -->
            <?php foreach ($weekdays as $day) { ?>
                <div class="row">
                    <div class="col-md-4">
                        <strong style="color: #22a022;">
                            <?php echo strtoupper($day); ?>
                        </strong> &nbsp;
                        <button type="button" class="btn btn-primary btn-xs addMoreLocation"
                            onclick="addMorelocationadmin('<?php echo $day; ?>')"> + Add Availability</button>
                        <button type="button" class="btn btn-primary btn-xs setAllTimings"
                            onclick="setAllTimings_admin('<?php echo $day; ?>')"> All hours/locations</button>
                    </div>
                </div>
                <br />

                <div id="<?php echo $day; ?>_container">


                    <!-- Append Here -->

                </div>

                <hr>

            <?php } ?>

            <div class="row">
                <div class="col-md-4">
                    <strong> Specify OFF DAYS </strong> &nbsp;
                    <button type="button" class="btn btn-primary btn-xs addOffDays" onclick="addOffDay()"> + Add Off
                        day</button>
                </div>
            </div>
            <br />

            <div class="offday_Div" id="offday_Div">
                <!-- <div class="row">
                    <div class="col-md-2">
                        <div class="form-group">
                            <input type="date" name="off_day[]">
                        </div>
                    </div>
                </div> -->

                <!-- Append Here -->

            </div>
            <br />

            <div class="row">
                <div class="col-md-2">
                    <button type="button" class="btn btn-success" onclick="saveInstructor('save')"> Create
                        Instructor</button>
                </div>
            </div>

        </form>
    </div>
    <?php
}

add_action('wp_ajax_nopriv_get_locations', 'get_locations');
add_action('wp_ajax_get_locations', 'get_locations');
function get_locations()
{

    $day = $_REQUEST['pass_day'];

    global $wpdb;
    //     $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS);
    $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS . " WHERE `is_deleted` = 0 AND (`platform` = 1 OR `platform` = 3)");
    $allSessions = $wpdb->get_results("SELECT * FROM " . DB_PACKAGE_SESSIONS);

    foreach ($allLocations as $key => $value) {
        $working_hours = json_decode($value->working_hours);
        if ($working_hours->{$day}->open == "" || $working_hours->{$day}->close == "") {
            unset($allLocations[$key]);
        }
    }

    ob_start(); ?>



    <div class="form-group row new_data">
        
        <div class="form-content ">


            <div class="select-col">
                <div class="dropdown">
                    <select class="form-control loc_sel" onchange="getAvailability(this, '<?php echo $day; ?>')">
                        <option value=""> -- Choose Location -- </option>
                        <?php foreach ($allLocations as $single) { ?>
                            <option value="<?php echo $single->id; ?>">
                                <?php echo $single->name; ?>
                            </option>
                        <?php } ?>
                    </select>
                </div>
            </div>
            <div class="select-col">
                <div class="dropdown">
                    <select class="form-control loc_start" onchange="getStartTime(this, '<?php echo $day; ?>')">
                        <option value=""> -- Choose Availability Start Time -- </option>
                    </select>
                </div>
            </div>

            <div class="select-col">
                <div class="dropdown">
                    <select class="form-control loc_end" onchange="getEndTime(this, '<?php echo $day; ?>')">
                        <option value=""> -- Choose Availability End Time -- </option>
                    </select>
                </div>
            </div>
        </div>
        <div class="btn_close_otr">
            <button class="close_btn" onClick="this.parentNode.parentNode.remove();"><img
                    src="https://shootinschool.com/wp-content/plugins/shootin-school-plugin/includes/custom/img/close-icon.svg" alt=""></button>
        </div>

    </div>


    <?php $renderedHtml = ob_get_clean();

    echo json_encode(['status' => TRUE, 'renderedHtml' => $renderedHtml]);
    die();
}
add_action('wp_ajax_nopriv_get_locations_admin', 'get_locations_admin');
add_action('wp_ajax_get_locations_admin', 'get_locations_admin');
function get_locations_admin()
{

    $day = $_REQUEST['pass_day'];

    global $wpdb;
//     $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS);
    // $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS." WHERE `is_deleted` = 0 AND (`platform` = 1 OR `platform` = 3)");
    $allLocations = $wpdb->get_results("SELECT * FROM " . DB_COACHING_LOCATIONS." WHERE `is_deleted` = 0");
	$allSessions = $wpdb->get_results("SELECT * FROM " . DB_PACKAGE_SESSIONS);
    $get_monday = date('Y-m-d', strtotime('monday this week'));
    foreach ($allLocations as $key => $value) {
        
        $CurrentWeekquery = $wpdb->get_row("SELECT *  FROM " . DB_WORKING_HOURS . " WHERE `location_id` = '$value->id' AND `start_date` = '$get_monday'");
        // echo $day;
    //    if(!empty($CurrentWeekquery)){
        $working_hours = json_decode($CurrentWeekquery->working_hours);
        
        if($working_hours->{$day}->open ==""||$working_hours->{$day}->close ==""){
            unset($allLocations[$key]);
        // }
    }
       
    }
    
   
    ob_start(); ?>

    <div class="row new_data">

        <!-- <div class="col-md-2">
            <div class="form-group">
                <select class="form-control session_sel">
                    <option value=""> -- Choose Session -- </option>
                    <?php foreach ($allSessions as $session) { ?>
                        <option value="<?php echo $session->id; ?>"> <?php echo $session->session_name; ?> </option>
                    <?php } ?>
                </select>
            </div>
        </div> -->

        <div class="col-md-3">
            <div class="form-group">
                <select class="form-control loc_sel" onchange="getAvailability(this, '<?php echo $day; ?>')">
                    <option value=""> -- Choose Location -- </option>
                    <?php foreach ($allLocations as $single) { ?>
                            <option value="<?php echo $single->id; ?>">
                                <?php echo $single->name; ?>
                            </option>
                        <?php } ?>
                </select>
            </div>
        </div>


        <div class="col-md-3">
            <div class="form-group">
                <select class="form-control loc_start" onchange="getStartTime(this, '<?php echo $day; ?>')">
                    <option value=""> -- Choose Availability Start Time -- </option>
                </select>
            </div>
        </div>

        <div class="col-md-3">
            <div class="form-group">
                <select class="form-control loc_end" onchange="getEndTime(this, '<?php echo $day; ?>')">
                    <option value=""> -- Choose Availability End Time -- </option>
                </select>
            </div>
        </div>

        <div class="col-md-1">
            <div class="form-group">
                <button type="button" class="btn btn-danger btn-xs" onClick="this.parentNode.parentNode.parentNode.remove();">X</button>
            </div>
        </div>
    </div>


<?php $renderedHtml = ob_get_clean();

    echo json_encode(['status' => TRUE, 'renderedHtml' => $renderedHtml]);
    die();
}

add_action('wp_ajax_nopriv_get_timings', 'get_timings');
add_action('wp_ajax_get_timings', 'get_timings');
function get_timings()
{

    $location_id = $_POST['location_id'];
    $pass_type = $_POST['type'];
    $day = $_POST['day'];
    $ignoreTimes = $_POST['ignoreTimes'];
    global $wpdb;
    // $fetchLocation = $wpdb->get_results("SELECT working_hours FROM " . DB_COACHING_LOCATIONS . " WHERE id = $location_id AND (`platform` = 1 OR `platform` = 3)");
    $fetchLocation = $wpdb->get_results("SELECT working_hours FROM " . DB_COACHING_LOCATIONS . " WHERE id = $location_id");
    $working_hours = json_decode($fetchLocation[0]->working_hours, TRUE);

    $renderedHtml = '<option value=""> -- Choose Availability ' . ucfirst($pass_type) . ' Time -- </option>';

    $AddMins = 60 * 60;
    $ignore_timings = array();
    $req_start = '';

    if (isset($_REQUEST['start_time'])) {
        $req_start = strtotime($_REQUEST['start_time']);
    }

    if (is_array($working_hours) && $working_hours[$day]) {
        // if($ignoreTimes){
        //     foreach($ignoreTimes as $ignore){
        //         $end_time = strtotime($ignore['end']) - $AddMins;
        //      if($pass_type == 'start'){
        //         $start_time = strtotime($ignore['start']);
        //      }else{
        //         $start_time = strtotime($ignore['start']) + $AddMins;
        //          if($req_start < $start_time){
        //            $s = $start_time;
        //            $day_end = strtotime($working_hours[$day]['close']);
        //            while($s <= $day_end){
        //                array_push($ignore_timings,$s);
        //                $s += $AddMins;
        //            }
        //          }
        //      }
        //      while ($start_time <= $end_time) {
        //          array_push($ignore_timings,$start_time);
        //          $start_time += $AddMins;
        //      }
        //     }
        //  }
        $start = $working_hours[$day]['open'];
        $close = $working_hours[$day]['close'];

        if ($start == "" || $close == "") {
            $renderedHtml .= '<option value=""> -- Location is Closed --</option>';
        } else {

            $AddMins = 60 * 60;

            if ($pass_type == 'start') {  // render start select box
                $StartTime = strtotime($start);
                $EndTime = strtotime($close) - $AddMins;
            } else { // render end select box
                $StartTime = strtotime($_REQUEST['start_time']) + $AddMins;
                $EndTime = strtotime($close);
            }

            while ($StartTime <= $EndTime) {
                $t = date("g:i A", $StartTime);
                $renderedHtml .= '<option value="' . $t . '"> ' . $t . ' </option>';
                $StartTime += $AddMins;
            }
        }

        echo json_encode(['status' => TRUE, 'renderedHtml' => $renderedHtml]);
        die();
    }
}

add_action('wp_ajax_nopriv_save_instructor', 'save_instructor');
add_action('wp_ajax_save_instructor', 'save_instructor');
function save_instructor()
{

    global $wpdb;

    parse_str($_POST['form_data'], $form_data); //This will convert the string to array

    $name = $form_data['name'];
    // $last_name = $form_data['lname'];
    $phone = $form_data['instructor_phone'];

    $email = $form_data['email'];
    $off_days = $form_data['off_day'];
    // $sessions = $form_data['session'];
    $appointment_days = $_POST['appointment_days_new'];
    $appointment_days_existing = $_POST['appointment_days_existing'];

    $record_type = $_POST['type'];
    $update_ins_id = $_POST['update_ins_id'];


    if ($record_type == 'save') {
        if (null == email_exists($email)) {

            // Generate the password and create the user
            // $password = wp_generate_password(12, false);
            $password = mt_rand(1000000, 9999999);
            $user_id = wp_create_user($email, $password, $email);
            add_user_meta($user_id, 'billing_billing_phone', $phone);
            add_user_meta($user_id, 'issupervisor', 0);
            // Set the nickname
            wp_update_user(
                array(
                    'ID' => $user_id,
                    'nickname' => $name,
                    'display_name' => $name
                )
            );

            if (isset($appointment_days) && count($appointment_days) > 0) {
                foreach ($appointment_days as $index => $outerSingle) {
                    $day = $index;

                    foreach ($outerSingle as $key => $single) {

                        $args = array(
                            "instructor_id" => $user_id,
                            "location_id" => $single['location'],
                            "start_time" => $single['start'],
                            "end_time" => $single['end'],
                            "weekday" => $day
                        );

                        $sqlInsert = $wpdb->insert(DB_INSTRUCTORS_AVAILABILITY, $args);
                    }
                }
            }

            $query = "SELECT location_id FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE instructor_id=" . $user_id . " GROUP BY location_id";
            $dataResults = $wpdb->get_results($query);
            if (!empty($dataResults)) {
                foreach ($dataResults as $result) {
                    $location_id = $result->location_id;
                    $query = "SELECT * FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE instructor_id=" . $user_id . " AND location_id=" . $location_id;
                    $dataTimings = $wpdb->get_results($query);

                    if (!empty($dataTimings)) {
                        $working_hours['monday'] = array('open' => "", 'close' => "");
                        $working_hours['tuesday'] = array('open' => "", 'close' => "");
                        $working_hours['wednesday'] = array('open' => "", 'close' => "");
                        $working_hours['thursday'] = array('open' => "", 'close' => "");
                        $working_hours['friday'] = array('open' => "", 'close' => "");
                        $working_hours['saturday'] = array('open' => "", 'close' => "");
                        $working_hours['sunday'] = array('open' => "", 'close' => "");
                        foreach ($dataTimings as $timings) {
                            if ($timings->weekday == "monday") {
                                $working_hours['monday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "tuesday") {
                                $working_hours['tuesday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "wednesday") {
                                $working_hours['wednesday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "thursday") {
                                $working_hours['thursday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "friday") {
                                $working_hours['friday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "saturday") {
                                $working_hours['saturday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                            if ($timings->weekday == "sunday") {
                                $working_hours['sunday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                            }
                        }
                    }

                    $monday = date('Y-m-d', strtotime('monday this week'));

                    global $wpdb;
                    $sync = array(
                        "instructor_id" => $user_id,
                        "location_id" => $location_id,
                        "start_date" => $monday,
                        "end_date" => $monday,
                        "working_hours" => json_encode($working_hours)

                    );

                    $wpdb->insert(DB_INSTRUCTORS_AVAILABILITY_SCHEDULE, $sync);
                    // echo $wpdb->last_query;

                }

            }

            if (isset($off_days) && $off_days) {
                foreach ($off_days as $index => $single) {
                    $args = array(
                        "instructor_id" => $user_id,
                        "off_day" => $single
                    );

                    $sqlInsert = $wpdb->insert(DB_INSTRUCTORS_OFF_DAYS, $args);
                }
            }

            // Set the role
            $user = new WP_User($user_id);
            $user->remove_role('subscriber');
            $user->add_role('siab_instructor');

            // Email the user
            $email_instructor = $wpdb->get_row("SELECT * FROM " . DB_EMAILS . " WHERE id = 1", ARRAY_A);
            $msg = $email_instructor['body'];

            preg_match_all('/{(.*?)}/', $msg, $matches);

            if (in_array("instructor_name", $matches[1])) {
                $msg = str_replace('{instructor_name}', $name, $msg);
            }
            if (in_array("instructor_email", $matches[1])) {
                $msg = str_replace('{instructor_email}', $email, $msg);
            }
            if (in_array("instructor_password", $matches[1])) {
                $msg = str_replace('{instructor_password}', $password, $msg);
            }

            $headers[] = 'Content-Type: text/html; charset=UTF-8';
            $headers[] = 'From: ShootInSchool <noreply@shootinschool.com>';
            if ($email_instructor['notify_via_email'] == 1) {
                try {
                    //code...
                    wp_mail($email, $email_instructor['subject'], $msg, $headers);

                } catch (Exception $th) {
                    //throw $th;
                }
            }
            if ($email_instructor['notify_via_sms'] == 1) {

                $msg = str_replace('<br>', "\n", $msg);
                $msg = str_replace('&nbsp', " ", $msg);
                preg_match_all('/<(.*?)>/', $msg, $sms_matches);
                if (count($phone) > 0) {
                    foreach ($sms_matches[0] as $match) {
                        if ($match == "</p>") {
                            $cust_msg_sms = str_replace($match, "\n", $msg);
                        } else {
                            $cust_msg_sms = str_replace($match, '', $msg);
                        }
                    }
                    //Twilio message
                    // $args = array(
                    //     'number_to'=> fetchCountryMobileCode($user_id) . $phone,
                    //     'message' => $msg
                    // );
                    // twl_send_sms( $args );
                    $phones = [];
                    if (!in_array($phone[0], $phones)) {

                        try {
                            $number = fetchCountryMobileCode($user_id) . $phone[0];
                            // twl_send_sms($args);
                            $sid = TWILIO_ID;
                            $token = TWILIO_AUTH_TOKEN;
                            // In production, these should be environment variables. E.g.:
                            // $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]

                            // A Twilio number you own with SMS capabilities
                            $twilio_number = TWILIO_NUMBER;
                            $twilio = new Client($sid, $token);

                            $message = $twilio->messages->create(
                                $number,
                                ["body" => $msg, "from" => $twilio_number]
                            );
                            array_push($phones, $phone[0]);
                        } catch (Exception $e) {
                            // die( $e->getCode() . ' : ' . $e->getMessage() );

                        }

                    }
                }
            }
        } else {
            echo json_encode(array("status" => FALSE, "message" => 'Email already exists.'));
            die();
        }
    } else {

        $user_id = $update_ins_id;

        if (get_current_user_id() == $user_id) {
            if (get_user_meta($user_id, 'locked') == 1) {
                echo json_encode(array("status" => FALSE, "message" => 'Cannot update timings'));
                die();
            } else {
                update_user_meta($user_id, 'locked', 1);
            }
        }
        // Set the nickname
        $x = wp_update_user(
            array(
                'ID' => $user_id,
                'nickname' => $name,
                'display_name' => $name
            )
        );

        update_user_meta($user_id, 'billing_billing_phone', $phone);

        // Existing availability update submissions handling
        $ids_to_delete = array();


        if (isset($appointment_days_existing) && count($appointment_days_existing) > 0) {
            foreach ($appointment_days_existing as $index => $outerSingle) {
                $day = $index;

                foreach ($outerSingle as $key => $single) {
                    $args = array(
                        // "instructor_id" => $user_id,
                        "location_id" => $single['location'],
                        "start_time" => $single['start'],
                        "end_time" => $single['end'],
                        "weekday" => $day
                    );

                    $sqlInsert = $wpdb->update(DB_INSTRUCTORS_AVAILABILITY, $args, array("id" => $single['id']));

                    $ids_to_delete[] = $single['id'];
                }
            }
            $ids_to_delete = "(" . implode(",", $ids_to_delete) . ")";
            $wpdb->query("DELETE FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE `instructor_id` = '$user_id' AND `id` NOT IN $ids_to_delete");
        } else {
            $wpdb->query("DELETE FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE `instructor_id` = '$user_id'");
        }

        // New submissions handling
        if (isset($appointment_days) && count($appointment_days) > 0) {
            foreach ($appointment_days as $index => $outerSingle) {
                $day = $index;

                foreach ($outerSingle as $key => $single) {
                    $args = array(
                        "instructor_id" => $user_id,
                        "location_id" => $single['location'],
                        "start_time" => $single['start'],
                        "end_time" => $single['end'],
                        "weekday" => $day
                    );

                    $sqlInsert = $wpdb->insert(DB_INSTRUCTORS_AVAILABILITY, $args);
                }
            }
        }

        $wpdb->query("DELETE FROM " . DB_INSTRUCTORS_OFF_DAYS . " WHERE `instructor_id` = '$user_id'");
        if (isset($off_days) && $off_days) {
            foreach (array_unique($off_days) as $index => $single) {
                $args = array(
                    "instructor_id" => $user_id,
                    "off_day" => $single
                );

                $sqlInsert = $wpdb->insert(DB_INSTRUCTORS_OFF_DAYS, $args);
            }
        }

        $query = "SELECT location_id FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE instructor_id=" . $user_id . " GROUP BY location_id";
        $dataResults = $wpdb->get_results($query);
        $monday = date('Y-m-d', strtotime('monday this week'));
        $wpdb->query("DELETE FROM " . DB_INSTRUCTORS_AVAILABILITY_SCHEDULE . " WHERE `instructor_id` = '$user_id' AND `start_date` = '$monday'");
        if (!empty($dataResults)) {

            foreach ($dataResults as $result) {
                $location_id = $result->location_id;
                $query = "SELECT * FROM " . DB_INSTRUCTORS_AVAILABILITY . " WHERE instructor_id=" . $user_id . " AND location_id=" . $location_id;
                $dataTimings = $wpdb->get_results($query);

                if (!empty($dataTimings)) {
                    $working_hours['monday'] = array('open' => "", 'close' => "");
                    $working_hours['tuesday'] = array('open' => "", 'close' => "");
                    $working_hours['wednesday'] = array('open' => "", 'close' => "");
                    $working_hours['thursday'] = array('open' => "", 'close' => "");
                    $working_hours['friday'] = array('open' => "", 'close' => "");
                    $working_hours['saturday'] = array('open' => "", 'close' => "");
                    $working_hours['sunday'] = array('open' => "", 'close' => "");
                    foreach ($dataTimings as $timings) {
                        if ($timings->weekday == "monday") {
                            $working_hours['monday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "tuesday") {
                            $working_hours['tuesday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "wednesday") {
                            $working_hours['wednesday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "thursday") {
                            $working_hours['thursday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "friday") {
                            $working_hours['friday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "saturday") {
                            $working_hours['saturday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                        if ($timings->weekday == "sunday") {
                            $working_hours['sunday'] = array('open' => date("G:i", strtotime($timings->start_time)), 'close' => date("G:i", strtotime($timings->end_time)));
                        }
                    }
                }

                $monday = date('Y-m-d', strtotime('monday this week'));

                global $wpdb;
                $sync = array(
                    "instructor_id" => $user_id,
                    "location_id" => $location_id,
                    "start_date" => $monday,
                    "end_date" => $monday,
                    "working_hours" => json_encode($working_hours)

                );

                $wpdb->insert(DB_INSTRUCTORS_AVAILABILITY_SCHEDULE, $sync);
                // echo $wpdb->last_query;

            }

        }

        echo json_encode(array("status" => TRUE, "message" => 'Availability has been updated successfully.'));
        die();
    }

    echo json_encode(array("status" => TRUE, "message" => 'Account has been created successfully.', 'redirect' => admin_url('/admin.php?page=siab-instructors', 'http')));
    die();
}

add_action('wp_ajax_nopriv_set_all_timings', 'set_all_timings');
add_action('wp_ajax_set_all_timings', 'set_all_timings');

function set_all_timings()
{
    global $wpdb;
    $day = $_POST['day'];
    $query = 'SELECT * FROM ' . DB_COACHING_LOCATIONS.'WHERE (`platform` = 1 OR `platform` = 3)';
    $locations = $wpdb->get_results($query, ARRAY_A);

    foreach ($locations as $key => $value) {
        $working_hours = json_decode($value['working_hours']);
        if ($working_hours->{$day}->open == "" || $working_hours->{$day}->close == "") {
            unset($locations[$key]);
        }
    }
    $renderedRow = '';
    foreach ($locations as $key => $location) {
        $start_options = '<option value=""> -- Choose Availability Start Time -- </option>';
        $end_options = '<option value=""> -- Choose Availability End Time -- </option>';

        $working_hours = json_decode($location['working_hours']);
        $timings = $working_hours->{$day};

        $AddMins = 60 * 60;

        $start = $timings->open;
        $end = $timings->close;

        if ($start != '' && $end != '') {
            $StartTime = strtotime($start);
            $EndTime = strtotime($end) - $AddMins;
            while ($StartTime <= $EndTime) {
                $t = date("g:i A", $StartTime);
                if ($StartTime == strtotime($start)) {
                    $start_options .= '<option value="' . $t . '" selected> ' . $t . ' </option>';
                } else {
                    $start_options .= '<option value="' . $t . '"> ' . $t . ' </option>';
                }
                $StartTime += $AddMins;
            }

            $StartTime = strtotime($start) + $AddMins;
            $EndTime = strtotime($end);

            while ($StartTime <= $EndTime) {
                $t = date("g:i A", $StartTime);
                if ($EndTime == strtotime($end)) {
                    $end_options .= '<option value="' . $t . '" selected> ' . $t . ' </option>';
                } else {
                    $end_options .= '<option value="' . $t . '"> ' . $t . ' </option>';
                }

                $StartTime += $AddMins;
            }
            ob_start(); ?>
            <div class="form-group new_data">
               
                <div class="form-content">
                    <div class="select-col">
                        <div class="dropdown">
                            <select class="form-control loc_sel" onchange="getAvailability(this, '<?php echo $day; ?>')">
                                <option value=""> -- Choose Location -- </option>
                                <?php foreach ($locations as $loc_key => $single) {
                                    if ($key == $loc_key) {
                                        ?>
                                        <option value="<?php echo $single['id']; ?>" selected>
                                            <?php echo $single['name']; ?>
                                        </option>
                                        <?php
                                    } else {
                                        ?>
                                        <option value="<?php echo $single['id']; ?>">
                                            <?php echo $single['name']; ?>
                                        </option>
                                        <?php
                                    }
                                } ?>
                            </select>
                        </div>
                    </div>
                    <div class="select-col">
                        <div class="dropdown">
                            <select class="form-control loc_start" onchange="getStartTime(this, '<?php echo $day; ?>')">
                                <!-- <option value=""> -- Choose Availability Start Time -- </option> -->
                                <?php
                                echo $start_options;
                                ?>
                            </select>
                        </div>
                    </div>
                    <div class="select-col">
                        <div class="dropdown">
                            <select class="form-control loc_end" onchange="getEndTime(this, '<?php echo $day; ?>')">
                                <?php echo $end_options; ?>
                            </select>
                        </div>
                    </div>



                    <div class="btn_close_otr">
                        <button class="close_btn"  onClick="this.parentNode.parentNode.parentNode.remove();"><img src="https://shootinschool.com/wp-content/plugins/shootin-school-plugin/includes/custom/img/close-icon.svg" alt=""></button>
                    </div>
                </div>
                </div>
                <?php
                $renderedRow .= ob_get_clean();
        }
    }

    echo json_encode(['status' => true, 'renderedHtml' => $renderedRow]);
    die();
}
add_action('wp_ajax_nopriv_set_all_timings_admin', 'set_all_timings_admin');
add_action('wp_ajax_set_all_timings_admin', 'set_all_timings_admin');

function set_all_timings_admin()
{
    global $wpdb;
    $day = $_POST['day'];
    $query = 'SELECT * FROM '.DB_COACHING_LOCATIONS.' WHERE (`platform` = 1 OR `platform` = 3)';
    $locations = $wpdb->get_results($query, ARRAY_A);

    foreach ($locations as $key => $value) {
        $working_hours = json_decode($value['working_hours']);
        if($working_hours->{$day}->open ==""||$working_hours->{$day}->close ==""){
            unset($locations[$key]);
        }
    }
    $renderedRow = '';
    foreach ($locations as $key => $location) {
        $start_options = '<option value=""> -- Choose Availability Start Time -- </option>';
        $end_options = '<option value=""> -- Choose Availability End Time -- </option>';

        $working_hours = json_decode($location['working_hours']);
        $timings = $working_hours->{$day};

        $AddMins  = 60 * 60;

        $start = $timings->open;
        $end = $timings->close;

        if($start != '' && $end != ''){
            $StartTime = strtotime($start);
            $EndTime = strtotime($end) - $AddMins;
            while ($StartTime <= $EndTime) {
                $t = date("g:i A", $StartTime);
                if($StartTime == strtotime($start)){
                   $start_options .= '<option value="' . $t . '" selected> ' . $t . ' </option>';
                }else{
                   $start_options .= '<option value="' . $t . '"> ' . $t . ' </option>';
                }
                $StartTime += $AddMins;
            }

            $StartTime = strtotime($start) + $AddMins;
            $EndTime = strtotime($end);

            while ($StartTime <= $EndTime) {
                $t = date("g:i A", $StartTime);
                if($EndTime == strtotime($end)){
                    $end_options .= '<option value="' . $t . '" selected> ' . $t . ' </option>';
                }else{
                    $end_options .= '<option value="' . $t . '"> ' . $t . ' </option>';
                }

                $StartTime += $AddMins;
            }
            ob_start(); ?>
            <div class="row new_data">
                <div class="col-md-3">
                    <div class="form-group">
                        <select class="form-control loc_sel" onchange="getAvailability(this, '<?php echo $day; ?>')">
                            <option value=""> -- Choose Location -- </option>
                            <?php foreach ($locations as $loc_key=>$single) {
                                if($key == $loc_key){
                                    ?>
                                    <option value="<?php echo $single['id']; ?>" selected> <?php echo $single['name']; ?> </option>
                                    <?php
                                }else{
                                    ?>
                                    <option value="<?php echo $single['id']; ?>"> <?php echo $single['name']; ?> </option>
                                    <?php
                                }
                            } ?>
                        </select>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="form-group">
                        <select class="form-control loc_start" onchange="getStartTime(this, '<?php echo $day; ?>')">
                            <!-- <option value=""> -- Choose Availability Start Time -- </option> -->
                            <?php
                            echo $start_options;
                            ?>
                        </select>
                    </div>
                </div>

                <div class="col-md-3">
                    <div class="form-group">
                        <select class="form-control loc_end" onchange="getEndTime(this, '<?php echo $day; ?>')">
                            <?php echo $end_options; ?>
                        </select>
                    </div>
                </div>

                <div class="col-md-1">
                    <div class="form-group">
                        <button type="button" class="btn btn-danger btn-xs" onClick="this.parentNode.parentNode.parentNode.remove();">X</button>
                    </div>
                </div>
            </div>
            <?php
            $renderedRow .= ob_get_clean();
        }
    }

    echo json_encode(['status'=>true,'renderedHtml'=>$renderedRow]);
    die();
}
?>