<?php
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

include "config.php";
include "functions.php";

use \Firebase\JWT\JWT;
$postjson = json_decode(file_get_contents('php://input'), true);

error_reporting(E_ALL);
ini_set('display_errors', 1);

// Load environment variables
require __DIR__ . '/vendor/autoload.php';
use Dotenv\Dotenv;

$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Retrieve the secret key from the environment variables
$secret_key = $_ENV['SECRET_KEY'];

try {
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $pdo->exec("SET time_zone = '+03:00'");

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    die("Error: " . $e->getMessage());
}



if ($postjson["method"] == "editUserProfile") {
    try {
        $userId = $postjson['userId'];
        $setClauses = [];
        $params = [];

        if (empty($postjson['userId'])) {
            http_response_code(400); // Bad Request
            echo json_encode(array('success' => false, 'message' => 'userId is required.'));
            exit;
        }

        // Build the SET clauses dynamically based on non-empty fields
        if (!empty($postjson['userFirstName'])) {
            $setClauses[] = "userFirstName = :userFirstName";
            $params[':userFirstName'] = $postjson['userFirstName'];
        }

        if (!empty($postjson['userLastName'])) {
            $setClauses[] = "userLastName = :userLastName";
            $params[':userLastName'] = $postjson['userLastName'];
        }

        if (!empty($postjson['userPassword'])) {
            $hashedPassword = password_hash($postjson['userPassword'], PASSWORD_DEFAULT);
            $setClauses[] = "userPassword = :userPassword";
            $params[':userPassword'] = $hashedPassword;
        }
        if (!empty($postjson['userMobile'])) {
            $setClauses[] = "userMobile = :userMobile";
            $params[':userMobile'] = $postjson['userMobile'];
        }
        if (!empty($postjson['userEmail'])) {
            $setClauses[] = "userEmail = :userEmail";
            $params[':userEmail'] = $postjson['userEmail'];
        }

        if (!empty($postjson['userAddress'])) {
            $setClauses[] = "userAddress = :userAddress";
            $params[':userAddress'] = $postjson['userAddress'];
        }

        if (!empty($postjson['userState'])) {
            $setClauses[] = "userState = :userState";
            $params[':userState'] = $postjson['userState'];
        }

        if (!empty($postjson['userLatitude'])) {
            $setClauses[] = "userLatitude = :userLatitude";
            $params[':userLatitude'] = $postjson['userLatitude'];
        }

        if (!empty($postjson['userLongitude'])) {
            $setClauses[] = "userLongitude = :userLongitude";
            $params[':userLongitude'] = $postjson['userLongitude'];
        }

        if (!empty($setClauses)) {
            // Construct the SQL query
            $sql = "UPDATE users SET " . implode(", ", $setClauses) . " WHERE userId = :userId";
            $stmtProfile = $pdo->prepare($sql);

            // Bind parameters
            $stmtProfile->bindParam(':userId', $userId, PDO::PARAM_INT);
            foreach ($params as $key => $value) {
                $stmtProfile->bindValue($key, $value);
            }

            // Execute the query
            $stmtProfile->execute();
            http_response_code(200); 

            $stmt = $pdo->prepare("SELECT userId, userMobile, userEmail, userFirstName, userLastName, userAddress, userState, userLatitude, userLongitude FROM users WHERE userId = ? ");
            $stmt->execute([$postjson['userId']]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            $user['userLatitude'] = (double)$user['userLatitude'];
            $user['userLongitude'] = (double)$user['userLongitude'];
            echo json_encode(array('success' => true,"user"=>$user, 'message' => 'user profile updated sucessfully.'));
        } else {
            http_response_code(400); // Bad Request
            echo json_encode(array('success' => false, 'message' => 'No fields to update.'));
            exit;
        }
    } catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error.' . $e->getMessage()));
    }
}

if ($postjson["method"] == "phoneVerify") {

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE  userMobile = ?");
        $stmt->execute([$postjson['userMobile']]);
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
    }
        if (!empty($users)) {
            
    
            http_response_code(401); // Bad Request
            $response = array(
                'success' => false,
                'message' => 'User with the same phone number already exists.'
            );
        } else {

            $stmt = $pdo->prepare("SELECT * FROM tempUser WHERE  tempUserPhone = ?");
            $stmt->execute([$postjson['userMobile']]);
            $tempUsers = $stmt->fetchAll(PDO::FETCH_ASSOC);
            $tempUserCode=mt_rand(10000, 99999);

            if(empty($tempUsers)){
         
            $stmt = $pdo->prepare("INSERT INTO tempUser (tempUserPhone,tempUserCode,otp_generation_time) VALUES (?,?,NOW())");
    //         $stmt = $pdo->prepare("INSERT INTO users (userRole, userPassword, userMobile, userEmail, userFirstName, userLastName, userPic, userStatus, userVerificationCode, userAddress)
    // VALUES ('customer', ?, ?, ?, ?, ?, NULL, 'active', NULL, NULL)");
  // OTP URL Api https://josmsservice.com/SMSServices/Clients/Prof/RestSingleSMS_General/SendSMS?senderid=Mass%20Jo&numbers=9627********&accname=massjoapi&AccPass=fF9ro3D40fq5g@P3&msg=SMSBODY

  $phone=$postjson['userMobile'];

  $smsMsg="Your OTP is: $tempUserCode";
    
//   $phone= "962".$phone;
  $phone = "962" . ltrim($phone, '0');
//   echo $phone;


  $smsMsg = urlencode($smsMsg);
  $phone = urlencode($phone);

//   $url = "https://josmsservice.com/SMSServices/Clients/Prof/RestSingleSMS_General/SendSMS?senderid=Mass%20Jo&numbers=$phone&accname=massjoapi&AccPass=fF9ro3D40fq5g@P3&msg=$smsMsg";
  $url = "https://sendsms.ngt.jo/http/send_sms_http.php?login_name=pickum&login_password=PikJO@5719&msg=$smsMsg&mobile_number=$phone&from=Pickum%20JO&charset=UTF-8";
//    echo $url;
  $responseOTP = file_get_contents($url);

                if ($stmt->execute([$postjson['userMobile'],$tempUserCode]) && $responseOTP) {
                $response = array(
                                'success' => true,
                                'phone number' => $postjson['userMobile'],
                                'code' => $tempUserCode
                            );
            }else{
                
    
                $response = array(
                                'success' => false,
                                'message' => 'error in verification.'
                            );
            }

        }else{
            
            $stmt = $pdo->prepare("UPDATE tempUser SET tempUserCode = ?, otp_generation_time = NOW() WHERE tempUserPhone = ?");

            $phone=$postjson['userMobile'];

            $smsMsg="Your OTP is: $tempUserCode";
              
            // $phone= "962".$phone;
            $phone = "962" . ltrim($phone, '0');

            // echo $phone;
            $smsMsg = urlencode($smsMsg);
            $phone = urlencode($phone);
          
            // $url = "https://josmsservice.com/SMSServices/Clients/Prof/RestSingleSMS_General/SendSMS?senderid=Mass%20Jo&numbers=$phone&accname=massjoapi&AccPass=fF9ro3D40fq5g@P3&msg=$smsMsg";

  $url = "https://sendsms.ngt.jo/http/send_sms_http.php?login_name=pickum&login_password=PikJO@5719&msg=$smsMsg&mobile_number=$phone&from=Pickum%20JO&charset=UTF-8";

          //    echo $url;
            $responseOTP = file_get_contents($url);
            
            if ($stmt->execute([$tempUserCode,$postjson['userMobile']])) {
                $response = array(
                                'success' => true,
                                'msg'=>"the code has been updated!",
                                'phone number' => $postjson['userMobile'],
                                'code' => $tempUserCode
                            );
            }else{
                
    
                $response = array(
                                'success' => false,
                                'message' => 'error in generate code.'
                            );
            }

        }
        }
    
        echo json_encode($response);
}

if ($postjson["method"] == "phoneVerifyForResetPassword") {
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ?");
        $stmt->execute([$postjson['userMobile']]);
        
        // Check if the query was successful
        if ($stmt->rowCount() === 0) {
            http_response_code(401); // Unauthorized
            $response = array(
                'success' => false,
                'message' => 'User with the same phone number does not exist.'
            );
        } else {
            $tempUserCode = mt_rand(10000, 99999);

            $stmt = $pdo->prepare("UPDATE users SET userVerificationCode = ?, otp_generation_time = NOW() WHERE userMobile = ?");

            $phone=$postjson['userMobile'];

            $smsMsg="Your OTP is: $tempUserCode";
              
            // $phone= "962".$phone;
            $phone = "962" . ltrim($phone, '0');

            // echo $phone;
            $smsMsg = urlencode($smsMsg);
            $phone = urlencode($phone);
          
            // $url = "https://josmsservice.com/SMSServices/Clients/Prof/RestSingleSMS_General/SendSMS?senderid=Mass%20Jo&numbers=$phone&accname=massjoapi&AccPass=fF9ro3D40fq5g@P3&msg=$smsMsg";
  $url = "https://sendsms.ngt.jo/http/send_sms_http.php?login_name=pickum&login_password=PikJO@5719&msg=$smsMsg&mobile_number=$phone&from=Pickum%20JO&charset=UTF-8";

          //    echo $url;
            $responseOTP = file_get_contents($url);
            
            if ($stmt->execute([$tempUserCode, $postjson['userMobile']])) {
                $response = array(
                    'success' => true,
                    'message' => 'The code has been generated!',
                    'phone number' => $postjson['userMobile'],
                    'code' => $tempUserCode
                );
            } else {
                $errorInfo = $stmt->errorInfo();
                $response = array(
                    'success' => false,
                    'message' => 'Error in generating code.',
                    'error_details' => $errorInfo[2] // The error message
                );
            }
        }
    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
        // Log the error and handle it appropriately
        $response = array(
            'success' => false,
            'message' => 'Database error.'
        );
    }

    echo json_encode($response);
}

if ($postjson["method"] == "verifyCodeForResetPassword") {
    try {
        // $stmt = $pdo->prepare("SELECT * FROM tempUser WHERE  tempUserPhone = ? && tempUserCode = ?");
        $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ? && userVerificationCode = ? && otp_generation_time >= NOW() - INTERVAL 10 MINUTE");
        $stmt->execute([$postjson['userMobile'],$postjson['userCode']]);
        $user = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
    }

    if (!empty($user)) {

        $response = array(
            'success' => true,
            'msg' => "the user code is correct!"
        );
    
     
    } else {
        // Set the HTTP response code to 401 (Unauthorized)
        http_response_code(401);
        $response = array(
            'success' => false,
            'msg' => "the user code is not correct!"
        );
        
    }

    echo json_encode($response);
}

if ($postjson["method"] == "verifyCode") {
    try {
        // $stmt = $pdo->prepare("SELECT * FROM tempUser WHERE  tempUserPhone = ? && tempUserCode = ?");
        $stmt = $pdo->prepare("SELECT * FROM tempUser WHERE tempUserPhone = ? && tempUserCode = ? && otp_generation_time >= NOW() - INTERVAL 10 MINUTE");
        $stmt->execute([$postjson['userMobile'],$postjson['userCode']]);
        $user = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch (PDOException $e) {
        echo "Database Error: " . $e->getMessage();
    }

    if (!empty($user)) {

        $response = array(
            'success' => true,
            'msg' => "the user code is correct!"
        );
    
     
    } else {
        // Set the HTTP response code to 401 (Unauthorized)
        http_response_code(401);
        $response = array(
            'success' => false,
            'msg' => "the user code is not correct!"
        );
        
    }

    echo json_encode($response);
}

if ($postjson["method"] == "signup") {
    // Validate input fields 
    if (empty($postjson['userFirstName']) || empty($postjson['userPassword']) || empty($postjson['userEmail']) ||  empty($postjson['userMobile'])) {

        http_response_code(401); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'All fields are required.'));
        exit;
    }
    
    
    // Check if the email, userMobile combination already exists
    try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userEmail = ? OR userMobile = ?");
    $stmt->execute([$postjson['userEmail'], $postjson['userMobile']]);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    echo "Database Error: " . $e->getMessage();
}
    if (!empty($users)) {
        foreach ($users as $user) {
            if ($user['userVerifiedStatus'] == 'disabled') {
                $msg = 'user is disabled';
                $userEnabled = false;
                break;  // exit the loop if a disabled user is found
            } else {
                $userEnabled = true;
                // $msg = 'User with the same email, phone number already exists.';
                $msg = 'رقم الهاتف او الايميل موجود بالفعل';
            }
        }

        http_response_code(400); // Bad Request
        $response = array(
            'success' => false,
            'userEnabled'=>$userEnabled,
            'message' => $msg
        );
    } else {
        
        // Hash the password
        $hashedPassword = password_hash($postjson['userPassword'], PASSWORD_DEFAULT);

        // Insert user data into the database
        // $stmt = $pdo->prepare("INSERT INTO users (userFirstName, userLastName, userPassword, userEmail,userMobile, userType, userStatus)
        // VALUES (?, ?, ?, ?, ?, 'customer', 0)");
        $stmt = $pdo->prepare("INSERT INTO users (userRole, userPassword, userMobile, userEmail, userFirstName, userLastName, userPic, userStatus, userVerificationCode, userAddress,userFcm,userState,userLatitude,userLongitude,userVerifiedStatus)
VALUES ('customer', ?, ?, ?, ?, ?, NULL, 'inactive', NULL, ?,?,?,?,?,'enabled')");
        
            if ($stmt->execute([$hashedPassword, $postjson['userMobile'], $postjson['userEmail'], $postjson['userFirstName'], $postjson['userLastName'],$postjson['userAddress'],$postjson['userFcm'],$postjson['userState'],$postjson['userLatitude'],$postjson['userLongitude']])) {
               
                $user_id = $pdo->lastInsertId();
                $user_id = intval($user_id);
                
                $stmt = $pdo->prepare("DELETE FROM tempUser WHERE tempUserPhone = ?");
        $stmt->execute([$postjson['userMobile']]);

           
                $issuer_claim = 'picum';
            $audience_claim = 'pickum_user';
            $issued_at_claim = time();
            $not_before_claim = $issued_at_claim + 10; // Token can't be used before this time
            $expire_claim = $issued_at_claim + 7200; // Token will expire after 2 hours
            $token = array(
                'iss' => $issuer_claim,
                'aud' => $audience_claim,
                'iat' => $issued_at_claim,
                'nbf' => $not_before_claim,
                'exp' => $expire_claim,
                'data' => array(
                    'userMobile' => $postjson['userMobile']
                )
                );
                $jwt = JWT::encode($token, $secret_key, 'HS256');

                $user_data = array(
                    'userId' => $user_id,
                    'userFirstName' => $postjson['userFirstName'],
                    'userLastName' => $postjson['userLastName'],
                    'userMobile' => $postjson['userMobile'],
                    'userEmail' => $postjson['userEmail'],
                    'userFcm' => $postjson['userFcm'],
                    'userAddress' => $postjson['userAddress'],
                    'userState' => $postjson['userState'],
                    'userLatitude' => $postjson['userLatitude'],
                    'userLongitude' => $postjson['userLongitude'],
                    // Add other user data here
                );

                $response = array(
                            'success' => true,
                            'message' => 'User created successfully.',
                            'user' => $user_data,
                            'token' => $jwt
                        );



        }else{
            

            $response = array(
                            'success' => false,
                            'message' => 'User not created. Please contact support.'
                        );
        }
        
    }

    echo json_encode($response);

}

// if ($postjson["method"] == "login") {
//      // Validate input fields 
//      if (empty($postjson['userMobile']) || empty($postjson['userPassword'])) {
//         http_response_code(400); // Bad Request
//         echo json_encode(array('success' => false, 'message' => 'All fields are required.'));
//         exit;
//     }
//     // Check if the email, username, and company code combination already exists
//     $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ? ");
//     $stmt->execute([$postjson['userMobile']]);
//     $user = $stmt->fetch(PDO::FETCH_ASSOC);

//     if (empty($user)) {
//         http_response_code(401); // Bad Request
//         $response = array(
//             'success' => false,
//             'message' => 'User is not exists.'
//         );
//     }else{
//         // Verify the provided password against the stored hashed password
//         // $hashedPassword = password_hash($postjson['userPassword'], PASSWORD_DEFAULT);
//         // echo $postjson['userPassword']."//".$user['userPassword']."/////".$hashedPassword;
        
//         if (password_verify($postjson['userPassword'], $user['userPassword'])) {
//             $response = array(
//                 'success' => true,
//                 'message' => 'Login successful.',
//                 'user' => $user
//             );
//         } else {
//             $response = array(
//                 'success' => false,
//                 'message' => 'Incorrect password.'
//             );
//         }
//     }
//     echo json_encode($response);
// }

if ($postjson["method"] == "changePassword") {
    if (empty($postjson['userId']) || !is_numeric($postjson['userId']) || empty($postjson['userOldPassword']) || empty($postjson['userNewPassword'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'All Fields are required.'));
        exit;
    }
   
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userId = ? ");
    $stmt->execute([$postjson['userId']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($user)) {
        http_response_code(404 ); // Not Found
        $response = array(
            'success' => false,
            'message' => 'User does not exist.'
        );
        echo json_encode($response);
    } else {

        if (password_verify($postjson['userOldPassword'], $user['userPassword'])) {

        $hashedPassword = password_hash($postjson['userNewPassword'], PASSWORD_DEFAULT);

            $updateUserPassword=$pdo->prepare("UPDATE users SET userPassword=? WHERE userId=?");
            if($updateUserPassword->execute([$hashedPassword,$postjson['userId']])){
                http_response_code(200);
                $response = array(
                    'success' => true,
                    'message' => 'password has been changed successfully.',
                );
                echo json_encode($response);
            }else{
                $errorInfo = $updateUserPassword->errorInfo();
                http_response_code(400); // Bad Request
                $response = array(
                    'success' => false,
                    'message' => 'Password didn\'t change. Error: ' . $errorInfo[2]
                );
            echo json_encode($response);
            }


        }else {
            http_response_code(401); // Unauthorized
            $response = array(
                'success' => false,
                'message' => 'Incorrect password.'
            );
            echo json_encode($response);
        }
    }

}

if ($postjson["method"] == "removeAccount") {
 
    if (empty($postjson['userId']) || !is_numeric($postjson['userId'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'userId is required.'));
        exit;
    }
    $stmt = $pdo->prepare("UPDATE users SET userVerifiedStatus='disabled' WHERE userId=? ");
    if($stmt->execute([$postjson['userId']])){

        http_response_code(200); 
        echo json_encode(array('success' => true, 'message' => 'user has been removed.'));
    }else{
        http_response_code(400); // Bad Request
        $errorInfo = $stmt->errorInfo();
        echo json_encode(array('success' => false, 'message' => 'User has not been removed. Error: ' . $errorInfo[2]));    }

}

if ($postjson["method"] == "login") {
   
    // Validate input fields
    if (empty($postjson['userMobile']) || empty($postjson['userPassword'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'All fields are required.'));
        exit;
    }
    // Check if the user with the provided mobile number exists
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ? AND userRole='customer'");
    $stmt->execute([$postjson['userMobile']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($user)) {
        http_response_code(404 ); // Not Found
        $response = array(
            'success' => false,
            'message' => 'User does not exist.'
        );
        echo json_encode($response);
    } else {

      
            if ($user['userVerifiedStatus'] == 'disabled') {
                $msg = 'user is disabled';
                $userEnabled = false;
                $response = array(
                    'success' => false,
                    'userEnabled'=>$userEnabled,
                    'message' => 'User is disabled.'
                );
                echo json_encode($response);
            } else {
                $userEnabled = true;
                
            
        
        
        // Verify the provided password against the stored hashed password
        if (password_verify($postjson['userPassword'], $user['userPassword'])) {

            $user['userLatitude'] = (double)$user['userLatitude'];
            $user['userLongitude'] = (double)$user['userLongitude'];

            // Generate a JWT token
            $issuer_claim = 'picum';
            $audience_claim = 'pickum_user';
            $issued_at_claim = time();
            $not_before_claim = $issued_at_claim + 10; // Token can't be used before this time
            $expire_claim = $issued_at_claim + 7200; // Token will expire after 2 hours
            $token = array(
                'iss' => $issuer_claim,
                'aud' => $audience_claim,
                'iat' => $issued_at_claim,
                'nbf' => $not_before_claim,
                'exp' => $expire_claim,
                'data' => array(
                    'userMobile' => $user['userMobile'],
                    'userId' => $user['userId'] 
                )
            );

            // Update the user's FCM token
            $newFcmToken = $postjson['userFcm']; // Replace with the actual FCM token
            $stmt = $pdo->prepare("UPDATE users SET userFcm = ? WHERE userId = ?");
            $stmt->execute([$newFcmToken, $user['userId']]);
            // $jwt = JWT::encode($token, $secret_key);
            $jwt = JWT::encode($token, $secret_key, 'HS256');


            // Respond with the JWT token
            $response = array(
                'success' => true,
                'message' => 'Login successful.',
                'userEnabled'=>$userEnabled,
                'user' => $user,
                'newFcm'=>$newFcmToken,
                'token' => $jwt
            );
            echo json_encode($response);
        
        } else {
            http_response_code(401); // Unauthorized
            $response = array(
                'success' => false,
                'message' => 'Incorrect password.'
            );
            echo json_encode($response);
        }
    }
    }
}


if ($postjson["method"] == "resetPassword") {
    // Validate input fields
    if (empty($postjson['userMobile']) || empty($postjson['userPassword'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'User mobile and new password are required.'));
        exit;
    }

    // Check if the user exists based on the provided mobile number
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ?");
    $stmt->execute([$postjson['userMobile']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($user)) {
        http_response_code(404); // Not Found
        echo json_encode(array('success' => false, 'message' => 'User not found.'));
        exit;
    }

    // Update the user's password
    $hashedPassword = password_hash($postjson['userPassword'], PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("UPDATE users SET userPassword = ? WHERE userMobile = ?");
    if ($stmt->execute([$hashedPassword, $postjson['userMobile']])) {
        // Password reset successful
        echo json_encode(array('success' => true, 'message' => 'Password reset successful.'));
    } else {
        // Password reset failed
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Password reset failed. Please contact support.'));
    }
}



if ($postjson["method"] == "getAllCustomers") {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userRole = ? ");
    $stmt->execute(['customer']);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    // echo "SSSS";
    if (count($users) > 0) {
     
        $response = array(
            'success' => true,
            'message' => 'all customers',
            'customers' => $users
        );
    }else{
        http_response_code(400);
        $response = array(
            'success' => false,
            'message' => 'No available customers',
        );
    }
    echo json_encode($response);

}



function generateVerificationLink($token)
{
    return 'http://domain.com/verify?token=' . $token;
}

function generateToken($length = 32)
{
    $tokenBytes = random_bytes($length);
    return bin2hex($tokenBytes);
}

?>