donation/app/Controllers/ApiIntegration.php

1209 lines
82 KiB
PHP

<?php
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ApiIntegrationModel;
class ApiIntegration extends ResourceController
{
use ResponseTrait;
private $global_variable_business_id;
private $global_variable_user_id;
private $global_variable_user_name;
private $global_variable_role;
public function __construct()
{
$this->global_variable_business_id = 1;
$this->global_variable_role = "Online";
$api_model = new ApiIntegrationModel();
$table = 'users';
$where = ['role'=>$this->global_variable_role,'business_id'=>(int)$this->global_variable_business_id];
$existing_data = $api_model->getData($table, $where);
$this->global_variable_user_id = isset($existing_data[0]->user_id) ? (int)$existing_data[0]->user_id : NULL;
$this->global_variable_user_name = isset($existing_data[0]->user_id) ? $existing_data[0]->first_name." ".$existing_data[0]->last_name : NULL;
}
public function api_integration($api_request_text) {
$this->logger->info("Api Integration : UID = ".$this->global_variable_user_id." * ".$this->global_variable_user_name);
$this->logger->info("Api Integration : Request Text = ".$api_request_text);
try {
$request_data = $this->request->getVar();
$this->logger->info("Api Integration : Request data type = ".gettype($request_data));
if(isset($request_data) && gettype($request_data) === 'object') {$request_data = [$request_data]; $this->logger->info("Api Integration : Request data type = ".gettype($request_data));}
if(count($request_data)>0){
$this->logger->info("Api Integration : Request data count = ".count($request_data));
$this->logger->info("Api Integration : Request data = ".json_encode($request_data));
$i = 0;
$final_response = [];
foreach($request_data as $row_data)
{
$get_response[$i] = $this->call_methods((array)$row_data, $api_request_text);
$final_response[$i] = isset($get_response[$i]['message'])?$get_response[$i]['message']:$get_response[$i];
$i++;
}
// return $this->respond(['status' => 200, 'message' => $final_response,'references'=>$get_response]);
return $this->respond(['status' => 200, 'message' => $final_response]);
}else{
$this->logger->error('Api Integration : Err = Request data Not Found.');
throw new \Exception('Api Request data Not Found.');
}
} catch (\Exception $e) {
// $this->logger->error("Api Integration : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api Integration : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ' : ' . $e->getMessage());
}
}
public function call_methods($row_data, $api_request_text)
{
$parts = explode('_', $api_request_text);
$method = $parts[0];
$table = constant($parts[1]);
$table_column = constant($parts[1].'_column');
$table_child = constant($parts[1].'_child');
// $table_child_column = constant($table.'_child_column');
$this->logger->info("Api CallMethods : method name = ".$method.", table = ".$table.", table child = ".$table_child);
$this->logger->info("Api CallMethods : table = ".$table ." and its column => " .implode(",",$table_column));
try {
switch ($method) {
case "create":
case "update":
try {
switch ($table) {
case "books":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_book_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Product Ref ID = ".$wordpress_book_id);
$response = $this->save_book_details($records, $wordpress_book_id);
$this->logger->info("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception} ", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case "customers":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_customer_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Customer Ref ID = ".$wordpress_customer_id);
$response = $this->save_customer_details($records, $wordpress_customer_id);
$this->logger->info("Api CallMethods : response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
case "invoice":
try {
$records = (array)$row_data;
$this->logger->info("Api CallMethods : method name = ".$method.", data type =".gettype($records));
if (isset($records['id']) && !empty($records['id'])) {
$wordpress_order_id = $records['id'];
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", wordpress Order Ref ID = ".$wordpress_order_id);
$response = $this->save_sales_details($records, $wordpress_order_id);
$this->logger->info("Api CallMethods : response = ".$response['status']);
} else {
throw new \Exception('The "id" field is not set or empty.');
}
} catch (\Exception $e) {
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('request failed, An error occurred on line ' . $e->getline() . ': ' . $e->getMessage());
}
break;
default:
$this->logger->error('Api CallMethods : Err = Invaild Api Route.');
throw new \Exception('Api Route Not Available');
}
} catch (\Exception $e) {
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
return $this->fail(ucwords($method).' request failed, An error occurred ' .$exception_ends_with);
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
}
break;
case 'delete':
try {
$basic_message = "";
$records = (array)$row_data;
$wordpress_refer_id = $records['id'];
$api_model = new ApiIntegrationModel();
$where = ['isactive' => 1, $table_column[1] => (int)$wordpress_refer_id];
$existing_data = $api_model->getData($table, $where);
$this->logger->info("Api CallMethods : method name = ".$method.", row data count = ".count($records).", ".$table_column[1]." Ref ID = ".$wordpress_refer_id);
if ((int)count($existing_data) > 0) {
if(isset($existing_data[0]) && gettype($existing_data[0]) === 'object') {$existing_data[0] = (array)$existing_data[0]; $this->logger->info("Api Integration : delete ".$table." array data type = ".gettype($existing_data[0]));}
$primary_key_id = (int)$existing_data[0][$table_column[0]];
$this->logger->info("Api CallMethods : ".$table." its PrimaryKey ID = ".$primary_key_id);
$inactive_data['isactive'] = 0;
$inactive_data['updated_by'] = $this->global_variable_user_id;
$update_where = ['isactive' => 1, $table_column[0] => $primary_key_id];
$api_model->updateData($table, $inactive_data, $update_where);
$get_existing_child_details = $api_model->getData($table_child, $update_where);
$this->logger->info("Api CallMethods : ".$table." Child Details Count = ".count($get_existing_child_details));
if ($get_existing_child_details) {
$api_model->updateData($table_child, $inactive_data, $update_where);
}
$basic_message = ucwords($table)." Details (ID = ".$primary_key_id.") and ".ucwords($table)." Child Details Are Deleted";
}else{
$basic_message = ucwords($table)." has No Details";
}
$this->logger->info("Api CallMethods : ".$basic_message);
$response = ['status' => 200, 'message' => $basic_message];
} catch (\Exception $e) {
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Exception Message: " . $e->getMessage() . "<br> File: " . $e->getFile() . "<br> Line: " . $e->getLine() . "<br>");
return $this->fail('DELETE request failed, An error occurred' . $exception_ends_with);
}
break;
default:
throw new \Exception('Unsupported HTTP method');
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." Unsupported HTTP method");
// return $this->fail('Unsupported HTTP method');
}
return $response;
} catch (\Exception $e) {
// Handle the exception, you can log it or return an error response
$exception_ends_with = $e->getline() ? 'on line ' . $e->getline() . ': ' . $e->getMessage() : $e->getMessage();
// $this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text))." {exception}", ['exception' => $e]);
$this->logger->error("Api CallMethods : ".str_replace("_", " ",ucwords($api_request_text)).$exception_ends_with);
return $this->fail('An error occurred ' . $exception_ends_with);
}
}
public function save_book_details($records, $wordpress_book_id)
{
$this->logger->info("Api SaveBookDetails : records count = ".count($records).", wordpress Product Ref ID = ".$wordpress_book_id);
$api_model = new ApiIntegrationModel();
$extensive_correspondence = "";
$basic_message = "";
$book_id = "";
if (count($records) > 0 && !empty($wordpress_book_id)) {
/** Draft status means entry must but inactive. publish means active that's why comment here
* $where = ['wp_api_product_id' => $wordpress_book_id, 'isactive' => $isactive_for_where];
**/
$where = ['wp_api_product_id' => $wordpress_book_id];
$book_details = $api_model->setTable('books')->where($where)->first();
if (isset($book_details['book_id']) && $book_details['book_id'] != "") {
$book_id = $book_details['book_id'];
$where['book_id'] = $book_details['book_id'];
} // update means bookid where condition added : else no where condition added.
$countAll = $api_model->countAll('books', $where);
$this->logger->info(($countAll) ? "Api SaveBookDetails : in wordpress product ref ID = ".$wordpress_book_id." is available on Book table and its PrimaryKey = ".$book_id : "Api SaveBookDetails : in wordpress product ref ID = ".$wordpress_book_id." Not available on Book table");
$publisher = NULL;
$language = NULL;
$page_count = NULL;
$genre = NULL;
$author = NULL;
$category = NULL; // Book
$attributes = $records['attributes'];
$categories = $records['categories'];
// if (count($categories) > 0) {
// $categoryNames = [];
// foreach ($categories as $category) {
// if (isset($category->name) && $category->name != "") {
// if($category->name !== "Membership"){
// $category = 1;$categoryNames[] = $category->name; }
// else{ $category = 2; }
// }
// }
// if (!empty($categoryNames)) {
// $genre = implode(", ", $categoryNames);
// }
// }
if (count($attributes) > 0) {
foreach ($attributes as $att) {
if (isset($att->name) && $att->name == "Publisher") {
$publisher = implode(", ", $att->options);
}
if (isset($att->name) && $att->name == "Book Author") {
$author = implode(", ", $att->options);
}
if (isset($att->name) && $att->name == "Book Language") {
$language = implode(", ", $att->options);
}
if (isset($att->name) && $att->name == "Page Count") {
$page_count = implode(", ", $att->options);
}
}
}
$book_data['wp_api_product_id'] = $wordpress_book_id;
$book_data['title'] = isset($records['name']) ? $records['name'] : NULL;
$book_data['publication_date'] = isset($records['date_created']) ? $records['date_created'] : NULL;
$book_data['publisher'] = $publisher;
$book_data['author'] = $author;
$book_data['genre'] = $genre;
$book_data['language'] = $language;
$book_data['description'] = isset($records['description']) ? $records['description'] : NULL;
$book_data['short_description'] = isset($records['short_description']) ? $records['short_description'] : NULL;
$book_data['page_count'] = $page_count;
$book_data['category'] = $category;
// $book_data['price'] = (isset($records['sale_price']) && $records['sale_price'] != '') ? $records['sale_price'] : ((isset($records['regular_price']) && $records['regular_price'] != '') ? $records['regular_price'] : NULL);
$book_data['price'] = (isset($records['sale_price']) && $records['sale_price'] != '') ? $records['sale_price'] : ((isset($records['regular_price']) && $records['regular_price'] != '') ? $records['regular_price'] : ((isset($records['price']) && $records['price'] != '') ? $records['price'] : NULL));
$book_data['sku'] = isset($records['sku']) ? $records['sku'] : NULL;
$book_data['isactive'] = (isset($records['status']) && strtolower($records['status']) === "publish") ? 1 : 0;
$book_data['business_id'] = $this->global_variable_business_id;
$images = $records['images'];
if ((int)$countAll == 0) {
$book_data['created_by'] = $this->global_variable_user_id;
$insert_result = $api_model->insertData('books', $book_data);
$last_insert_book_id = $insert_result['info'];
$extensive_correspondence .= $insert_result['info'] ? "Book id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Book id : " . $insert_result['info'] : "Book details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveBookDetails : Book id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveBookDetails : Err = ".$insert_result['err']):"";
} else {
$last_insert_book_id = $book_id;
$book_data['updated_by'] = $this->global_variable_user_id;
/** Draft status means entry must but inactive. publish means active that's why comment here
* $book_where = ['book_id' => $book_id, 'isactive' => 1, 'wp_api_product_id' => $wordpress_book_id];
**/
$book_where = ['book_id' => $book_id, 'wp_api_product_id' => $wordpress_book_id];
$update_result = $api_model->updateData('books', $book_data, $book_where);
$extensive_correspondence .= $update_result['info'] ? "Book id : " . $last_insert_book_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Book id : " . $last_insert_book_id;
$update_result['info'] ? $this->logger->info("Api SaveBookDetails : Book id : " . $last_insert_book_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveBookDetails : Err = ".$update_result['err']):"";
}
$this->logger->info("Api SaveBookDetails : Book images count : " .count($images));
if (count($images) > 0 && $last_insert_book_id != "") {
$extensive_correspondence .= " Its have " . count($images) . " Images ,";
$basic_message .= " Its have " . count($images) . " Images";
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
$where = ['book_id' => (int)$last_insert_book_id, 'isactive' => 1];
$existing_images = $api_model->getData('book_images', $where);
$request_images = (array)$images;
$filteringExistingImagesWpApiId = [];
$filteringRequestedImagesWpApiId = [];
$commonElements = [];
if (!empty($existing_images)) {
for ($z = 0; $z < count($request_images); $z++) {
$filteringRequestedImagesWpApiId[$z] = $request_images[$z]->id;
}
for ($y = 0; $y < count($existing_images); $y++) {
$filteringExistingImagesWpApiId[$y] = $existing_images[$y]->wp_api_img_id;
}
if (!empty($filteringExistingImagesWpApiId)) {
$this->logger->info("Api SaveBookDetails : Incoming Images Wp Id " .implode(",",$filteringRequestedImagesWpApiId));
$this->logger->info("Api SaveBookDetails : Existing Images Wp Id " .implode(",",$filteringExistingImagesWpApiId));
$A = $filteringExistingImagesWpApiId;
$B = $filteringRequestedImagesWpApiId;
$missingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonElements = array_intersect($A, $B);
if (!empty($missingValues)) {
$this->logger->info("Api SaveBookDetails : Missing Images Wp Id " .implode(",",$missingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'book_id' => (int)$last_insert_book_id];
$inactive_whereIn[0] = 'wp_api_img_id';
$inactive_whereIn[1] = $missingValues;
$data_to_batch_update = ['isactive' => 0,'updated_by'=>$this->global_variable_user_id];
$api_model->inactiveMissingDetails('book_images',$data_to_batch_update, $inactive_where, $inactive_whereIn);
}
}
}
$where = ['book_id' => (int)$last_insert_book_id, 'isactive' => 1];
if (!empty($commonElements)) {
$whereIn[0] = 'wp_api_img_id';
$whereIn[1] = $commonElements;
} else {
$whereIn = null;
}
$lastestActiveBookImageData = $api_model->getData('book_images', $where, $whereIn);
$this->logger->info("Api SaveBookDetails : lastest Active Book Image Data Count " .count($lastestActiveBookImageData));
$book_image_data = [];
$i = 0;
foreach ($images as $img) {
$bookImgId = null;
// Iterate through the array and find the 'book_img_id' based on 'wp_api_img_id'
if (!empty($lastestActiveBookImageData)) {
foreach ($lastestActiveBookImageData as $item) {
if ($item->wp_api_img_id == $img->id) {
$bookImgId = $item->book_img_id;
break; // Found the match, no need to continue looping
}
}
}
$book_image_data[$i]['img_name'] =isset($img->name) && !empty($img->name) ? $img->name : NULL;
$book_image_data[$i]['wp_img_url'] = isset($img->src) && !empty($img->src) ? $img->src : NULL;
$book_image_data[$i]['is_cover'] = (!empty($bookImgId) && $i == 0) ? 1 : 0 ;
$book_image_data[$i]['type'] = 2;
$book_image_data[$i]['book_id'] = $last_insert_book_id;
$book_image_data[$i]['isactive'] = 1;
$book_image_data[$i]['wp_api_img_id'] = isset($img->id) && !empty($img->id) ? $img->id : NULL;
$book_image_data[$i]['book_img_id'] = $bookImgId;
$i++;
$this->logger->info("Api SaveBookDetails : Image Data = $i Request data = ".json_encode($book_image_data));
} // image loop closed
$extensive_correspondence .= (!empty($book_image_data) ? $api_model->insertAndUpdateChildDetails($book_image_data, 'book_images', 'book_img_id') : "");
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
} //image count closed
else{
$this->logger->error("Api SaveBookDetails : Err = Image Data Not Found");
}
if (count($categories) > 0 && $last_insert_book_id != "") {
$this->save_categories_master_details($categories);
$extensive_correspondence .= " Its have " . count($categories) . " Categories";
$basic_message .= " And Its have " . count($categories) . " Categories";
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
$master_categories = $api_model->getData('category', ['isactive' => 1]);
$this->logger->info("Api SaveBookDetails : total master categories count = ".count($master_categories));
$where = ['book_id' => (int)$last_insert_book_id, 'isactive' => 1 ];
$existing_categories = $api_model->getData('book_categories', $where);
$this->logger->info("Api SaveBookDetails : existing categories count = ".count($existing_categories));
$request_categories = (array)$categories;
$filtering_existing_categories_wpApiId = [];
$filtering_requested_categories_wpApiId = [];
$missing_category_values = [];
$common_category_element = [];
if (!empty($existing_categories)) {
for ($z = 0; $z < count($request_categories); $z++) {
$filtering_requested_categories_wpApiId[$z] = $request_categories[$z]->id;
}
for ($y = 0; $y < count($master_categories); $y++) {
$filtering_existing_categories_wpApiId[$y] = $master_categories[$y]->wp_api_category_id;
}
$filtering_existing_categories_wpApiId = array_diff($filtering_existing_categories_wpApiId, array(""));
if (!empty($filtering_requested_categories_wpApiId)) {
$this->logger->info("Api SaveBookDetails : Incoming Categories Wp Id " .implode(",",$filtering_requested_categories_wpApiId));
$this->logger->info("Api SaveBookDetails : Existing Categories Wp Id " .implode(",",$filtering_existing_categories_wpApiId));
$A = $filtering_existing_categories_wpApiId;
$B = $filtering_requested_categories_wpApiId;
$missing_category_values = array_diff($A, $B); //Find difference element in Existing Images only
$common_category_element = array_intersect($A, $B);
$this->logger->info("Api SaveBookDetails : Missing Categories Wp Id " .implode(",",$missing_category_values)." Are inactived");
if (!empty($missing_category_values)) {
$this->logger->info("Api SaveBookDetails : Missing Categories Wp Id " .implode(",",$missing_category_values)." Are inactived");
$where1 = ['isactive' => 1];
$whereIn1[0] = 'wp_api_category_id';
$whereIn1[1] = array_filter($missing_category_values);
$get_master_category_id_to_inactive = $api_model->getData('category', $where1, $whereIn1);
for ($x = 0; $x < count($get_master_category_id_to_inactive); $x++) {
$book_categories_to_inactive[$x] = $get_master_category_id_to_inactive[$x]->id;
}
$this->logger->info("Api SaveBookDetails : Missing Categories Wp Id " .implode(",",$missing_category_values)." catgory pkid => ".implode(",",$book_categories_to_inactive). "Are inactived");
$where2 = ['isactive' => 1];
$whereIn2[0] = 'category_id';
$whereIn2[1] = $book_categories_to_inactive;
$data_to_batch_update2 = ['isactive' => 0,'updated_by'=>$this->global_variable_user_id];
$api_model->inactiveMissingDetails('book_categories',$data_to_batch_update2, $where2, $whereIn2);
//echo $api_model->getlastQuery();
}
} // loop closed
}
$where = ['isactive' => 1];
if (!empty($common_category_element)) {
$whereIn[0] = 'wp_api_category_id';
$whereIn[1] = $common_category_element;
} else {
$whereIn = null;
}
$get_master_category_based_WPid = $api_model->getData('category', $where, $whereIn);
$this->logger->info("Api SaveBookDetails : Common Categories Wp Id " .implode(",",$common_category_element)." Are already inserted data");
$this->logger->info("Api SaveBookDetails : available category data count = " .count($request_categories));
$book_categories_data = [];
$j = 0;
foreach ($categories as $cate) {
$categories_id = null;
$book_category_primarykey = null;
// Iterate through the array and find the 'book_img_id' based on 'wp_api_img_id'
if (!empty($get_master_category_based_WPid)) {
foreach ($get_master_category_based_WPid as $master) {
if ($master->wp_api_category_id == $cate->id) {
$categories_id = $master->id;
$exist_categories = $api_model->getData('book_categories', ['isactive'=>1,'category_id'=>$categories_id,'book_id' => (int)$last_insert_book_id]);
$book_category_primarykey = isset($exist_categories) && !empty($exist_categories) ? $exist_categories[0]->id : NULL;
$this->logger->info("Api SaveBookDetails : Master Category ID = " .$categories_id." => WP CategoryID = ".$master->wp_api_category_id);
break; // Found the match, no need to continue looping
}
}
}
$book_categories_data[$j]['id'] = $book_category_primarykey;
$book_categories_data[$j]['category_id'] = (int)$categories_id;
$book_categories_data[$j]['book_id'] = $last_insert_book_id;
$j++;
} // loop closed
$extensive_correspondence .= (!empty($book_categories_data) ? $api_model->insertAndUpdateChildDetails($book_categories_data, 'book_categories', 'id') : "");
$this->logger->info("Api SaveBookDetails : ".$extensive_correspondence);
} //category count closed
else{
$this->logger->error("Api SaveBookDetails : Err = Category Data Not Found");
}
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
} //if cond. closed
else {
$this->logger->error("Api SaveBookDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data Not Found'];
}
return $response;
}
public function save_customer_details($records, $wordpress_customer_id)
{
$this->logger->info("Api SaveCustomerDetails : records count = ".count($records).", wordpress Customer Ref ID = ".$wordpress_customer_id);
$api_model = new ApiIntegrationModel();
$extensive_correspondence = "";
$basic_message = "";
$customer_id = "";
if (count($records) > 0 && !empty($wordpress_customer_id)) {
$where = ['wp_api_customer_id' => $wordpress_customer_id, 'isactive' => 1];
$customer_details = $api_model->setTable('customers')->where($where)->first();
if (isset($customer_details['customer_id']) && $customer_details['customer_id'] != "") {
$customer_id = $customer_details['customer_id'];
$where['customer_id'] = $customer_details['customer_id'];
}
$countAll = $api_model->countAll('customers', $where);
$this->logger->info(($countAll) ? "Api SaveCustomerDetails : in wordpress customer ref ID = ".$wordpress_customer_id." is available on customer table and its PrimaryKey = ".$customer_id : "Api SaveBookDetails : in wordpress Customer ref ID = ".$wordpress_customer_id." Not available on Customer table");
$customer_data['first_name'] = $records['first_name'];
$customer_data['last_name'] = $records['last_name'];
$customer_data['type'] = $records['role'];
$customer_data['email'] = $records['email'];
$customer_data['profile_picture'] = $records['avatar_url'];
$customer_data['wp_api_customer_id'] = $wordpress_customer_id;
$customer_data['mode'] = $this->global_variable_role;
$customer_data['business_id'] = $this->global_variable_business_id;
$billing = $records['billing'];
$shipping = $records['shipping'];
if ((int)$countAll == 0) {
$customer_data['created_by'] = $this->global_variable_user_id;
$insert_result = $api_model->insertData('customers', $customer_data);
$last_insert_customer_id = $insert_result['info'];
$extensive_correspondence .= $insert_result['info'] ? "Customer id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Customer id : " . $insert_result['info'] : "Customer details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveCustomerDetails : Customer id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveCustomerDetails : Err = ".$insert_result['err']):"";
} else {
$customer_data['updated_by'] = $this->global_variable_user_id;
$last_insert_customer_id = $customer_id;
$customer_where = ['customer_id' => $customer_id, 'isactive' => 1, 'wp_api_customer_id' => $wordpress_customer_id];
$update_result = $api_model->updateData('customers', $customer_data, $customer_where);
$extensive_correspondence .= $update_result['info'] ? "Customer id : " . $last_insert_customer_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Customer id : " . $last_insert_customer_id;
$update_result['info'] ? $this->logger->info("Api SaveCustomerDetails : Customer id : " . $last_insert_customer_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveCustomerDetails : Err = ".$update_result['err']):"";
}
$i = 0; $customer_billing_address_data = [];
$j = 0; $customer_shipping_address_data = [];
if(isset($billing) && gettype($billing) === 'object') {$billing = [$billing];}
if(isset($shipping) && gettype($shipping) === 'object') {$shipping = [$shipping];}
$this->logger->info("Api SaveCustomerDetails : billing count : " .count($billing));
$this->logger->info("Api SaveCustomerDetails : shipping count : " .count($shipping));
// echo "Customer ID : ".$last_insert_customer_id." have Billing address = ".count($billing)." and Shipping address = ".count($shipping)." <br/>";
if (count($billing) > 0 && $last_insert_customer_id != "") {
$extensive_correspondence .= " Its have " . count($billing) . " Billing address ,";
$basic_message .= " Its have " . count($billing) . " Billing address ,";
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1, 'address_type'=>1];
$existing_billing = $api_model->getData('customer_addresses', $where);
$request_billing = (array)$billing;
$filteringExistingBillingAddress = [];
$filteringRequestedBillingAddress = [];
$commonBillingElements = [];
if (!empty($existing_billing)) {
for ($z = 0; $z < count($request_billing); $z++) {
$filteringRequestedBillingAddress[$z] = $request_billing[$z]->address_1;
}
for ($y = 0; $y < count($existing_billing); $y++) {
$filteringExistingBillingAddress[$y] = $existing_billing[$y]->address_1;
}
if (!empty($filteringExistingBillingAddress)) {
$this->logger->info("Api SaveCustomerDetails : Incoming billing " .implode(",",$filteringExistingBillingAddress));
$this->logger->info("Api SaveCustomerDetails : Existing billing " .implode(",",$filteringRequestedBillingAddress));
$A = $filteringExistingBillingAddress;
$B = $filteringRequestedBillingAddress;
$missingBillingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonBillingElements = array_intersect($A, $B);
if (!empty($missingBillingValues)) {
$this->logger->info("Api SaveCustomerDetails : Missing billing " .implode(",",$missingBillingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'customer_id' => (int)$last_insert_customer_id,'address_type'=>1];
$inactive_whereIn[0] = 'address_1';
$inactive_whereIn[1] = $missingBillingValues;
$data_to_batch_update = ['isactive' => 0,'updated_by'=>$this->global_variable_user_id];
$api_model->inactiveMissingDetails('customer_addresses',$data_to_batch_update, $inactive_where, $inactive_whereIn);
}
}
}
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1,'address_type'=>1];
if (!empty($commonBillingElements)) {
$whereIn[0] = 'address_1';
$whereIn[1] = $commonBillingElements;
} else {
$whereIn = null;
}
$lastestActiveBillingAdressData = $api_model->getData('customer_addresses', $where, $whereIn);
$this->logger->info("Api SaveCustomerDetails : lastest Active billing Data Count " .count($lastestActiveBillingAdressData));
foreach ($billing as $bill) {
$billingAddressId = null;
if ($bill->first_name !== '') {
if (!empty($lastestActiveBillingAdressData)) {
foreach ($lastestActiveBillingAdressData as $item) {
if ($item->address_1 == $bill->address_1) {
$billingAddressId = $item->customer_address_id;
break; // Found the match, no need to continue looping
}
}
}
$customer_billing_address_data[$i]['first_name'] = $bill->first_name;
$customer_billing_address_data[$i]['last_name'] = $bill->last_name;
$customer_billing_address_data[$i]['company'] = $bill->company;
$customer_billing_address_data[$i]['address_1'] = $bill->address_1;
$customer_billing_address_data[$i]['address_2'] = $bill->address_2;
$customer_billing_address_data[$i]['city'] = $bill->city;
$customer_billing_address_data[$i]['state'] = $bill->state;
$customer_billing_address_data[$i]['country'] = $bill->country;
$customer_billing_address_data[$i]['postal_code'] = $bill->postcode;
$customer_billing_address_data[$i]['customer_id'] = $last_insert_customer_id;
$customer_billing_address_data[$i]['address_type'] = 1;
$customer_billing_address_data[$i]['email'] = isset($bill->email) ? $bill->email : '';
$customer_billing_address_data[$i]['mobile_no'] = isset($bill->phone) ? $bill->phone : '';
$customer_billing_address_data[$i]['customer_address_id'] = $billingAddressId;
$this->logger->info("Api SaveCustomerDetails : Billing address has a value and Inserted ");
$i++;
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Billing address has a value and Inserted ".$i." <br/>";
}else{
$this->logger->info("Api SaveCustomerDetails : Billing address has no value ");
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Billing address has no value; <br/>";
}
}
$extensive_correspondence .= (!empty($customer_billing_address_data) ? $api_model->insertAndUpdateChildDetails($customer_billing_address_data, 'customer_addresses', 'customer_address_id') : "");
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
}
if (count($shipping) > 0 && $last_insert_customer_id != "") {
$extensive_correspondence .= " Its have " . count($shipping) . " Shipping address ,";
$basic_message .= " Its have " . count($shipping) . " Shipping address .";
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1, 'address_type'=>2];
$existing_shipping = $api_model->getData('customer_addresses', $where);
$request_shipping = (array)$shipping;
$filteringExistingShippingAddress = [];
$filteringRequestedShippingAddress = [];
$commonShippingElements = [];
if (!empty($existing_shipping)) {
for ($z = 0; $z < count($request_shipping); $z++) {
$filteringRequestedShippingAddress[$z] = $request_shipping[$z]->address_1;
}
for ($y = 0; $y < count($existing_shipping); $y++) {
$filteringExistingShippingAddress[$y] = $existing_shipping[$y]->address_1;
}
if (!empty($filteringExistingShippingAddress)) {
$this->logger->info("Api SaveCustomerDetails : Incoming shipping " .implode(",",$filteringExistingShippingAddress));
$this->logger->info("Api SaveCustomerDetails : Existing shipping " .implode(",",$filteringExistingShippingAddress));
$A = $filteringExistingShippingAddress;
$B = $filteringRequestedShippingAddress;
$missingShippingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonShippingElements = array_intersect($A, $B);
if (!empty($missingShippingValues)) {
$inactive_where = ['isactive' => 1, 'customer_id' => (int)$last_insert_customer_id, 'address_type'=>2];
$inactive_whereIn[0] = 'address_1';
$inactive_whereIn[1] = $missingShippingValues;
$data_to_batch_update = ['isactive' => 0,'updated_by'=>$this->global_variable_user_id];
$api_model->inactiveMissingDetails('customer_addresses',$data_to_batch_update, $inactive_where, $inactive_whereIn);
$this->logger->info("Api SaveCustomerDetails : Missing Shipping " .implode(",",$missingShippingValues)." Are inactived");
}
}
}
$where = ['customer_id' => (int)$last_insert_customer_id, 'isactive' => 1 ,'address_type'=>2];
if (!empty($commonShippingElements)) {
$whereIn[0] = 'address_1';
$whereIn[1] = $commonShippingElements;
} else {
$whereIn = null;
}
$lastestActiveShippingAdressData = $api_model->getData('customer_addresses', $where, $whereIn);
$this->logger->info("Api SaveCustomerDetails : lastest Active Shipping Data Count " .count($lastestActiveShippingAdressData));
foreach ($shipping as $ship) {
$shippingAddressId = null;
if ($ship->first_name !== '') {
if (!empty($lastestActiveShippingAdressData)) {
foreach ($lastestActiveShippingAdressData as $item) {
if ($item->address_1 == $ship->address_1) {
$shippingAddressId = $item->customer_address_id;
break; // Found the match, no need to continue looping
}
}
}
$customer_shipping_address_data[$j]['first_name'] = $ship->first_name;
$customer_shipping_address_data[$j]['last_name'] = $ship->last_name;
$customer_shipping_address_data[$j]['company'] = $ship->company;
$customer_shipping_address_data[$j]['address_1'] = $ship->address_1;
$customer_shipping_address_data[$j]['address_2'] = $ship->address_2;
$customer_shipping_address_data[$j]['city'] = $ship->city;
$customer_shipping_address_data[$j]['state'] = $ship->state;
$customer_shipping_address_data[$j]['country'] = $ship->country;
$customer_shipping_address_data[$j]['postal_code'] = $ship->postcode;
$customer_shipping_address_data[$j]['email'] = isset($ship->email)?$ship->email:"";
$customer_shipping_address_data[$j]['mobile_no'] = isset($ship->phone)?$ship->phone:"";
$customer_shipping_address_data[$j]['customer_id'] = $last_insert_customer_id;
$customer_shipping_address_data[$j]['address_type'] = 2;
$customer_shipping_address_data[$j]['customer_address_id'] = $shippingAddressId;
$this->logger->info("Api SaveCustomerDetails : Shipping address has a value and Inserted ");
$j++;
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Shipping address has a value and Inserted ".$j." <br/>";
}
else{
$this->logger->info("Api SaveCustomerDetails : Shipping address has no value ");
// echo "&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; Keys are available but Shipping address has no value <br/>";
}
}
$extensive_correspondence .= (!empty($customer_shipping_address_data) ? $api_model->insertAndUpdateChildDetails($customer_shipping_address_data, 'customer_addresses', 'customer_address_id') : "");
$this->logger->info("Api SaveCustomerDetails : ".$extensive_correspondence);
}else{
$this->logger->error("Api SaveCustomerDetails : Err = Address Data Not Found");
}
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
} //if cond. closed
else {
$this->logger->error("Api SaveCustomerDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data No Found'];
}
return $response;
}
public function save_sales_details($records, $wordpress_order_id){
$this->logger->info("Api SaveSalesDetails : records count = ".count($records).", wordpress Order Ref ID = ".$wordpress_order_id);
$basic_message="";
$api_model = new ApiIntegrationModel();
$extensive_correspondence = "";
$invoice_id = "";
if (count($records) > 0 && !empty($wordpress_order_id)) {
$where = ['wp_api_order_id' => $wordpress_order_id, 'isactive' => 1];
$invoice_details = $api_model->setTable('invoice')->where($where)->first();
if (isset($invoice_details['invoice_id']) && $invoice_details['invoice_id'] != "") {
$invoice_id = $invoice_details['invoice_id'];
$where['invoice_id'] = (int)$invoice_id;
}
$countAll = $api_model->countAll('invoice', $where);
$this->logger->info(($countAll) ? "Api SaveSalesDetails : in wordpress product ref ID = ".$wordpress_order_id." is available on Invoice table and its PrimaryKey = ".$invoice_id : "Api SaveSalesDetails : in wordpress order ref ID = ".$wordpress_order_id." Not available on Invoice table");
$billing_addr = NULL;$shipping_addr = NULL;
$lineitems_array = [];
$billing_array = []; $shipping_array = [];
$lineitems_subtotal = 0; $lineitems_tax = 0;
$lineitems_discount = 0; $lineitems_total=0;
// $line_items = ;
if(isset($records['billing']) && gettype($records['billing']) === 'object') {$billing_array = [$records['billing']];}
if(isset($records['shipping']) && gettype($records['shipping']) === 'object') {$shipping_array = [$records['shipping']];}
$where = ['wp_api_customer_id' => (int)$records['customer_id'], 'isactive' => 1];
$local_customer = $api_model->getData('customers', $where);
$local_customer_id = !empty($local_customer) ? $local_customer[0]->customer_id : NULL;
$this->logger->info((!empty($local_customer)) ? "Api SaveSalesDetails : in wordpress customer ref ID = ".$records['customer_id']." is available on Customer table and its PrimaryKey = ".$local_customer_id."(local customer id)" : "Api SaveSalesDetails : in wordpress customer ref ID = ".$records['customer_id']." Not available on Customer table");
if (count($billing_array) > 0) {
// foreach ($billing_array as $bill) {
// if($bill->first_name != ""){
// $billing_addr = $bill->address_1 . " " . $bill->address_2 . ",\n" . $bill->city . ",\n" . $bill->state . " - " . $bill->postal_code . ",\n" . $bill->country . ".";
// }
// }
$result_billing_addr = $this->save_invoice_address_in_customer_address($billing_array,1,(int)$local_customer_id);
$billing_addr_id = $result_billing_addr['addr_id'];
$billing_addr = $result_billing_addr['addr'];
}
if (count($shipping_array) > 0) {
// foreach ($shipping_array as $ship) {
// if($ship->first_name != ""){
// $shipping_addr = $ship->address_1 . " " . $ship->address_2 . ",\n" . $ship->city . ",\n" . $ship->state . " - " . $ship->postal_code . ",\n" . $ship->country . ".";
// }
// }
$result_shipping_addr = $this->save_invoice_address_in_customer_address($shipping_array,2,(int)$local_customer_id);
$shipping_addr_id = $result_shipping_addr['addr_id'];
$shipping_addr = $result_shipping_addr['addr'];
}
if (count($records['line_items']) > 0) {
// echo count($records['line_items']);die;
$lineitems_array = $records['line_items'];
foreach ($lineitems_array as $item) {
$lineitems_subtotal += (float)$item->subtotal;
$lineitems_tax += (float)$item->total_tax;
}
$lineitems_total += ((float)$lineitems_subtotal + (float)$lineitems_tax) - (float)$lineitems_discount;
}
$method_title = '';
$method_total = NULL;
if (count($records['shipping_lines']) > 0) {
$shipping_lines_array = $records['shipping_lines'];
foreach ($shipping_lines_array as $sl) {
$method_title = $sl->method_title;
$method_total = ((float)$sl->total)+((float)$sl->total_tax);
}
}
$subtotal = (float)$lineitems_subtotal + (float)$records['shipping_total'];
$tax = $lineitems_tax + (float)$records['shipping_tax'];
$total = ($lineitems_total)+(float)$records['shipping_total'] + (float)$records['shipping_tax'];
$invoice_data['invoice_id']=$invoice_id;
$invoice_data['invoice_number']=$records['number'];
$invoice_data['customer_id']=$local_customer_id;
$invoice_data['wp_api_order_id']=$records['id'];
$invoice_data['invoice_date']=date("Y-m-d", strtotime($records['date_created']));
$invoice_data['due_date']=NULL;
$invoice_data['subtotal']=(int)$subtotal;
$invoice_data['tax']=(int)$tax;
$invoice_data['discount']=(int)$lineitems_discount;
$invoice_data['total_amount']= $records['total'];
$invoice_data['payment_status']=$records['status'];
$invoice_data['order_number']=$records['order_key'];
$invoice_data['payment_method']=$records['payment_method_title'];
$invoice_data['status']='Approved';
$invoice_data['event_id']=NULL;
$invoice_data['business_id']=$this->global_variable_business_id;
$invoice_data['shipping_address']=$shipping_addr;
$invoice_data['shipping_address_id']=$shipping_addr_id;
$invoice_data['billing_address']=$billing_addr;
$invoice_data['billing_address_id'] =$billing_addr_id;
$invoice_data['shipping_label'] = !empty($method_title)?$method_title:NULL;
$invoice_data['shipping_charge'] = isset($records['shipping_total'])?$records['shipping_total']: (!empty($method_total)?$method_total:NULL);
$invoice_data['notes'] = isset($records['customer_note'])?$records['customer_note']:NULL;
$invoice_data['invoice_type'] = 1;
if ((int)$countAll == 0) {
$invoice_data['created_by'] = $this->global_variable_user_id;
$insert_result = $api_model->insertData('invoice', $invoice_data);
$last_insert_invoice_id = $insert_result['info'];
$extensive_correspondence .= $insert_result['info'] ? "Invoice id : " . $insert_result['info']
: "Err :" . $insert_result['err'];
$basic_message .= $insert_result['info'] ? " Invoice id : " . $insert_result['info'] : "Invoice details Not Inserted";
$insert_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id = ".$insert_result['info']):"";
$insert_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$insert_result['err']):"";
} else {
$last_insert_invoice_id = $invoice_id;
$customer_where = ['invoice_id' => $invoice_id, 'isactive' => 1, 'wp_api_order_id' => $wordpress_order_id];
$invoice_data['updated_by'] = $this->global_variable_user_id;
$update_result = $api_model->updateData('invoice', $invoice_data, $customer_where);
$extensive_correspondence .= $update_result['info'] ? "Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"
: " ( Err :" . $update_result['err'] . ")";
$basic_message .= "Invoice id : " . $last_insert_invoice_id;
$update_result['info'] ? $this->logger->info("Api SaveSalesDetails : Invoice id : " . $last_insert_invoice_id . " ( " . $update_result['info'] . ")"):"";
$update_result['err'] ? $this->logger->error("Api SaveSalesDetails : Err = ".$update_result['err']):"";
}
$line_item_data = [];
$subscription_data = [];
//$shipping_line_item_data = [];
$h=0;$i = 0;//$j=0;
$this->logger->info("Api SaveSalesDetails : Invoice items count : " .count($lineitems_array));
if (count($lineitems_array) > 0 && $last_insert_invoice_id != "") {
$extensive_correspondence .= " Its have " . count($lineitems_array) . " LineItems ,";
$basic_message .= " Its have " . count($lineitems_array) . " LineItems";
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1, 'quantity != '=>0];
$existing_invoiceitem = $api_model->getData('invoiceitems', $where);
$request_invoiceitem = (array)$lineitems_array;
$filteringExistingInvoiceItemWpApiId = [];
$filteringRequestedInvoiceItemWpApiId = [];
$filteringRequestedSKUWpId = [];
$commonElements = [];
if (!empty($existing_invoiceitem)) {
for ($z = 0; $z < count($request_invoiceitem); $z++) {
$filteringRequestedInvoiceItemWpApiId[$z] = $request_invoiceitem[$z]->id;
}
for ($y = 0; $y < count($existing_invoiceitem); $y++) {
$filteringExistingInvoiceItemWpApiId[$y] = $existing_invoiceitem[$y]->wp_api_line_items_id;
}
if (!empty($filteringExistingInvoiceItemWpApiId)) {
$this->logger->info("Api SaveSalesDetails : Incoming InvoiceItem Wp Id " .implode(",",$filteringRequestedInvoiceItemWpApiId));
$this->logger->info("Api SaveSalesDetails : Existing InvoiceItem Wp Id " .implode(",",$filteringExistingInvoiceItemWpApiId));
$A = $filteringExistingInvoiceItemWpApiId;
$B = $filteringRequestedInvoiceItemWpApiId;
$missingValues = array_diff($A, $B); //Find difference element in Existing Images only
$commonElements = array_intersect($A, $B);
if (!empty($missingValues)) {
$this->logger->info("Api SaveSalesDetails : Missing InvoiceItem Wp Id " .implode(",",$missingValues)." Are inactived");
$inactive_where = ['isactive' => 1, 'invoice_id' => (int)$last_insert_invoice_id];
$inactive_whereIn[0] = 'wp_api_line_items_id';
$inactive_whereIn[1] = $missingValues;
$data_to_batch_update = ['isactive' => 0,'updated_by'=>$this->global_variable_user_id];
$api_model->inactiveMissingDetails('invoiceitems',$data_to_batch_update, $inactive_where, $inactive_whereIn);
}
}
}
$where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1, 'quantity != '=>0];
if (!empty($commonElements)) {
$whereIn[0] = 'wp_api_line_items_id';
$whereIn[1] = $commonElements;
} else {
$whereIn = null;
}
$lastestActiveInvoiceitemsData = $api_model->getData('invoiceitems', $where, $whereIn);
$this->logger->info("Api SaveSalesDetails : lastest Active Invoice Items Data Count " .count($lastestActiveInvoiceitemsData));
foreach ($lineitems_array as $ii) {
$invoiceItemsId = null;
$skuId = null;
// Iterate through the array and find the 'book_img_id' based on 'wp_api_img_id'
if (!empty($lastestActiveInvoiceitemsData)) {
foreach ($lastestActiveInvoiceitemsData as $item) {
if ($item->wp_api_line_items_id == $ii->id) {
$invoiceItemsId = $item->invoice_child_id;
break; // Found the match, no need to continue looping
}
}
}
$where = ['wp_api_product_id' => (int)$ii->product_id];
$get_book_data_based_on_wp_product_id = $api_model->getData('books', $where);
$skuId = (string)$ii->sku;
// $get_book_category = $api_model->getData('book_categories', ['book_id' => (int)$ii->product_id,'isactive'=>1]);
$get_book_category = $api_model->getBookCategories($ii->product_id);
// $result_book_category = array_filter($get_book_category, function ($element) {
// return $element['category_name'] === 'Membership' && $element['sku'] === $skuId;
// });
$result_book_category = array_filter($get_book_category, function ($element) use ($skuId) {
return $element['category_name'] === 'Membership' && $element['sku'] === $skuId;
});
$fromDate = NULL;
$toDate = NULL;
for ($x = 0; $x < count($result_book_category); $x++) {
$duration = $result_book_category[$x]['duration'] * 12;
$fromDateTimestamp = strtotime($records['date_created']);
$toDateTimestamp = strtotime("+$duration months", $fromDateTimestamp);
$fromDate = date("Y-m-d", strtotime($records['date_created']));
$toDate = date("Y-m-d", $toDateTimestamp);
// $scheme_id = $result_book_category[$x]['category_id']; b4
$scheme_id = $result_book_category[$x]['book_id'];
$dataToCheck = ['scheme_id'=>$scheme_id,'customer_id' => $local_customer_id,'invoice_id' => $invoice_id ];
$existing_subscription = $api_model->getData('subscription', $dataToCheck);
if (count($existing_subscription) > 0) {
$this->logger->info("Api SaveSalesDetails : Subscription ".count($existing_subscription)." data already exists = ".json_encode($dataToCheck));
} else {
$subscription_data[$x]['scheme_id'] = $result_book_category[$x]['category_id'];
$subscription_data[$x]['customer_id'] = $local_customer_id;
$subscription_data[$x]['invoice_id'] = $invoice_id;
$subscription_data[$x]['from_subscription'] = $fromDate;
$subscription_data[$x]['to_subscription'] = $toDate;
$subscription_data[$x]['mode'] = $result_book_category[$x]['category_name'];
$subscription_data[$x]['business_id']=$this->global_variable_business_id;
$this->logger->info("Api SaveSalesDetails : Subscription Data inx = $x Request data = ".json_encode($subscription_data));
}
}
// echo $fromDate;
// echo $toDate;
// print_r($subscription_data);die;
// print_r($get_book_category);
// print_r($result_book_category);
// print_r($subscription_data);
// die;
// $skuId = $ii->sku;
// $this->logger->info("Api SaveSalesDetails : Lineitem SKU ID = " .$skuId);
// $where = ['online_sku' => $skuId, 'isactive' => 1];
// $existing_schemes = $api_model->getData('schemes', $where);
// if(!empty($skuId) && !empty($existing_schemes)){
// $duration = $existing_schemes[0]->duration;
// $fromDateTimestamp = strtotime($records['date_created']);
// $toDateTimestamp = strtotime("+$duration months", $fromDateTimestamp);
// $fromDate = date("Y-m-d", strtotime($records['date_created']));
// $toDate = date("Y-m-d", $toDateTimestamp);
// $subscription_data[$h]['scheme_id'] = $existing_schemes[0]->scheme_id;
// $subscription_data[$h]['customer_id'] = $records['customer_id'];
// $subscription_data[$h]['invoice_id'] = $invoice_id;
// $subscription_data[$h]['from_subscription'] = $fromDate;
// $subscription_data[$h]['to_subscription'] = $toDate;
// $subscription_data[$h]['mode'] = "From WordPress Data";
// $h++;
// $this->logger->info("Api SaveSalesDetails : Subscription Data inx = $h Request data = ".json_encode($subscription_data));
// }else{ sku
$line_item_data[$i]['product'] = (!empty($get_book_data_based_on_wp_product_id) ? $get_book_data_based_on_wp_product_id[0]->book_id : NULL);
$line_item_data[$i]['quantity'] =(float)$ii->quantity;
$line_item_data[$i]['unit_price'] =(float)$ii->price;
$line_item_data[$i]['tax'] =(float)$ii->total_tax;
$line_item_data[$i]['subtotal'] =(int)$ii->total;
$line_item_data[$i]['invoice_child_id'] = $invoiceItemsId;
$line_item_data[$i]['wp_api_line_items_id'] = $ii->id;
$line_item_data[$i]['invoice_id'] = $last_insert_invoice_id;
$line_item_data[$i]['from_subscription'] = $fromDate;
$line_item_data[$i]['to_subscription'] = $toDate;
$i++;
$this->logger->info("Api SaveSalesDetails : Invoiceitem Data inx = $i Request data = ".json_encode($line_item_data));
// }
} // line item loop closed
$extensive_correspondence .= (!empty($line_item_data) ? $api_model->insertAndUpdateChildDetails($line_item_data, 'invoiceitems', 'invoice_child_id') : "");
$extensive_correspondence .= (!empty($subscription_data) ? $api_model->insertAndUpdateChildDetails($subscription_data, 'subscription', 'sub_id') : "");
$invoice_type_data[0]['invoice_type'] = count($result_book_category)>0 ? 2 : 1;
$invoice_type_data[0]['invoice_id'] = $last_insert_invoice_id;
(!empty($invoice_type_data) ? $api_model->insertAndUpdateChildDetails($invoice_type_data, 'invoice', 'invoice_id') : "");
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
$this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
}
else{
$this->logger->error("Api SaveSalesDetails : Err = Invoice items Data Not Found");
}
// $shipping_lineitems_array = $records['shipping_lines'];
// $this->logger->info("Api SaveSalesDetails : Shipping Invoice items count : " .count($shipping_lineitems_array));
// if (count($shipping_lineitems_array) > 0 && $last_insert_invoice_id != "") {
// $extensive_correspondence .= " Its have " . count($shipping_lineitems_array) . " shipping details ,";
// $basic_message .= " and Its have " . count($shipping_lineitems_array) . " shipping details";
// $this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
// $shipping_where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1,'quantity'=>0];
// $existing_shipping_invoiceitem = $api_model->getData('invoiceitems', $shipping_where);
// $request_shipping_invoiceitem = (array)$shipping_lineitems_array;
// $filteringExistingShippingInvoiceItemWpApiId = [];
// $filteringRequestedShippingInvoiceItemWpApiId = [];
// $commonShippingElements = [];
// if (!empty($existing_shipping_invoiceitem)) {
// for ($z = 0; $z < count($request_shipping_invoiceitem); $z++) {
// $filteringRequestedShippingInvoiceItemWpApiId[$z] = $request_shipping_invoiceitem[$z]->id;
// }
// for ($y = 0; $y < count($existing_shipping_invoiceitem); $y++) {
// $filteringExistingShippingInvoiceItemWpApiId[$y] = $existing_shipping_invoiceitem[$y]->wp_api_line_items_id;
// }
// if (!empty($filteringExistingShippingInvoiceItemWpApiId)) {
// $this->logger->info("Api SaveSalesDetails : Incoming InvoiceItem (Shipping) Wp Id " .implode(",",$filteringRequestedShippingInvoiceItemWpApiId));
// $this->logger->info("Api SaveSalesDetails : Existing InvoiceItem (Shipping) Wp Id " .implode(",",$filteringExistingShippingInvoiceItemWpApiId));
// $A = $filteringExistingShippingInvoiceItemWpApiId;
// $B = $filteringRequestedShippingInvoiceItemWpApiId;
// $missingShippingValues = array_diff($A, $B); //Find difference element in Existing Images only
// $commonShippingElements = array_intersect($A, $B);
// if (!empty($missingShippingValues)) {
// $this->logger->info("Api SaveSalesDetails : Missing InvoiceItem (shipping) Wp Id " .implode(",",$missingShippingValues)." Are inactived");
// $inactive_where = ['isactive' => 1, 'invoice_id' => (int)$last_insert_invoice_id];
// $inactive_whereIn[0] = 'wp_api_line_items_id';
// $inactive_whereIn[1] = $missingShippingValues;
// $api_model->inactiveMissingDetails('invoiceitems', $inactive_where, $inactive_whereIn);
// }
// }
// }
// $where = ['invoice_id' => (int)$last_insert_invoice_id, 'isactive' => 1,'quantity'=>0];
// if (!empty($commonShippingElements)) {
// $whereIn[0] = 'wp_api_line_items_id';
// $whereIn[1] = $commonShippingElements;
// } else {
// $whereIn = null;
// }
// $lastestActiveShippingInvoiceitemsData = $api_model->getData('invoiceitems', $where, $whereIn);
// $this->logger->info("Api SaveSalesDetails : lastest Active Invoice Item (shipping) Data Count " .count($lastestActiveShippingInvoiceitemsData));
// foreach ($shipping_lineitems_array as $sii) {
// $shippingInvoiceItemsId = null;
// // Iterate through the array and find the 'book_img_id' based on 'wp_api_img_id'
// if (!empty($lastestActiveShippingInvoiceitemsData)) {
// foreach ($lastestActiveShippingInvoiceitemsData as $item) {
// if ($item->wp_api_line_items_id == $sii->id) {
// $shippingInvoiceItemsId = $item->invoice_child_id;
// break; // Found the match, no need to continue looping
// }
// }
// }
// $where = ['title' => (int)$sii->method_title];
// $get_book_data_based_on_title = $api_model->getData('books', $where);
// $shipping_line_item_data[$j]['product'] = (!empty($get_book_data_based_on_title) ? $get_book_data_based_on_title[0]->book_id : NULL);
// $shipping_line_item_data[$j]['quantity'] = 0;
// $shipping_line_item_data[$j]['unit_price'] =0;
// $shipping_line_item_data[$j]['tax'] =(float)$sii->total_tax;
// $shipping_line_item_data[$j]['subtotal'] =(float)$sii->total;
// $shipping_line_item_data[$j]['invoice_child_id'] = $shippingInvoiceItemsId;
// $shipping_line_item_data[$j]['wp_api_line_items_id'] = $sii->id;
// $shipping_line_item_data[$j]['invoice_id'] = $last_insert_invoice_id;
// $this->logger->info("Api SaveSalesDetails : Invoiceitem Data For Shipping inx = $j ");
// $j++;
// } // line item loop closed
// $extensive_correspondence .= (!empty($shipping_line_item_data) ? $api_model->insertAndUpdateChildDetails($shipping_line_item_data, 'invoiceitems', 'invoice_child_id') : "");
// $this->logger->info("Api SaveSalesDetails : ".$extensive_correspondence);
// }
// else{
// $this->logger->error("Api SaveSalesDetails : Err = Invoice items (Shipping) Data Not Found");
// }
$response = ['status' => 200, 'message' => $basic_message ,'indetails' => $extensive_correspondence];
}
else {
$this->logger->error("Api SaveSalesDetails : Err = Data Not Found");
$response = ['status' => 204, 'message' => 'Data No Found'];
}
return $response;
}
public function save_categories_master_details($records)
{
$api_model = new ApiIntegrationModel();
if (count($records) > 0) {
$this->logger->info("Api SaveCategoriesMasterDetails : Master Categories Count = " . count($records));
$where = ['isactive' => 1];
$where_in = null;
$existing_master_categories = $api_model->getData('category', $where);
$request_master_categories = (array)$records;
$common_master_categories = [];
$filter_existing_master_categories_WPID = [];
$filter_request_master_categories_WPID = [];
if (!empty($request_master_categories)) {
for ($z = 0; $z < count($request_master_categories); $z++) {
$filter_request_master_categories_WPID[$z] = $request_master_categories[$z]->id;
}
$this->logger->info("Api SaveCategoriesMasterDetails : Incoming Categories Wp Id " . implode(",", $filter_request_master_categories_WPID));
}
if (!empty($existing_master_categories)) {
for ($y = 0; $y < count($existing_master_categories); $y++) {
$filter_existing_master_categories_WPID[$y] = $existing_master_categories[$y]->wp_api_category_id;
}
$this->logger->info("Api SaveCategoriesMasterDetails : Existing Categories Wp Id " . implode(",", $filter_existing_master_categories_WPID));
}
if (!empty($filter_existing_master_categories_WPID)) {
$common_master_categories = array_intersect($filter_existing_master_categories_WPID, $filter_request_master_categories_WPID);
if (!empty($common_master_categories)) {
$where_in[0] = 'wp_api_category_id';
$where_in[1] = $common_master_categories;
}
}
$lastestActiveMasterCategoriesData = $api_model->getData('category', $where, $where_in);
$this->logger->info("Api SaveCategoriesMasterDetails : lastest Active Book Categories Data Count " . count($lastestActiveMasterCategoriesData));
$book_category_data = [];
$a = 0;
foreach ($request_master_categories as $r) {
$masterCategoryId = null;
if (!empty($lastestActiveMasterCategoriesData)) {
foreach ($lastestActiveMasterCategoriesData as $l) {
if ($l->wp_api_category_id == $r->id) {
$masterCategoryId = $l->id; //local category id from Master Table
break; // Found the match, no need to continue looping
}
}
}
$book_category_data[$a]['id'] = $masterCategoryId;
$book_category_data[$a]['name'] = $r->name;
$book_category_data[$a]['wp_api_category_id'] = $r->id;
$book_category_data[$a]['business_id'] = $this->global_variable_business_id;
$book_category_data[$a]['parent_wp_api_category_id'] = NULL;
$a++;
$this->logger->info("Api SaveCategoriesMasterDetails : Categories Data = $a Request data to save on master category = " . json_encode($book_category_data));
} // loop closed
$message = (!empty($book_category_data) ? $api_model->insertAndUpdateChildDetails($book_category_data, 'category', 'id') : "Info : New Categories Not Avaialble to Save");
$this->logger->info("Api SaveCategoriesMasterDetails : " . $message);
} // count closed
else {
$this->logger->error("Api SaveCategoriesMasterDetails : Err = Categories Data Not Found");
}
}
public function save_invoice_address_in_customer_address($request_addr_array,$flag,$customer_id){
$this->logger->info("Api saveInvoiceAddressInCustomerAddress = ".json_encode($request_addr_array));
$this->logger->info("Api saveInvoiceAddressInCustomerAddress Flag = ".$flag." Customer Id = ".$customer_id);
$api_model = new ApiIntegrationModel();
$where = ['customer_id' =>$customer_id,'address_type'=>(int)$flag,
'first_name'=>$request_addr_array[0]->first_name,'last_name'=>$request_addr_array[0]->last_name,
'address_1'=>$request_addr_array[0]->address_1,'address_2'=>$request_addr_array[0]->address_2,
'city'=>$request_addr_array[0]->city,'postal_code'=>$request_addr_array[0]->postcode];
$existing_addr = $api_model->getData('customer_addresses', $where);
$this->logger->info("Api saveInvoiceAddressInCustomerAddress Count = ".count($existing_addr));
$final_array['addr_id'] = NULL;
$final_array['addr'] = NULL;
$addr_data = [];
if (!empty($existing_addr)) {
$final_array['addr_id'] = isset($existing_addr) && !empty($existing_addr) ? $existing_addr[0]->customer_address_id : NULL;
$this->logger->info("Api saveInvoiceAddressInCustomerAddress Ex Addr id = ".$final_array['addr_id']);
if($existing_addr[0]->first_name != ""){
$final_array['addr'] = $existing_addr[0]->address_1 . " " . $existing_addr[0]->address_2 . ",\n" . $existing_addr[0]->city . ",\n" . $existing_addr[0]->state . " - " . $existing_addr[0]->postal_code . ",\n" . $existing_addr[0]->country . ".";
}
$this->logger->info("Api saveInvoiceAddressInCustomerAddress Ex Addr = ".$final_array['addr']);
}
if (empty($existing_addr)) {
foreach ($request_addr_array as $addr) {
if($addr->first_name != ""){
$addr_data['first_name'] = $addr->first_name;
$addr_data['last_name'] = $addr->last_name;
$addr_data['company'] = $addr->company;
$addr_data['address_1'] = $addr->address_1;
$addr_data['address_2'] = $addr->address_2;
$addr_data['city'] = $addr->city;
$addr_data['state'] = $addr->state;
$addr_data['country'] = $addr->country;
$addr_data['postal_code'] = $addr->postcode;
$addr_data['email'] = isset($addr->email)? $addr->email:"";
$addr_data['mobile_no'] = isset($addr->phone)?$addr->phone:"";
$addr_data['customer_id'] = $customer_id;
$addr_data['address_type'] = $flag;
$addr_data['customer_address_id'] = NULL;
$addr_data['created_by'] = $this->global_variable_user_id;
$final_array['addr'] = $addr->address_1 . " " . $addr->address_2 . ",\n" . $addr->city . ",\n" . $addr->state . " - " . $addr->postcode . ",\n" . $addr->country . ".";
}
}
$this->logger->info("Api saveInvoiceAddressInCustomerAddress New Addr = ".$final_array['addr']);
if(!empty($addr_data)){
$insert_result = $api_model->insertData('customer_addresses',$addr_data);
$final_array['addr_id'] = $insert_result['info'];
$this->logger->info("Api saveInvoiceAddressInCustomerAddress New Addr id = ".$final_array['addr_id']);
}
}
return $final_array;
}
}