<?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 {
    date_default_timezone_set('Asia/Amman');
    $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"] == "nashmiVerifiedStatus") {
    try {

        $stmtCheckVendor = $pdo->prepare("SELECT * FROM users WHERE userId = ? AND userRole = 'vendor'");
        $stmtCheckVendor->execute([$postjson['vendorId']]);
        $vendorExists = $stmtCheckVendor->fetch(PDO::FETCH_ASSOC);
        if(empty($vendorExists)){
            http_response_code(404 ); // Not Found
        $response = array(
            'success' => false,
            'message' => 'Vendor is not exist.'
        );
        echo json_encode($response);
        }else{
            http_response_code(200);
                $response = array(
                    'success' => true,
                    'VendorVerified'=>$vendorExists['userVerifiedStatus']
                );
                echo json_encode($response);
        }
        
    } catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error.' . $e->getMessage()));
    }
}

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"] == "editNashmiProfile") {
    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($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"] == "addSubSpecToVendor") {


    try{

        $stmtVendorSubSpec=$pdo->prepare("INSERT INTO vendorSpecialties (vsUserId,subSpecId) VALUE(?, ?)");
        $stmtVendorSubSpec->execute([$postjson["venderId"],$postjson["subSpecId"]]);
        if($stmtVendorSubSpec){
            echo json_encode(array('success' => true, 'message' => 'sup Spec inserted successfully!' ));
        }else{
            echo json_encode(array('success' => false, 'message' => 'sup Spec not inserted!' ));
        
        }

    }catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error.'. $e->getMessage()));
    }

}

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

    try{
            $stmt=$pdo->prepare("SELECT r.*, 
            u_vendor.*,
            u_customer.userFirstName AS customerFirstName, u_customer.userLastName AS customerLastName, u_customer.userEmail AS customerEmail,
            u_customer.userMobile AS customerMobile,
            s.subSpecNameAr
            FROM requests r
            INNER JOIN users u_vendor ON u_vendor.userId = r.reqVenderId
            INNER JOIN users u_customer ON u_customer.userId = r.reqUserId
            INNER JOIN subSpecialties s ON s.subSpecId = r.reqSubSpecId
            WHERE r.reqId = ?
        ");
        $stmt->execute([$postjson['reqId']]);
        $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $count=$stmt->rowCount();
        if($count>0){
            echo json_encode(array('success' => true, 'request' => $requests ));
        }else{
            echo json_encode(array('success' => false, 'message' => 'no requests for this id'));

        }
       

        

    } catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error.'. $e->getMessage()));
    }
}

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

    try{
        $stmtCheckUser=$pdo->prepare("SELECT userRole from users WHERE userId =?");
        $stmtCheckUser->execute([$postjson["venderId"]]);
        $userRole=$stmtCheckUser->fetchColumn();
        if($userRole=="vendor"){
            $stmt=$pdo->prepare("SELECT r.*, 
            u_vendor.*,
            u_customer.userFirstName AS customerFirstName, u_customer.userLastName AS customerLastName, u_customer.userEmail AS customerEmail,
            u_customer.userMobile AS customerMobile,
            s.subSpecNameAr
            FROM requests r
            INNER JOIN users u_vendor ON u_vendor.userId = r.reqVenderId
            INNER JOIN users u_customer ON u_customer.userId = r.reqUserId
            INNER JOIN subSpecialties s ON s.subSpecId = r.reqSubSpecId
            WHERE r.reqVenderId = ?
        ");
        $stmt->execute([$postjson['venderId']]);
        $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $count=$stmt->rowCount();
        if($count>0){
            echo json_encode(array('success' => true, 'requests' => $requests ));
        }else{
            echo json_encode(array('success' => false, 'message' => 'no requests for this user'));

        }
        }else{
            echo json_encode(array('success' => false, 'message' => 'invalid user'));
        }

        

    } catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error.'. $e->getMessage()));
    }
}
if ($postjson["method"] == "changeVenderStatusSignup") {

}
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)) {

        http_response_code(400); // Bad Request
        $response = array(
            'success' => false,
            // 'message' => 'User with the same email, phone number already exists.'
            'message' => 'رقم الهاتف او الايميل موجود بالفعل'
        );
    } else {
        
        // Hash the password
        $hashedPassword = password_hash($postjson['userPassword'], PASSWORD_DEFAULT);

       
        $stmt = $pdo->prepare("INSERT INTO users (userRole, userPassword, userMobile, userEmail, userFirstName, userLastName, userPic, userStatus, userVerificationCode, userAddress,userFcm,userState,userLatitude,userLongitude,userCredit,userVerifiedStatus)
VALUES ('vendor', ?, ?, ?, ?, ?, NULL, 'inactive', NULL, ?,?,?,?,?,0,'disabled')");
        
            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);

        $stmtVendorSubSpec=$pdo->prepare("SELECT * FROM vendorSpecialties WHERE vsUserId=?");
        $stmtVendorSubSpec->execute([$user_id]);
        $VendorSubSpec = $stmtVendorSubSpec->fetchAll(PDO::FETCH_ASSOC);
                if(!empty($VendorSubSpec)){
                    $vendorHasSubSpec=true;
                }else{
                    $vendorHasSubSpec=false;
                }

        $stmtVendorCarSpec=$pdo->prepare("SELECT * FROM vendorCar WHERE vcUserId=?");
        $stmtVendorCarSpec->execute([$user_id]);
        $stmtVendorCar = $stmtVendorCarSpec->fetchAll(PDO::FETCH_ASSOC);


        if(!empty($stmtVendorCar)){
            $vendorHasCarSpecifications=true;
        }else{
            $vendorHasCarSpecifications=false;
        }



                
                $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'],
                    'userCredit' => 100
                    

                    // Add other user data here
                );

                $response = array(
                            'success' => true,
                            'message' => 'User created successfully.',
                            'user' => $user_data,
                            'vendorHasCarSpecifications'=>$vendorHasCarSpecifications,
                    'vendorHasSubSpec'=>$vendorHasSubSpec,
                            '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 user with the provided mobile number exists
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ? AND userRole='vendor'");
    $stmt->execute([$postjson['userMobile']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($user)) {
        http_response_code(401); // Unauthorized
        $response = array(
            'success' => false,
            'message' => 'User is not exist.'
        );
        echo json_encode($response);
    } else {
        
        // 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'] 
                )
            );

            $stmtVendorSubSpec=$pdo->prepare("SELECT * FROM vendorSpecialties WHERE vsUserId=?");
            $stmtVendorSubSpec->execute([$user['userId']]);
            $VendorSubSpec = $stmtVendorSubSpec->fetchAll(PDO::FETCH_ASSOC);
                    if(!empty($VendorSubSpec)){
                        $vendorHasSubSpec=true;
                    }else{
                        $vendorHasSubSpec=false;
                    }
    
            $stmtVendorCarSpec=$pdo->prepare("SELECT * FROM vendorCar WHERE vcUserId=?");
            $stmtVendorCarSpec->execute([$user['userId']]);
            $stmtVendorCar = $stmtVendorCarSpec->fetchAll(PDO::FETCH_ASSOC);
    
    
            if(!empty($stmtVendorCar)){
                $vendorHasCarSpecifications=true;
            }else{
                $vendorHasCarSpecifications=false;
            }
    

            // Update the user's FCM token
            $newFcmToken = $postjson['userFcm']; // Replace with the actual FCM token
            $stmt = $pdo->prepare("UPDATE users SET userFcm = ? , userStatus = 'inactive' 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.',
                'user' => $user,
                'vendorHasCarSpecifications'=>$vendorHasCarSpecifications,
                'vendorHasSubSpec'=>$vendorHasSubSpec,
                '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"] == "phoneVerify") {

    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE  userMobile = ? AND userRole='vendor'");
        $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.'
                'message' => 'رقم الهاتف موجود بالفعل'
            );
        } 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)");

    $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])) {
                $response = array(
                                'success' => true,
                                'phone number' => $postjson['userMobile'],
                                'code' => $tempUserCode
                            );
            }else{
                
    
                $response = array(
                                'success' => false,
                                'message' => 'error in generate code.'
                            );
            }

        }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"] == "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"] == "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"] == "phoneVerifyForResetPassword") {
    try {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE userMobile = ? AND userRole='vendor'");
        $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.'
                'message' => 'رقم الهاتف موجود بالفعل'
            );
        } else {
            $tempUserCode = mt_rand(10000, 99999);

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

            // $smsMsg="Your OTP is: $tempUserCode";
            $smsMsg="Your OTP is $tempUserCode \nOxcWE23KxKl";

    
//   $phone= "962".$phone;
  $phone=$postjson['userMobile'];

  $phone = "962" . ltrim($phone, '0');


  $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"] == "venderCarSpecifications") {
    // Validate input fields
    $requiredFields = ['venderId', 'subSpecId', 'panelNumber', 'carlicenseExpire', 'drivingExpire', 'carBrand', 'carModel','carYear'];
    foreach ($requiredFields as $field) {
        if (empty($postjson[$field])) {
            http_response_code(400); // Bad Request
            echo json_encode(array('success' => false, 'message' => $field . ' is required.'));
            exit;
        }
    }

    try {
        // Check if the vendor, and specialty exist
       
        $stmtCheckVendor = $pdo->prepare("SELECT COUNT(*) as count FROM users WHERE userId = ? AND userRole = 'vendor'");
        $stmtCheckVendor->execute([$postjson['venderId']]);
        $vendorExists = $stmtCheckVendor->fetch(PDO::FETCH_ASSOC)['count'];

        $stmtCheckSpec = $pdo->prepare("SELECT COUNT(*) as count FROM subSpecialties WHERE subSpecId = ?");
        $stmtCheckSpec->execute([$postjson['subSpecId']]);
        $specExists = $stmtCheckSpec->fetch(PDO::FETCH_ASSOC)['count'];

        if ($vendorExists && $specExists) {

            $stmtCheckVendorEnabled = $pdo->prepare("SELECT COUNT(*) as count FROM users WHERE userId = ? AND userRole = 'vendor' AND userVerifiedStatus='enabled'");
            $stmtCheckVendorEnabled->execute([$postjson['venderId']]);
            $vendorEnabled = $stmtCheckVendorEnabled->fetch(PDO::FETCH_ASSOC)['count'];

            if($vendorEnabled)
            {

            

            $stmtCheckCarInfo = $pdo->prepare("SELECT COUNT(*) as count FROM vendorCar WHERE vcUserId = ?");
            $stmtCheckCarInfo->execute([$postjson['venderId']]);
            $carInfoExists = $stmtCheckCarInfo->fetch(PDO::FETCH_ASSOC)['count'];

            if ($carInfoExists) {
                // Vendor has already entered car information, return failure response
                echo json_encode(['success' => false, 'message' => 'Vendor has already entered car information.']);
            } else {
            // Insert the new request into the requests table

            $stmt = $pdo->prepare("
                INSERT INTO vendorCar (vcUserId, vcPanelNumber, vcCarlicenseExpire, vcDrivingExpire, vcCarBrand, vcCarModel,vcCarYear)
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $postjson['venderId'],
                $postjson['panelNumber'],
                $postjson['carlicenseExpire'],
                $postjson['drivingExpire'],
                $postjson['carBrand'],
                $postjson['carModel'],
                $postjson['carYear']
            ]);
            //update vendor credit for subSpec 1 & 2 to 0
            if($postjson['subSpecId']==1 || $postjson['subSpecId']==2){
                $updateVendorCreditStmt=$pdo->prepare("UPDATE users SET userCredit = 0 WHERE userId = ?");
                $updateVendorCreditStmt->execute([$postjson['venderId']]);
            }

             // Insert vendor and specialty into vendorSpecialties table
             $stmtInsertSpecialty = $pdo->prepare("
             INSERT INTO vendorSpecialties (vsUserId, subSpecId)
             VALUES (?, ?)
         ");
         $stmtInsertSpecialty->execute([
             $postjson['venderId'],
             $postjson['subSpecId']
         ]);

            // Return success response
            echo json_encode(['success' => true, 'message' => 'Car Specifications added successfully.']);
        }
    }else{
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Vendor is disabled.']);

        }
        } 
        else {
            // Return failure response if user, vendor, or specialty doesn't exist
            http_response_code(401);
            echo json_encode(['success' => false, 'message' => 'Invalid vendor, or sub specialty.']);
        }
    } catch (PDOException $e) {
        // Return failure response for any database error
        http_response_code(500); // Internal Server Error
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}



if ($postjson["method"] == "completeRequest") {
    // Validate input fields
    if (empty($postjson['reqId'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'reqId is required.'));
        exit;
    }

    try {
        // Check if the request exists
        $stmtCheckRequest = $pdo->prepare("SELECT COUNT(*) as count FROM requests WHERE reqId = ? AND reqStatus='pending'");
        $stmtCheckRequest->execute([$postjson['reqId']]);
        $requestExists = $stmtCheckRequest->fetch(PDO::FETCH_ASSOC)['count'];

        if ($requestExists) {
            // Update the request status to "completed"
            $stmtUpdateRequest = $pdo->prepare("UPDATE requests SET reqStatus = 'completed' WHERE reqId = ?");
            $stmtUpdateRequest->execute([$postjson['reqId']]);

            $userFcm=$pdo->prepare("SELECT userFcm from users WHERE userId =(select reqUserId from requests WHERE reqId=?)");
            $userFcm->execute([$postjson['reqId']]);
            $fcm=$userFcm->fetchColumn();
                sendGCM("الطلب","تم اكمال طلبك ",$fcm,"none","none",true);
                
            // Return success response
            echo json_encode(['success' => true, 'message' => 'Request completed successfully.']);
        } else {
            // Return failure response if the request doesn't exist
            http_response_code(404); // Not Found
            echo json_encode(['success' => false, 'message' => 'Request not found Or request status is not pending.']);
        }
    } catch (PDOException $e) {
        // Return failure response for any database error
        http_response_code(500); // Internal Server Error
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}

if ($postjson["method"] == "acceptRequest") {
        // Validate input fields
        if (empty($postjson['reqId'])) {
            http_response_code(400); // Bad Request
            echo json_encode(array('success' => false, 'message' => 'reqId is required.'));
            exit;
        }
    
        try {
            // Check if the request exists
            $stmtCheckRequest = $pdo->prepare("SELECT COUNT(*) as count FROM requests WHERE reqId = ? AND reqStatus='new'");
            $stmtCheckRequest->execute([$postjson['reqId']]);
            $requestExists = $stmtCheckRequest->fetch(PDO::FETCH_ASSOC)['count'];
    
            if ($requestExists) {

                $userFcm=$pdo->prepare("SELECT userFcm from users WHERE userId =(select reqUserId from requests WHERE reqId=?)");
                $userFcm->execute([$postjson['reqId']]);
                $fcm=$userFcm->fetchColumn();
                sendGCM("الطلب","تم قبول طلبك ",$fcm,"none","none",true);

                $vendorPrecentage=$pdo->prepare("SELECT vendorPrecentage FROM subSpecialties WHERE subSpecId=(SELECT reqSubSpecId from requests WHERE reqId=?)");
                $vendorPrecentage->execute([$postjson['reqId']]);
                $precentage=$vendorPrecentage->fetchColumn();
                // echo $precentage;

                // if(!empty($precentage)){

                    if($precentage!=0){

                //vendor credit
                $stmtUserCredit=$pdo->prepare("SELECT userCredit from users WHERE userId =?");
                $stmtUserCredit->execute([$postjson['vendorId']]);
                $userCredit=$stmtUserCredit->fetchColumn();

                //service fee
                $stmtServiceFee=$pdo->prepare("SELECT serviceFee from subSpecialties WHERE subSpecId =(SELECT reqSubSpecId FROM requests WHERE reqId=?)");
                $stmtServiceFee->execute([$postjson['reqId']]);
                $serviceFee=$stmtServiceFee->fetchColumn();

                //Request Total price
                $stmtReqTotalPric=$pdo->prepare("SELECT reqTotalPrice from requests WHERE reqId =?");
                $stmtReqTotalPric->execute([$postjson['reqId']]);
                $reqTotalPrice=$stmtReqTotalPric->fetchColumn();

                // new vendor credit = (reqTotalPrice - serviceFee) * venderPresentage + 1 
                $newVendorCredit = $userCredit - ((($reqTotalPrice - $serviceFee) * ($precentage / 100)) + 1);
                $venderCreditStmt=$pdo->prepare("UPDATE users Set userCredit = $newVendorCredit WHERE userId = ?");
                // $venderCreditStmt=$pdo->prepare("UPDATE users Set userCredit=(userCredit - userCredit * $precentage/100) WHERE userId = ?");

                // Update the request status to "pending"
                $stmtUpdateRequest = $pdo->prepare("UPDATE requests SET reqStatus = 'pending' WHERE reqId = ?");
                // $stmtUpdateRequest->execute([$postjson['reqId']]);

                
                    if($venderCreditStmt->execute([$postjson['vendorId']]) && $stmtUpdateRequest->execute([$postjson['reqId']]))
                // Return success response
            {
                
                echo json_encode(['success' => true, 'message' => 'Request accepted successfully.']);
            }else{
                echo json_encode(['success' => false, 'message' => 'error in updating credit or req status.']);

            }
                }else{
                $stmtUpdateRequest = $pdo->prepare("UPDATE requests SET reqStatus = 'pending' WHERE reqId = ?");
                    if($stmtUpdateRequest->execute([$postjson['reqId']]))
                    // Return success response
                {
                    echo json_encode(['success' => true, 'message' => 'Request accepted successfully.']);
                }else{
                    echo json_encode(['success' => false, 'message' => 'error in updating the req status.']);
    
                }
                }

        // }else{
        //     echo json_encode(['success' => false, 'message' => 'No Vendor precentage founded.']);
        // }

            } else {
                // Return failure response if the request doesn't exist
                http_response_code(404); // Not Found
                echo json_encode(['success' => false, 'message' => 'Request not found Or not new.']);
            }
        } catch (PDOException $e) {
            // Return failure response for any database error
            http_response_code(500); // Internal Server Error
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
    }
    

    
if ($postjson["method"] == "rejectRequest") {
    // Validate input fields
    if (empty($postjson['reqId'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'reqId is required.'));
        exit;
    }

    try {
        // Check if the request exists
        $stmtCheckRequest = $pdo->prepare("SELECT COUNT(*) as count FROM requests WHERE reqId = ? AND reqStatus='new'");
        $stmtCheckRequest->execute([$postjson['reqId']]);
        $requestExists = $stmtCheckRequest->fetch(PDO::FETCH_ASSOC)['count'];

        if ($requestExists) {

            $userFcm=$pdo->prepare("SELECT userFcm from users WHERE userId =(select reqUserId from requests WHERE reqId=?)");
                $userFcm->execute([$postjson['reqId']]);
                $fcm=$userFcm->fetchColumn();
                sendGCM("الطلب","تم رفض طلبك ",$fcm,"none","none",true);

                $stmtReqSubSpec=$pdo->prepare("SELECT reqSubSpecId FROM requests WHERE reqId=?");
                $stmtReqSubSpec->execute([$postjson['reqId']]);
                $subSpec=$stmtReqSubSpec->fetchColumn();

                if($subSpec==1 || $subSpec==2){
            // decreace 1.5 d from vendor credit if subSpec 1 or 2
            $stmtVendorCredit = $pdo->prepare("UPDATE users SET userCredit = userCredit - 0 WHERE userId = (SELECT reqVenderId FROM requests WHERE reqId = ?)");
            $stmtVendorCredit->execute([$postjson['reqId']]);
                }else{   
                    // decreace 2 d from vendor credit
                    $stmtVendorCredit = $pdo->prepare("UPDATE users SET userCredit = userCredit - 2 WHERE userId = (SELECT reqVenderId FROM requests WHERE reqId = ?)");
                    $stmtVendorCredit->execute([$postjson['reqId']]);
                }

            // Update the request status to "rejected"
            $stmtUpdateRequest = $pdo->prepare("UPDATE requests SET reqStatus = 'rejected' WHERE reqId = ?");
            $stmtUpdateRequest->execute([$postjson['reqId']]);

            // Return success response
            echo json_encode(['success' => true, 'message' => 'Request rejected!']);
        } else {
            // Return failure response if the request doesn't exist
            http_response_code(404); // Not Found
            echo json_encode(['success' => false, 'message' => 'Request not found OR request status is not new.']);
        }
    } catch (PDOException $e) {
        // Return failure response for any database error
        http_response_code(500); // Internal Server Error
        echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
    }
}

if ($postjson["method"] == "getVenderHomeData") {
    // Validate input fields
    if (empty($postjson['venderId'])) {
        http_response_code(400); // Bad Request
        echo json_encode(array('success' => false, 'message' => 'venderId is required.'));
        exit;
    }

    try {

        // 0. Retrieve vender  spec from venderSpecialties table
        $stmtVenderSpec = $pdo->prepare("SELECT s.specId, s.specNameAr, s.specPhoto
        FROM specialties s WHERE s.specId = 
        (SELECT ss.specId from subSpecialties ss WHERE ss.subSpecId=
        (SELECT subSpecId from vendorSpecialties WHERE vsUserId=?))");

        $stmtVenderSpec->execute([$postjson['venderId']]);
        // $venderSpec = $stmtVenderSpec->fetchAll(PDO::FETCH_ASSOC);
        $venderSpec = $stmtVenderSpec->fetch(PDO::FETCH_ASSOC);
        // $venderSpec = $stmtVenderSpec->fetchColumn();

        $specPhoto = $venderSpec['specPhoto'];
        $specSpecNameAr = $venderSpec['specNameAr'];
        $specId=$venderSpec['specId'];

        // 1. Retrieve vender sub spec from venderSpecialties table
        $stmtVenderSubSpec = $pdo->prepare("SELECT s.subSpecNameAr, s.subSpecPhoto
        FROM vendorSpecialties vs
        JOIN subSpecialties s ON vs.subSpecId = s.subSpecId
        WHERE vs.vsUserId = ?");
        $stmtVenderSubSpec->execute([$postjson['venderId']]);
        // $venderSubSpec = $stmtVenderSubSpec->fetchColumn();
        $venderSubSpec = $stmtVenderSubSpec->fetch(PDO::FETCH_ASSOC);

        // Access subSpecNameAr
        $subSpecNameAr = $venderSubSpec['subSpecNameAr'];



        // 2. Retrieve vender credit from user table
        $stmtVenderCredit = $pdo->prepare("SELECT userCredit FROM users WHERE userId = ?");
        $stmtVenderCredit->execute([$postjson['venderId']]);
        $venderCredit = $stmtVenderCredit->fetchColumn();

        // 3. Retrieve the total requests this vender completes from requests table within the current day
        $stmtCompletedRequests = $pdo->prepare("SELECT COUNT(*) FROM requests WHERE reqVenderId = ? AND reqStatus = 'completed'");
        $stmtCompletedRequests->execute([$postjson['venderId']]);
        $completedRequestsCount = $stmtCompletedRequests->fetchColumn();

        // 4. Retrieve the requests this vender rejects within the current day
        $stmtRejectedRequests = $pdo->prepare("SELECT COUNT(*) FROM requests WHERE reqVenderId = ? AND reqStatus = 'rejected'");
        $stmtRejectedRequests->execute([$postjson['venderId']]);
        $rejectedRequestsCount = $stmtRejectedRequests->fetchColumn();

        // 5. Retrieve the requests this vender gets with "reqStatus= new"
        $stmtNewRequests = $pdo->prepare("SELECT COUNT(*) FROM requests WHERE reqVenderId = ? AND reqStatus = 'new'");
        $stmtNewRequests->execute([$postjson['venderId']]);
        $newRequestsCount = $stmtNewRequests->fetchColumn();

        // 6. Retrieve the requests this vender gets with "reqStatus= pending" and waiting for his confirmation
        $stmtPendingRequests = $pdo->prepare("SELECT COUNT(*) FROM requests WHERE reqVenderId = ? AND reqStatus = 'pending'");
        $stmtPendingRequests->execute([$postjson['venderId']]);
        $pendingRequestsCount = $stmtPendingRequests->fetchColumn();

        // 7. Retrieve vender status from user table
        $stmtVenderStatus = $pdo->prepare("SELECT userStatus FROM users WHERE userId = ?");
        $stmtVenderStatus->execute([$postjson['venderId']]);
        $venderStatus = $stmtVenderStatus->fetchColumn();


        // Prepare the response array
        $response = array(
            'success' => true,
            'venderSpecId' => $specId,
            'venderSpec' => $specSpecNameAr,
            'specPhoto' =>$specPhoto,
            'venderSubSpec' => $subSpecNameAr,
            'venderCredit' => $venderCredit,
            'venderStatus' => $venderStatus,
            'completedRequestsCount' => $completedRequestsCount,
            'rejectedRequestsCount' => $rejectedRequestsCount,
            'newRequestsCount' => $newRequestsCount,
            'pendingRequestsCount' => $pendingRequestsCount
        );

        // Return the response as JSON
        echo json_encode($response);
    } catch (PDOException $e) {
        http_response_code(500); // Internal Server Error
        echo json_encode(array('success' => false, 'message' => 'Database error: ' . $e->getMessage()));
    }
}

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

    // Validate input fields
    $requiredFields = ['venderId', 'venderStatus'];
    foreach ($requiredFields as $field) {
        if (empty($postjson[$field])) {
            http_response_code(400); // Bad Request
            echo json_encode(array('success' => false, 'message' => $field . ' is required.'));
            exit;
        }
    }
    // if (empty($postjson['venderId']) || empty($postjson['venderStatus'])) {
    //     http_response_code(400); // Bad Request
    //     echo json_encode(array('success' => false, 'message' => 'venderId and venderStatus are required.'));
    //     exit;
    // }

    // Check if the provided venderId belongs to a vender in the users table
    $stmtCheckVender = $pdo->prepare("SELECT COUNT(*) as count FROM users WHERE userId = ? AND userRole = 'vendor'");
    $stmtCheckVender->execute([$postjson['venderId']]);
    $venderExists = $stmtCheckVender->fetch(PDO::FETCH_ASSOC)['count'];

    if ($venderExists) {
       
        if($postjson['venderStatus']=="active"){
                    // Update the vendor status & location info in the users table
                $stmtUpdateStatus = $pdo->prepare("UPDATE users SET userStatus = ? , userAddress = ? , userState = ? , userLatitude = ? , userLongitude = ? WHERE userId = ?");
                $stmtUpdateStatus->execute([$postjson['venderStatus'],$postjson['userAddress'],$postjson['userState'],$postjson['userLatitude'],$postjson['userLongitude'], $postjson['venderId']]);

            $stmtVendorActivity=$pdo->prepare("INSERT INTO vendorActivityLog(activityUserId,activityStatus) VALUES(?, 'active')");

            if($stmtVendorActivity->execute([$postjson['venderId']])){
                $log=true;
            }else{
                $log=false;
            }
        }else {
               // Update the vendor status in the users table
               $stmtUpdateStatus = $pdo->prepare("UPDATE users SET userStatus = ? WHERE userId = ?");
               $stmtUpdateStatus->execute([$postjson['venderStatus'],$postjson['venderId']]);

            // Update the last record for the vendor where activityEndTime is NULL
            $stmtUpdateActivityEndTime = $pdo->prepare("UPDATE vendorActivityLog SET activityEndTime = CURRENT_TIMESTAMP WHERE activityUserId = ? AND activityEndTime IS NULL ORDER BY activityStartTime DESC LIMIT 1");
            if ($stmtUpdateActivityEndTime->execute([$postjson['venderId']])) {
                $log = true;
            } else {
                $log = false;
            }
        }

        echo json_encode(array('success' => true, 'message' => 'Vender status updated successfully.','activity Log'=>$log));
    } else {
        // Return failure response if the provided venderId doesn't belong to a vender
        http_response_code(401);
        echo json_encode(array('success' => false, 'message' => 'Invalid venderId.'));
    }
}
