<?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";


mysqli_set_charset($mysqli, 'utf8');

$postjson = json_decode(file_get_contents('php://input'),true);


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 = "Asia/Amman"');
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    die("Error: " . $e->getMessage());
}

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 = ? AND (userRole= 'admin' OR userRole='subAdmin') AND userVerifiedStatus='enabled'");
   $stmt->execute([$postjson['userMobile']]);
   $user = $stmt->fetch(PDO::FETCH_ASSOC);

   if (empty($user)) {
    //    http_response_code(400); // 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"] == "view-categories") {
    try {
       
        $stmt = $pdo->prepare("SELECT * from categories");

        // Execute the statement
        if ($stmt->execute()) {
            // Fetch the results as an associative array
            $dataInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($dataInfo) {
                $result = json_encode(array('success' => true, 'info' => $dataInfo));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No categories found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}
if ($postjson["method"] == "view-specialities") {
    try {
       
        $stmt = $pdo->prepare("SELECT * from specialties WHERE catId=?");

        // Execute the statement
        if ($stmt->execute([$postjson['catId']])) {
            // Fetch the results as an associative array
            $specialties = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($specialties) {
                $result = json_encode(array('success' => true, 'specialties' => $specialties));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No specialties found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "view-subSpecialities") {
    try {
       
        // $stmt = $pdo->prepare("SELECT * from subSpecialties WHERE specId=?");
        $stmt = $pdo->prepare("SELECT s.*, u.unit, u.price, u.dpId from subSpecialties s
        LEFT JOIN specUnitsPrice u ON s.subSpecId = u.subSpecId
         WHERE specId=?");

        // Execute the statement
        if ($stmt->execute([$postjson['specId']])) {
            // Fetch the results as an associative array
            $subSpecialties = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($subSpecialties) {
                $result = json_encode(array('success' => true, 'subSpecialties' => $subSpecialties));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No subSpecialties found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "view-subSpecialitiesUnitPrice") {
    try {
       
        $stmt = $pdo->prepare("SELECT * from specUnitsPrice WHERE subSpecId=?");

        // Execute the statement
        if ($stmt->execute([$postjson['subSpecId']])) {
            // Fetch the results as an associative array
            $specUnitsPrice = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($specUnitsPrice) {
                $result = json_encode(array('success' => true, 'specUnitsPrice' => $specUnitsPrice));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No specUnitsPrice found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}


if ($postjson["method"] == "view-nashmi") {
    try {
        // Prepare the SQL statement with a placeholder for the userRole
        // $stmt = $pdo->prepare("SELECT * FROM users WHERE userRole = 'vendor'");
        $stmt = $pdo->prepare("SELECT u.userId, u.userMobile, u.userEmail, u.userFirstName, u.userLastName, u.userCreatedAt, u.userStatus, u.userAddress,
        u.userCredit, u.userLatitude, u.userLongitude, u.userVerifiedStatus, s.subSpecNameAr as subSpecName FROM users u
        LEFT JOIN subSpecialties s ON s.subSpecId IN (SELECT subSpecId FROM vendorSpecialties vs WHERE vs.vsUserId=u.userId)
        WHERE u.userRole = 'vendor'");

        // Execute the statement
        if ($stmt->execute()) {
            // Fetch the results as an associative array
            $dataInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($dataInfo) {
                $result = json_encode(array('success' => true, 'info' => $dataInfo));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No Nashmi found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

//enable or disable vendor
if ($postjson["method"] == "nashmi-disabled-enabled") {
    try {
        if($postjson['venderStatus']=="enabled"){
            $status='disabled';
        }else{
            $status='enabled';
        }
        $stmt=$pdo->prepare("UPDATE users SET userVerifiedStatus = ? WHERE userId=?");
        if($stmt->execute([$status,$postjson['venderId']])){
            $result = json_encode(array('success' => true, 'msg' => 'Nashmi verfied status has been updated'));
        }else{
            $result = json_encode(array('success' => false, 'msg' => 'Error'));
        }
        echo $result;

    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

//make Nashmi status inactive
if ($postjson["method"] == "nashmi-inactive") {
    try {
       
        $stmt=$pdo->prepare("UPDATE users SET userStatus = 'inactive' WHERE userId=?");
        if($stmt->execute([$postjson['venderId']])){
            $result = json_encode(array('success' => true, 'msg' => 'Nashmi status has been updated'));
        }else{
            $result = json_encode(array('success' => false, 'msg' => 'Error'));
        }
        echo $result;

    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if($postjson["method"]=="view-orders"){

    $stmt = $pdo->prepare("SELECT r.reqDate,r.reqId,r.reqVenderId,r.reqStatus,r.reqFrom,r.reqTo,r.reqUnit, r.reqRate, v.userFirstName as vendorName, s.subSpecNameAr as subSpecName from requests r LEFT JOIN users v ON v.userId = r.reqVenderId LEFT JOIN subSpecialties s ON r.reqSubSpecId=s.subSpecId"); //add subSpec and nashmi name for each order 
    $stmt->execute();
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($orders)) {
        // http_response_code(400); // Bad Request
        $response = array(
            'success' => false,
            'message' => 'there is no orders.'
        );
    }else{
            $response = array(
                'success' => true,
                'message' => 'orders info retrived successful.',
                'data' => $orders
            );
       
    }
    echo json_encode($response);
}



if($postjson["method"]=="view-orders-by-nashmi-id"){

    $stmt = $pdo->prepare("SELECT r.reqDate,r.reqId,r.reqVenderId,r.reqStatus,r.reqFrom,r.reqTo,r.reqUnit, r.reqRate, v.userFirstName as vendorName, v.userEmail as vendorEmail, v.userCredit as vendorCredit, v.userCreatedAt as vendorCreatedAt, v.userMobile as vendorMobile, s.subSpecNameAr as subSpecName from requests r LEFT JOIN users v ON v.userId = r.reqVenderId LEFT JOIN subSpecialties s ON r.reqSubSpecId=s.subSpecId WHERE r.reqVenderId=?"); //add subSpec and nashmi name for each order 
    $stmt->execute([$postjson['nashmiId']]);
    $orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $stmtVendor = $pdo->prepare("SELECT v.userId, v.userMobile, v.userEmail, v.userFirstName, v.userLastName, v.userCredit, v.userCreatedAt FROM users v WHERE v.userId=?");
    $stmtVendor->execute([$postjson['nashmiId']]);
    $vendorInfo = $stmtVendor->fetchAll(PDO::FETCH_ASSOC);

    if (empty($orders) && empty($vendorInfo)) {
        // http_response_code(400); // Bad Request
        $response = array(
            'success' => false,
            'message' => 'there is no orders.'
        );
    }else{
            $response = array(
                'success' => true,
                'message' => 'orders & vendor info retrived successful.',
                'data' => $orders,
                'vendorInfo' => $vendorInfo
            );
       
    }
    echo json_encode($response);
}

if ($postjson["method"] == "edit-info") {
    try {
        $userId = $postjson["userId"];
        $firstName = $postjson["firstName"];
        $lastName = $postjson["lastName"];
        $userMobile = $postjson["phoneNumber"];
        // $password = $postjson["password"];
        $password = password_hash($postjson['password'], PASSWORD_DEFAULT);


         // Check if another user with the same mobile number exists
         $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE userMobile = :userMobile AND userId != :userId");
         $stmtCheck->bindParam(':userMobile', $userMobile);
         $stmtCheck->bindParam(':userId', $userId);
         $stmtCheck->execute();
         $count = $stmtCheck->fetchColumn();
       
         if ($count > 0) {
            // Another user with the same mobile number already exists, return a message
            $result = json_encode(array('success' => false, 'message' => 'UserMobile already exists'));
        } else {
        $stmt = $pdo->prepare("UPDATE users 
                               SET userFirstName = :firstName, 
                                   userLastName = :lastName, 
                                   userMobile = :userMobile, 
                                   userPassword = :password
                               WHERE userId = :userId");

        $stmt->bindParam(':firstName', $firstName);
        $stmt->bindParam(':lastName', $lastName);
        $stmt->bindParam(':userMobile', $userMobile);
        $stmt->bindParam(':password', $password);
        $stmt->bindParam(':userId', $userId);

        if ($stmt->execute()) {
            $result = json_encode(array('success' => true));
        } else {
            $result = json_encode(array('success' => false));
        }
    }
        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "edit-sub-admin") {
    try {
        $userId = $postjson["userId"];
        $firstName = $postjson["firstName"];
        $lastName = $postjson["lastName"];
        $userMobile = $postjson["phoneNumber"];
        $email = $postjson["email"];
        // $password = $postjson["password"];
        $password = password_hash($postjson['password'], PASSWORD_DEFAULT);


         // Check if another user with the same mobile number exists
         $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE userMobile = :userMobile AND userId != :userId AND userRole='subAdmin'");
         $stmtCheck->bindParam(':userMobile', $userMobile);
         $stmtCheck->bindParam(':userId', $userId);
         $stmtCheck->execute();
         $count = $stmtCheck->fetchColumn();
       
         if ($count > 0) {
            // Another user with the same mobile number already exists, return a message
            $result = json_encode(array('success' => false, 'message' => 'UserMobile already exists'));
        } else {
        $stmt = $pdo->prepare("UPDATE users 
                               SET userFirstName = :firstName, 
                                   userLastName = :lastName, 
                                   userMobile = :userMobile, 
                                   userEmail = :userEmail, 
                                   userPassword = :password
                               WHERE userId = :userId");

        $stmt->bindParam(':firstName', $firstName);
        $stmt->bindParam(':lastName', $lastName);
        $stmt->bindParam(':userMobile', $userMobile);
        $stmt->bindParam(':userEmail', $email);
        $stmt->bindParam(':password', $password);
        $stmt->bindParam(':userId', $userId);

        if ($stmt->execute()) {
            $result = json_encode(array('success' => true));
        } else {
            $result = json_encode(array('success' => false));
        }
    }
        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "home-data") {
    try {

        $stmtTotalOrders=$pdo->prepare("SELECT COUNT(*) as totalOrders FROM requests");
        $stmtTotalVendors=$pdo->prepare("SELECT COUNT(*) as totalVendors FROM users where userRole='vendor'"); 
        $stmtTotalCustomers=$pdo->prepare("SELECT COUNT(*) as totalCustomers from users where userRole='customer'");

        if($stmtTotalOrders->execute() && $stmtTotalVendors->execute() && $stmtTotalCustomers->execute()){
            $totalOrders=  $stmtTotalOrders->fetchColumn();
            $totalVendors=  $stmtTotalVendors->fetchColumn();
            $totalCustomers=  $stmtTotalCustomers->fetchColumn();
           
            
            $result=json_encode(array('success' => true,"totalOrders"=>$totalOrders,"totalVendors"=>$totalVendors,"totalCustomers"=>$totalCustomers));
        }else{
            $result=json_encode(array('success' => false,"msg"=> "data not fetch"));
        }
        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }

}

if($postjson["method"]=="add-sub-admin"){
    // echo "sss";
    try {
        // Define the data to be inserted
        $firstName = $postjson["firstName"];
        $lastName = $postjson["lastName"];
        $userMobile = $postjson["phoneNumber"];
        $userEmail = $postjson["email"];
        // $password = $postjson["password"];
        $password = password_hash($postjson['password'], PASSWORD_DEFAULT);

        $userType = 'subAdmin';

        // Check if the userMobile already exists
        $stmtCheck = $pdo->prepare("SELECT COUNT(*) FROM users WHERE userMobile = :userMobile");
        $stmtCheck->bindParam(':userMobile', $userMobile);
        $stmtCheck->execute();
        $count = $stmtCheck->fetchColumn();

        if ($count > 0) {
            // UserMobile already exists, return a message to the admin
            $result = json_encode(array('success' => false, 'message' => 'User Mobile already exists'));
        } else {
        // Prepare the SQL statement with placeholders
        $stmt = $pdo->prepare("INSERT INTO users (userFirstName, userLastName, userMobile, userEmail, userPassword, userRole)
                               VALUES (:firstName, :lastName, :userMobile, :userEmail, :password, :userRole)");

        // Bind parameters
        $stmt->bindParam(':firstName', $firstName);
        $stmt->bindParam(':lastName', $lastName);
        $stmt->bindParam(':userMobile', $userMobile);
        $stmt->bindParam(':userEmail', $userEmail);
        $stmt->bindParam(':password', $password);
        $stmt->bindParam(':userRole', $userType);

        // Execute the statement
        if ($stmt->execute()) {
            $result = json_encode(array('success' => true));
        } else {
            $result = json_encode(array('success' => false));
        }
    }
        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "view-sub-admins") {
    try {
        // Prepare the SQL statement with a placeholder for the userRole
        $stmt = $pdo->prepare("SELECT * FROM users WHERE userRole = 'subAdmin'");

        // Execute the statement
        if ($stmt->execute()) {
            // Fetch the results as an associative array
            $dataInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($dataInfo) {
                $result = json_encode(array('success' => true, 'info' => $dataInfo));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No sub admins found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}

if ($postjson["method"] == "get-sub-admin") {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE userId = ? ");
    $stmt->execute([$postjson['subAdminId']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($user)) {
        http_response_code(400); // Bad Request
        $response = array(
            'success' => false,
            'message' => 'sub admin 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;
        
        
            $response = array(
                'success' => true,
                'message' => 'sub admin info retrived successful.',
                'user' => $user
            );
       
    }
    echo json_encode($response);
}

if ($postjson["method"] == "edit-credit") {
    try {
        $nashmiId = $postjson["nashmiId"];
        $newCredit = $postjson["newCredit"];

        // Prepare the SQL statement with placeholders
        $stmt = $pdo->prepare("UPDATE users SET userCredit = :userCredit WHERE userId = :userId");

        // Bind parameters
        $stmt->bindParam(':userCredit', $newCredit);
        $stmt->bindParam(':userId', $nashmiId);

        // Execute the statement
        if ($stmt->execute()) {
            $result = json_encode(array('success' => true));
        } else {
            $result = json_encode(array('success' => false));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}



if ($postjson["method"] == "view-feedback") {
    try {
        // Prepare the SQL statement with a placeholder for the userRole
        $stmt = $pdo->prepare("SELECT i.issueId, i.issueDetails, i.issueReqId,
        u.userFirstName as customerFirstName, u.userLastName as customerLastName, u.userMobile as customerMobile,
        v.userFirstName as vendorFirstName, v.userLastName as vendorLastName, v.userMobile as vendorMobile FROM issues i 
        LEFT JOIN users u ON u.userId = i.issueCustomerId
        LEFT JOIN users v ON v.userId = i.issueVenderId");

        // Execute the statement
        if ($stmt->execute()) {
            // Fetch the results as an associative array
            $dataInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Check if there are results
            if ($dataInfo) {
                $result = json_encode(array('success' => true, 'info' => $dataInfo));
            } else {
                $result = json_encode(array('success' => false, 'msg' => 'No issues found'));
            }
        } else {
            $result = json_encode(array('success' => false, 'msg' => 'Error fetching data'));
        }

        echo $result;
    } catch (PDOException $e) {
        echo json_encode(array('success' => false, 'error' => $e->getMessage()));
    }
}
