<?php
if (session_status() === PHP_SESSION_NONE) {
    if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
        session_save_path($_SERVER['DOCUMENT_ROOT'].'/timesheet_new/sessions');
    } else {
        session_save_path($_SERVER['DOCUMENT_ROOT'].'/sessions');
    }

    ini_set('session.gc_probability', 1);
    session_start();
}
error_reporting(E_ALL ^ E_WARNING); 
error_reporting(E_ALL ^ E_NOTICE);  
ini_set('display_errors',0);
/*ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
*/

$conn = mysqli_connect('localhost','timesheethub_user','7yDJ9ntw.#@T','timesheethub_main_db');
function get_user_by_id($pass_id){
   global $conn;
   if(empty($pass_id)){ return ''; }
   $fetch_user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_users WHERE id=".$pass_id)); 
   return $fetch_user;
}
function get_user_by_mail($email){
    global $conn;
    if(empty($email)){ return ''; }
    $fetch_user = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_users WHERE TRIM(email) LIKE '".$email."'")); 
    return $fetch_user;
 }
function generate_password($length){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.
            '0123456789=~!@#$%^&*()+<>?[]{}|';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[random_int(0, $max)];

  return $str;
}
function get_log_array($pass_id){
    global $conn;

        $get_log = mysqli_fetch_array(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$pass_id))['log']; 
        if(empty($get_log)){
            $old_log = array();
        } else {
            $old_log = unserialize($get_log); 
        }

    return $old_log;
}
if(isset($_SESSION['loggedin_user']) && !empty($_SESSION['loggedin_user'])){
    $emp_list   = mysqli_fetch_assoc(mysqli_query($conn, "select * from db_users where id=".$_SESSION['loggedin_user']));
   
    $show_name  = $emp_list['full_name'];
    $show_email = $emp_list['email'];
    $show_phone = $emp_list['phone'];
    //if($emp_list['type'] == 'company'){ $emp_list['type'] = 'admin'; }
    $is_admin_login = ($emp_list['type'] == 'admin') ? 1 : 0;
    $curr_user_type = $emp_list['type'];
}
if(isset($_GET['approve_from_mail']) && !empty($_GET['approve_from_mail']) && !empty($_GET['pass_uid'])){
    $all_ids = array();
    $show_name  = get_user_by_id($_SESSION['loggedin_user'])['full_name'];
    parse_str($_GET['approve_from_mail'], $all_ids);
    if(empty($all_ids) && !empty($_GET['approve_from_mail'])){
        $all_ids = $_GET['approve_from_mail'];
    }
    $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$all_ids[0]));
    if($get_timelog['action_by_email'] == 1 ){
        echo "<h3 style='color:red;'>Already Action taken for this timelog through this link.</h3>";
        die();
    }
    //mysqli_query($conn, "UPDATE db_timelog SET status='approved', action_by_email=1 WHERE id in(".implode(',', $all_ids).")");

    if(!empty($all_ids)){
        foreach($all_ids as $ai){
            $old_log = get_log_array($ai);
            array_push($old_log, array('user_id'=>$_GET['pass_uid'],'action'=>'Approved','date_time'=>strtotime('now')));
            mysqli_query($conn, "UPDATE db_timelog SET status='approved', action_by_email=1, log='".serialize($old_log)."' WHERE id=".$ai); 

        }    
    }
     

    
    
    if(!empty($get_timelog['project_id'])){

        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));
        $title = "Approved timelog by ".$show_name." for project ".$get_project_name['name'];

        // Add entry in activity table.
        mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_GET['pass_uid']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
        // Send mail to related user
        if(!empty(get_user_by_id($get_timelog['user_id']))){
            $mail_to = get_user_by_id($get_timelog['user_id']);
            //mail($mail_to['email'],'$title',"Hello, $title");
            send_zoho_mail($mail_to['email'],"$title","Hello, $title");
        }
        

    }
    echo "<h3>Approved Successfully!!</h3>";
    die();
}
if(isset($_GET['reject_from_mail']) && !empty($_GET['reject_from_mail']) && !empty($_GET['pass_uid'])){
    $all_ids = array();
    parse_str($_GET['reject_from_mail'], $all_ids);
    if(empty($all_ids) && !empty($_GET['reject_from_mail'])){
        $all_ids = $_GET['reject_from_mail'];
    }

     
    
    $get_timelog = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_timelog WHERE id=".$all_ids[0]));
    if($get_timelog['action_by_email'] == 1 ){
        echo "<h3 style='color:red;'>Already Action taken for this timelog through this link.</h3>";
        die();
    }

    //mysqli_query($conn, "UPDATE db_timelog SET status='rejected', action_by_email=1 WHERE id in(".implode(',', $all_ids).")");

    if(!empty($all_ids)){
        foreach($all_ids as $ai){
            $old_log = get_log_array($ai);
            array_push($old_log, array('user_id'=>$_GET['pass_uid'],'action'=>'Rejected','date_time'=>strtotime('now')));
            mysqli_query($conn, "UPDATE db_timelog SET status='rejected', action_by_email=1, log='".serialize($old_log)."' WHERE id=".$ai); 

        }    
    }

    if(!empty($get_timelog['project_id'])){

        $get_project_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$get_timelog['project_id']));
        $title = "Rejected timelog by ".$show_name." for project ".$get_project_name['name'];

        // Add entry in activity table.
        mysqli_query($conn, "INSERT INTO db_user_activity(title, description, created_by, to_user_id, date_time) VALUES('$title', '','".$_GET['pass_uid']."', '".$get_timelog['user_id']."', '".date("Y-m-d h:i:s")."')");
        // Send mail to related user
        if(!empty(get_user_by_id($get_timelog['user_id']))){
            $mail_to = get_user_by_id($get_timelog['user_id']);
            //mail($mail_to['email'],'$title',"Hello, $title");
            send_zoho_mail($mail_to['email'],"$title","Hello, $title");
        }
        

    }
    echo "<h3>Rejected Successfully!!</h3>";
    die();
}
 if(isset($_SERVER['HTTPS'])){
        $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
    }else{
        $protocol = 'http';
    }

    $site_url = $protocol . "://" . $_SERVER['HTTP_HOST']."/";
    if (strpos($_SERVER['REQUEST_URI'], 'timesheet_new') !== false) {
        $site_url = $protocol . "://" . $_SERVER['HTTP_HOST']."/timesheet_new/";
    }

    /*if(strpos($_SERVER['REQUEST_URI'], "/company/") !== false){
        $req_url = explode('/', $_SERVER['REQUEST_URI']);
        if(isset($req_url[3]) && !empty($req_url[3])){
            $site_url = $site_url.$req_url[1].'/'.$req_url[2];
            echo $site_url;
        }
       
    }*/
 //if(strpos($_SERVER['REQUEST_URI'], '/dist/') !== false){ 
if(strpos($_SERVER['SCRIPT_NAME'], '/dist/') !== false){
    /** for backend site checking if user not loggedin and try to access the page then redirect them to login page. **/
    if(!isset($_SESSION['loggedin_user'])){
        header("location:".$site_url."login.php");
    }
   
} else {
     /** for front end site checking if user loggedin then redirect them to backend dashboard page. **/
    if(isset($_SESSION['loggedin_user'])){
        header("location:".$site_url);
    }
}
/** Reset password when first time employee login **/
if(isset($_SESSION['loggedin_user']) ){
   $u = get_user_by_id($_SESSION['loggedin_user']); 
    $comp_domain = '';
    if(!empty($u['company_name'])){
        $company_name = ($u['type'] == 'company') ?  strtolower($u['username']) : strtolower(get_user_by_id($u['company_name'])['username']);
        $comp_domain = "company/".$company_name."/";
    }
    if($u['first_time_login'] == 0 && strpos($_SERVER['REQUEST_URI'], 'reset_first_time.php') == false && !isset($_GET['signout'])){
       
            header("location:".$site_url.$comp_domain."dist/reset_first_time.php");
    } 
        
}
//if($_SERVER['SCRIPT_URI'] == $site_url || $_SERVER['REQUEST_URI'] == "/"){
if($_SERVER['REQUEST_URI'] == '/?signout=1' || $_SERVER['REQUEST_URI'] == "/"){
    if(isset($_GET['signout']) && $_GET['signout'] == 1){
        unset($_SESSION['loggedin_user']);
        header("location:".$site_url."login.php");
    }
    if(isset($_SESSION['loggedin_user']) ){
        $u = get_user_by_id($_SESSION['loggedin_user']); 
        $comp_domain = '';
        if(!empty($u['company_name'])){
            $comp_domain = "company/".strtolower(get_user_by_id($u['company_name'])['username'])."/";
        }
        if($u['type'] == 'company'){
            $comp_domain = "company/".strtolower($u['username'])."/";
        }
            if(!empty($comp_domain)){
                header("location:".$site_url.$comp_domain);
            }
            
        
    }
}
// checking the current user have right compnay name in the url if not then redirect to their company name url.
if(strpos($_SERVER['REQUEST_URI'], "/company/") !== false && isset($_SESSION['loggedin_user'])){


    $req_url = explode('/', $_SERVER['REQUEST_URI']);
    $req_url = array_filter($req_url);
    $u = get_user_by_id($_SESSION['loggedin_user']);
   
    if($u['type'] == 'company'){
        $curr_comp_name = $u['username'];
    } else {
        $curr_comp_name = get_user_by_id($u['company_name'])['username'];
    }
    if(isset($req_url[2]) && !empty($req_url[2])){
        
        if(strtolower($curr_comp_name) != $req_url[2]){
            $req_url[2] = strtolower($curr_comp_name);
            header("location:/".implode('/', $req_url));
        }
        
    } else {
        $req_url[2] = strtolower($curr_comp_name);
        header("location:/".implode('/', $req_url));
    }
         
}

function utf8_uri_encode( $utf8_string, $length = 0 ) {
    $unicode = '';
    $values = array();
    $num_octets = 1;
    $unicode_length = 0;

    $string_length = strlen( $utf8_string );
    for ($i = 0; $i < $string_length; $i++ ) {

        $value = ord( $utf8_string[ $i ] );

        if ( $value < 128 ) {
            if ( $length && ( $unicode_length >= $length ) )
                break;
            $unicode .= chr($value);
            $unicode_length++;
        } else {
            if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;

            $values[] = $value;

            if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
                break;
            if ( count( $values ) == $num_octets ) {
                if ($num_octets == 3) {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
                    $unicode_length += 9;
                } else {
                    $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
                    $unicode_length += 6;
                }

                $values = array();
                $num_octets = 1;
            }
        }
    }

    return $unicode;
}

//taken from wordpress
function seems_utf8($str) {
    $length = strlen($str);
    for ($i=0; $i < $length; $i++) {
        $c = ord($str[$i]);
        if ($c < 0x80) $n = 0; # 0bbbbbbb
        elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
        elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
        elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
        elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
        elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
        else return false; # Does not match any model
        for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
            if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
                return false;
        }
    }
    return true;
}
function sanitize($title) {
    $title = strip_tags($title);
    
    $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
    $title = str_replace('%', '', $title);
    $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

    if (seems_utf8($title)) {
        if (function_exists('mb_strtolower')) {
            $title = mb_strtolower($title, 'UTF-8');
        }
        $title = utf8_uri_encode($title, 200);
    }

    $title = strtolower($title);
    $title = preg_replace('/&.+?;/', '', $title); // kill entities
    $title = str_replace('.', '-', $title);
    $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
    $title = preg_replace('/\s+/', '-', $title);
    $title = preg_replace('|-+|', '-', $title);
    $title = trim($title, '-');

    return $title;
}

/*** Check timelog is duplicate entries ***/
if(isset($_POST['get_pro_time']) && isset($_POST['proj_id'])){
    
    /*$get_pro = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$_POST['proj_id']));
    $e_data = unserialize($get_pro['employee_ids']);
    $get_emp_col = array_search($_SESSION['loggedin_user'], array_column($e_data, 'employe_id'));*/
    $t_query = "SELECT * FROM db_timelog WHERE user_id='".$_SESSION['loggedin_user']."' and project_id=".$_POST['proj_id'];
    if(isset($_POST['task_id']) && !empty($_POST['task_id'])){
        $t_query = "SELECT * FROM db_timelog WHERE user_id='".$_SESSION['loggedin_user']."' and task_id =".$_POST['task_id']." and project_id=".$_POST['proj_id'];
    }
    $qry = mysqli_query($conn, $t_query );
    $pass_res = array();
    while($row = mysqli_fetch_assoc($qry)){
       array_push($pass_res, date('Y-m-d', strtotime($row['task_date']))); 
    }
    echo json_encode($pass_res);
    die;       
}
if(isset($_POST['clone_week']) && isset($_POST['clone_ids'])){

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

    $qry = mysqli_query($conn,"Select * from db_timelog WHERE task_date BETWEEN '" . $this_week_monday . " 00:00:00' AND '" . $this_week_sunday . " 00:00:00' AND user_id=".$_SESSION['loggedin_user']);

    $already_added = array();
    if($qry->num_rows > 0){
        while($row = mysqli_fetch_assoc($qry)){
            array_push($already_added,$row);
        }
    }

    $ex_week = explode(',', $_POST['clone_ids']);
    $pass_array = array();
    foreach ($ex_week as $ex_single) {

        $single_data    = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM db_timelog WHERE id=".$ex_single));
        $get_pro        = mysqli_fetch_assoc(mysqli_query($conn,"SELECT * FROM db_projects WHERE id=".$single_data['project_id']));

        $arr =  unserialize($get_pro['employee_ids']);
        $s = array_search($_SESSION['loggedin_user'], array_column($arr, 'employe_id'));
        $single_data['project_start_date'] = $arr[$s]['start_date'];
        $single_data['project_end_date'] = $arr[$s]['end_date'];
        array_push($pass_array,$single_data);

    }
    echo json_encode(array("last_week_data"=>$pass_array,"this_week_data"=>$already_added));
    die; 
}

if(isset($_POST['report_start_date'])){
    $u_id = $_SESSION['loggedin_user'];
    if(get_user_by_id($u_id)['type'] == 'company'){
        $comp_mem_ids = mysqli_fetch_assoc(mysqli_query($conn, "SELECT GROUP_CONCAT(id SEPARATOR ',') AS ids FROM db_users WHERE company_name=".$_SESSION['loggedin_user']));
        if(!empty($comp_mem_ids)){
             $u_id = $comp_mem_ids['ids'];
        }
    }
    if(isset($_POST['pass_user_id']) && !empty($_POST['pass_user_id'])){
        $u_id = $_POST['pass_user_id'];
    }
    
    $qry = mysqli_query($conn, "SELECT SUM( TIME_TO_SEC( total_time ) ) AS timeSum , task_date, status FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['report_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['report_end_date'])). " 00:00:00' AND user_id in(".$u_id.") GROUP by task_date, status");  

    $qry_1 = mysqli_query($conn, "SELECT SUM( TIME_TO_SEC( total_time ) ) AS timeSum , task_date, project_id FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['report_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['report_end_date'])). " 00:00:00' AND user_id in(".$u_id.") GROUP by project_id, task_date ");
    //echo "SELECT SUM( TIME_TO_SEC( total_time ) ) AS timeSum , task_date, project_id FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['report_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['report_end_date'])). " 00:00:00' AND user_id in(".$u_id.") GROUP by project_id, task_date ";
    //echo "SELECT SUM( TIME_TO_SEC( total_time ) ) AS timeSum , task_date, project_id FROM db_timelog where task_date BETWEEN '" .date("Y-m-d",strtotime($_POST['report_start_date'])). " 00:00:00' AND '" .date("Y-m-d",strtotime($_POST['report_end_date'])). " 00:00:00' AND user_id in(".$u_id.") GROUP by project_id, task_date ";
    
    $time_data = array();
    $project_data = array();
    $project_names = array();

    while($row = mysqli_fetch_assoc($qry)){
       
        $date_hour = $row['timeSum'];
        
        //$time = gmdate("H", $date_hour); //date('h', $date_hour);
        //if(gmdate("H", $date_hour) != 0){
            //$time .= '.'.gmdate("i", $date_hour);
        //}
        $time = $date_hour; //gmdate("i", $date_hour);
        //$time_data[str_replace(" 00:00:00", "", $row['task_date'])] = (float)$time;
        if(is_array($time_data[date("Y-m-d", strtotime($row['task_date']))][$row['status']])){
           $time = (float)$time_data[date("Y-m-d", strtotime($row['task_date']))][$row['status']][0]+(float)$time;
            //$time_data[date("Y-m-d", strtotime($row['task_date']))][$row['status']] = array();
        }
        $time_data[date("Y-m-d", strtotime($row['task_date']))][$row['status']][0] = (float)$time;
    }
    //print_r($time_data);
    $all_data = array();
    while($row_1 = mysqli_fetch_assoc($qry_1)){
        //print_r($row_1);
        $time_1 = gmdate("H", $row_1['timeSum']); //date('h', $date_hour);
        $time_1 .= '.'.gmdate("i", $row_1['timeSum']);
        $time_1 = (float)$time_data[date("Y-m-d", strtotime($row_1['task_date']))][$row_1['status']][0]+(float)$row_1['timeSum'];
        array_push($project_data, $time_1);

        $get_name = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_projects WHERE id=".$row_1['project_id']));
        array_push($project_names, $get_name['name']);
        if(isset($all_data[$get_name['name']])){
            $all_data[$get_name['name']] += $time_1;
        } else {
            $all_data[$get_name['name']] = $time_1;
        }
    }

    $project_names = array_keys($all_data);
    $project_data = array_values($all_data);

    echo json_encode(array("time_data"=>$time_data, "project_data"=>$project_data, "project_names"=>$project_names));
    die();
}
$is_ref_token = 0;
function send_zoho_mail($to, $subject, $msg){
    global $conn;
    
    $get_code = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_config WHERE option_key = 'zoho_code'"));
    $get_acc_token = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_config WHERE option_key = 'zoho_access_token'"));
    $get_account_id = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_config WHERE option_key = 'zoho_account_id'"));
    
    if(!empty($get_code)){
        

        $curl = curl_init();
        
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://mail.zoho.com/api/accounts/'.$get_account_id['option_value'].'/messages',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS =>'{"toAddress":"'.$to.'", "subject": "'.$subject.'", "content":"'.$msg.'","mailFormat":"html", "fromAddress":" Timesheethub <admin@timesheethub.com>"}',
          CURLOPT_HTTPHEADER => array(
            'Authorization: Zoho-oauthtoken '.$get_acc_token['option_value'],
            'Content-Type: application/json',
            'Cookie: zmuac=ODA3MjUzOTA3XzI0NjAwNDA=; JSESSIONID=BD1F89254D7A0A6C1D453A0236256F27; _zcsr_tmp=e94f34f7-c682-48f8-8e77-717f1a6422a0; fc2f5e4ce1=9d9cdac02b0aa549e15915272f874468; zmcsr=e94f34f7-c682-48f8-8e77-717f1a6422a0'
          ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        $res = json_decode($response);
       
        if($res->status->code == '404' && $is_ref_token == 0){
            $is_ref_token++;
            regenrate_token();
            send_zoho_mail($to, $subject, $msg);
        }
        //print_r($res);
        

    }
}

function regenrate_token(){
    global $conn;
    $get_ref_token = mysqli_fetch_assoc(mysqli_query($conn, "SELECT * FROM db_config WHERE option_key = 'zoho_refresh_token'"));

        $curl = curl_init();
        
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://accounts.zoho.com/oauth/v2/token?refresh_token='.$get_ref_token['option_value'].'&grant_type=refresh_token&client_id=1000.WU9BJHLEV32CV01E1NJEX3RVQ123IG&client_secret=662568743820374d80a585ef131c4f82083195372c&redirect_uri=https://timesheethub.com/?zoho_res=1&scope=VirtualOffice.messages.CREATE,VirtualOffice.accounts.READ',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json',
            'Cookie: JSESSIONID=CD0A3A00343923CDFC345697F41F34FD; _zcsr_tmp=9943b18f-188b-4bd9-b0fc-6031141e971c; b266a5bf57=57c7a14afabcac9a0b9dfc64b3542b70; iamcsr=9943b18f-188b-4bd9-b0fc-6031141e971c'
          ),
        ));
        
        $response = curl_exec($curl);

    curl_close($curl);
    $new_res = json_decode($response);
    if(isset($new_res->access_token)){
        mysqli_query($conn, "UPDATE db_config SET option_value='".$new_res->access_token."' WHERE option_key = 'zoho_access_token'");
    }

}
?>