the_mechanic/app/Controllers/Products.php
venba-Inspriron-3558 3a2456b629 FIX_minor Bugs
2025-11-13 17:54:23 +05:30

734 lines
28 KiB
PHP
Executable File

<?php
namespace App\Controllers;
use App\Models\ProductModel;
use App\Models\BikemakeModel;
use App\Models\VendorModel;
use App\Models\BikemodelsModel;
use App\Models\ManufacturerModel;
use App\Models\ProductCategoryModel;
use App\Models\AdditionalProductNameModal;
use App\Models\ComplaintModel;
use CodeIgniter\API\ResponseTrait;
class Products extends BaseController
{
protected $additionalProductNameModal;
protected $ProductModel;
protected $BikemakeModel;
protected $BikemodelsModel;
protected $VendorModel;
protected $ManufacturerModel;
protected $ProductCategoryModel;
protected $ComplaintModel;
public $session;
use ResponseTrait;
public function __construct()
{
$this->session = session();
$this->ProductModel = new ProductModel();
$this->BikemakeModel = new BikemakeModel();
$this->BikemodelsModel = new BikemodelsModel();
$this->VendorModel = new VendorModel();
$this->ManufacturerModel = new ManufacturerModel();
$this->ProductCategoryModel = new ProductCategoryModel();
$this->additionalProductNameModal = new AdditionalProductNameModal();
$this->ComplaintModel = new ComplaintModel();
}
public function product_categories()
{
$ProductCategoryModel = new ProductCategoryModel();
$productcategory = $ProductCategoryModel->orderBy('product_category_id')->findAll();
// print_r($productcategory);
foreach ($productcategory as &$category) {
$sub_query_result = $this->ProductModel
->select('count(product_category) as total_product')
->where('product_category', $category['product_category_name'])
->first();
$category['total_product'] = $sub_query_result['total_product'] ?? 0;
}
$data['productcategory'] = $productcategory;
return view('product_categories',$data);
}
public function product_index($manufacturer_id = null)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$category = $this->request->getGet('category');
if ($manufacturer_id) {
$data['products'] = $this->ProductModel->where('manufacturer_id',$manufacturer_id)->orderBy('product_name')->findAll();
$manufacturer = $this->ManufacturerModel->where('manufacturer_id',$manufacturer_id)->select('manufacturer_name')->first();
// print_r($manufacturer);die;
$data['manufacturer_id'] = $manufacturer_id;
$data['manufacturer_name'] = $manufacturer['manufacturer_name'];
return view('product_list',$data);
} else if(isset($category)) {
$data['products'] = $this->ProductModel->get_products($this->session->get('logged_user_branch_id'),$category);
$data['manufacturer_id'] = $manufacturer_id;
return view('product_list',$data);
}else {
$data['products'] = $this->ProductModel->get_products($this->session->get('logged_user_branch_id'));
$data['manufacturer_id'] = $manufacturer_id;
return view('product_list',$data);
}
}
public function add_new_product()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$tax = $this->ProductModel->getTax();
$data['tax']=$tax;
$data['make'] = $this->BikemakeModel->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('make')->findAll();
$data['capacity'] = $this->ComplaintModel->getCubicCapacityName();
$data['vendors'] = $this->VendorModel->orderBy('vendor_name')->findAll();
$data['manufacturers'] = $this->ManufacturerModel->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('manufacturer_name')->findAll();
$data['page_name']="Add Product";
$productcategory = $this->ProductCategoryModel->orderBy('product_category_id')->findAll();
$data['productcategory']=$productcategory;
$data['vendorsProduct'] =[];
$productcategory = $this->ProductCategoryModel->orderBy('product_category_id')->findAll();
$data['product_id'] = 0;
$data['products'] = [];
$data['additionalProdutName'] = [];
echo view('product_form',$data);
}
public function edit_product($product_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$data['page_name'] = "Edit Product";
$products = $this->ProductModel->where('product_id', $product_id)->get()->getRowArray();
// $products['make_id'] = json_decode($products['make_id'], true);
// $products['models_id'] = json_decode($products['models_id'], true);
$data['products'] = $products;
// $data['make'] = $this->BikemakeModel->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('make')->findAll();
// $make_id = $products['make_id'];
// $models = [];
// if( $products['make_id'] != null) {
// foreach ($products['make_id'] as $make_id) {
// $models[] = $this->BikemodelsModel->where('make_id', $make_id)->orderBy('model_name')->findAll();
// }
// }
// $data['models'] = $models;
$tax = $this->ProductModel->getTax();
$data['tax']=$tax;
$data['vendors'] = $this->VendorModel->orderBy('vendor_name')->findAll();
$data['manufacturers'] = $this->ManufacturerModel->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('manufacturer_name', 'ASC')->findAll();
// dd($data['vendors']);
$vendorIds = json_decode($products['vendor'], true);
$vendors = [];
if($vendorIds){
foreach ($vendorIds as $vendorId) {
$vendor = $this->VendorModel->find($vendorId);
if ($vendor) {
$vendors[] = ['id' => $vendor['vendor_id'], 'name' => $vendor['vendor_name']];
}
}}
$data['vendorsProduct'] = $vendors;
$preferredVendorId = $products['prefered_vendor'];
$data['preferredVendorId'] = $preferredVendorId;
$data['product_id'] = $product_id;
$productcategory = $this->ProductCategoryModel->orderBy('product_category_id')->findAll();
$additionalProdutName = $this->additionalProductNameModal
->where('product_id', $product_id)
->where('isactive', 1)
->orderBy('product_names_id', 'asc')
->findAll();
$data['productcategory'] = $productcategory;
$data['additionalProdutName'] = $additionalProdutName;
$data['capacity'] = $this->ComplaintModel->getCubicCapacityName();
echo view('product_form',$data);
}
public function add_product()
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$tax= $this->request->getPost('tax')/2;
$ml = 0; $box = 0; $qty_per_box = 0; $barrel = 0; $ltr_per_barrel = 0;
if ($this->request->getPost('per') == 'ml') {
$ml = $this->request->getPost('ml');
}else if ($this->request->getPost('per') == 'box'){
$box = $this->request->getPost('box');
$qty_per_box = $this->request->getPost('qty_per_box');
}else if ($this->request->getPost('per') == 'barrel'){
$barrel = $this->request->getPost('barrel');
$ltr_per_barrel = $this->request->getPost('ltr_per_barrel');
}
$data = [
'product_name' => $this->request->getPost('productname'),
'product_category' => $this->request->getPost('hiddenproductcategory'),
'mfr_part_no' => $this->request->getPost('mfr_part_no'),
'unit_price' => $this->request->getPost('unit_price'),
// 'commision_rate' => $this->request->getPost('commision_rate'),
'sgst' => $tax,
'cgst' => $tax,
'purchase_cost' => $this->request->getPost('purchase_cost'),
'qty_stock'=> $this->request->getPost('qty_in_stock'),
'description' => $this->request->getPost('description'),
'vendor' =>json_encode( $this->request->getPost('vendor')),
'purchase_order_level' => $this->request->getPost('purchase_order_level'),
'reorder_level' => $this->request->getPost('reorder_level'),
'quality' => $this->request->getPost('quality'),
// 'make_id' => json_encode($this->request->getPost('make')),
// 'models_id' => json_encode($this->request->getPost('model')),
'rack_number' => $this->request->getPost('rack_number'),
'manufacturer_id' => $this->request->getPost('manufacturer'),
'prefered_vendor' => $this->request->getPost('prefered_vendor'),
'specification' => $this->request->getPost('specification'),
'hsn_sac' => $this->request->getPost('hsn_sac'),
'isactive' => 1 ,
'branch_id' => $this->session->get('logged_user_branch_id'),
'total_amount' => $this->request->getPost('total_amount'),
'per' => $this->request->getPost('per'),
'ml' => $ml,
'box' => $box,
'qty_per_box' => $qty_per_box,
'barrel' => $barrel,
'ltr_per_barrel' => $ltr_per_barrel,
'cubic_centimeter_id' => json_encode($this->request->getPost('cubic_centimeter_id')),
];
$product_id = $this->request->getPost('product_id');
// $additional_product_name = $this->request->getPost('additional_product_name');
// $product_names_id = $this->request->getPost('product_names_id');
$model_ids = $this->request->getPost('fk_model_id');
// print_r($data);die;
if (!empty($product_id)) {
$this->ProductModel->update($product_id, $data);
} else {
$this->ProductModel->insert($data);
$product_id = $this->ProductModel->getInsertID();
}
//for insert or update Additional Product Names
// $this->insertOrUpdateAdditionalProductName($additional_product_name, $product_names_id, $model_ids, $product_id, $data['product_name']);
$orderNumber = 'TM' . str_pad($product_id, 8, '0', STR_PAD_LEFT);
// Update sales order with generated order number
$this->ProductModel->update($product_id, ['sku_id' => $orderNumber]);
return redirect()->to('product_index');
}
public function delete_product($product_id)
{
if(!$this->session->has('logged_user')) { return redirect()->to(base_url()); }
$where = ['product_id' => $product_id, 'isactive' => 1 , 'branch_id' => $this->session->get('logged_user_branch_id')]; // Assuming 'isactive' is a column in your database
$existingProduct = $this->ProductModel->where($where)->first();
if ($existingProduct) {
$data['isactive'] = 0;
if ($this->ProductModel->update($product_id, $data)) {
session()->setFlashdata('success', 'Deleted successfully.');
$this->logger->info("Users: has been Inactivated successfully. Inactivated ID = ".$product_id);
}
}
return redirect()->to('product_index');
}
// Retrieve the make_id from the AJAX request
public function get_vendors_by_model()
{
$model_ids = $this->request->getPost('model_ids');
$make_id = $this->request->getPost('make_id');
$Vendors = $this->VendorModel->where('branch_id',$this->session->get('logged_user_branch_id'))->findAll();
if($Vendors){
$data = [];
foreach ($model_ids as $modelKey => $modelValue)
{
foreach ($Vendors as $vendorsKey => $vendorsValue)
{
print_r($vendorsValue);die;
$modelsArray = json_decode($vendorsValue['model'], true);
if (is_array($modelsArray))
{
$findIfModelExist = array_search($modelValue, $modelsArray);
if ($findIfModelExist !== false)
{
array_push($data,$vendorsValue);
}
}
}
}
if (count($data)) {
$arrayOfArrays = array_map(function($obj) {
return (array) $obj;
}, $data);
// Remove duplicates based on string representation of each object
$uniqueArray = array_map('unserialize', array_unique(array_map('serialize', $arrayOfArrays)));
// Convert the unique array of associative arrays back to an array of objects
$uniqueObjectsArray = array_map(function($arr) {
return (object) $arr;
}, $uniqueArray);
return $this->response->setJSON($uniqueArray);
} else {
return $this->response->setJSON([]);
}
}else {
return $this->response->setJSON([]);
}
}
public function get_models()
{
$make_ids = $this->request->getPost('make_id');
$formatted_models = [];
// Iterate over each selected make ID
if ($make_ids) {
foreach ($make_ids as $make_id) {
// Fetch models based on the selected make ID
$models = $this->BikemodelsModel->where('make_id', $make_id)->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('model_name')->findAll();
// Iterate over each fetched model and format it as needed
foreach ($models as $model) {
// Create an associative array with 'model_id' and 'model_name' properties
$formatted_model = [
'make_id' => $model['make_id'],
'model_id' => $model['model_id'],
'model_name' => $model['model_name']
// Add other properties if needed
];
// Push the formatted model into the array
$formatted_models[] = $formatted_model;
}
}
}
return $this->response->setJSON($formatted_models);
}
public function save_make()
{
$response = []; // Initialize an empty array to hold the response data
$make = $this->request->getPost('make');
$model = $this->request->getPost('model');
// Check if both make and model are provided
if (!empty($make) && !empty($model)) {
$data = [
'make' => $make,
'business_id' => $this->session->get('logged_user_business_id'),
];
// Insert the make into the database
$this->BikemakeModel->insert($data);
$make_id = $this->BikemakeModel->getInsertID();
$modelData = [
'model_name' => $model,
'make_id' => $make_id,
'business_id' => $this->session->get('logged_user_business_id'),
];
// Insert the model into the database
$this->BikemodelsModel->insert($modelData);
// Set success status in the response
$response['success'] = true;
} else {
// If make or model is empty, set success status to false
$response['success'] = false;
}
// Send JSON response back to the client
return $this->response->setJSON($response);
}
public function get_makes()
{
$makes = $this->BikemakeModel->findAll();
return $this->response->setJSON($makes);
}
public function save_model()
{
$response = [];
$make_id = $this->request->getPost('make_id');
$model = $this->request->getPost('modelvalue');
if (!empty($make_id) && !empty($model)) {
$modelData = [
'model_name' => $model,
'make_id' => $make_id,
'business_id' => $this->session->get('logged_user_business_id'),
];
$model_id = $this->BikemodelsModel->insert($modelData);
$modelData = $this->BikemodelsModel->where('make_id',$make_id)->findAll();
$response['success'] = true;
$response['model_id'] = $model_id;
$response['model_value'] = $model;
} else {
$response['success'] = false;
}
return $this->response->setJSON($response);
}
public function save_manufacturer()
{
$response = [];
$manufacturer_name = $this->request->getPost('manufacturer_name');
$quality = $this->request->getPost('quality');
if (!empty($manufacturer_name) && !empty($quality)) {
$modelData = [
'manufacturer_name' => $manufacturer_name,
'quality' => $quality,
'business_id'=> $this->session->get('logged_user_business_id')
];
$manufacturer_id = $this->ManufacturerModel->insert($modelData);
$modelData = $this->ManufacturerModel->where('business_id', $this->session->get('logged_user_business_id'))->orderBy('manufacturer_name')->findAll();
$response['success'] = true;
$response['manufacturer_id'] = $manufacturer_id;
$response['quality'] = $quality;
$response['modelData'] = $modelData;
} else {
$response['success'] = false;
}
return $this->response->setJSON($response);
}
public function product_list_for_service()
{
// Assuming you have a model for products and one for manufacturers
$products = $this->ProductModel->select('products.*, manufacturer.manufacturer_name')
->join('manufacturer', 'manufacturer.manufacturer_id = products.manufacturer_id','left')
->where('products.isactive', 1)
->findAll();
return $this->response->setJSON($products);
}
public function status_product()
{
try {
$product_id = $this->request->getPost('product_id');
$isactive = $this->request->getPost('isactive');
$data = [
'isactive' => $isactive
];
$updated = $this->ProductModel->update($product_id, $data);
if ($updated) {
$result = $data;
return $this->respond(['status' => 'success','code' => 200],200);
} else {
$result = "No Match's";
return $this->respond(['status' => 'failed','code' => 404],404);
}
} catch (\Exception $exception) {
return $this->respond(['status' => 'failed','code' => 500,'data' => $exception],500);
}
}
//----VENKAT------------------------------------------------------------------------------------------------
public function insertOrUpdateAdditionalProductName($product_names, $product_name_id,$model_ids, $product_id, $first_product_name)
{
// Fetch existing product names for the given product ID
$product_name_data = $this->additionalProductNameModal->where('product_id', $product_id)
->orderBy('product_names_id', 'asc')
->findAll();
$product_name_count = count($product_name_data);
// Check if there are no existing product names and insert the first product name
// if ($product_name_count == 0 && !empty($first_product_name)) {
// $firstProductNameData = [
// 'product_id' => $product_id,
// 'additional_product_name' => $first_product_name,
// 'model_id' => 0
// ];
// // Insert the first product name
// $this->additionalProductNameModal->insert($firstProductNameData);
// } else {
// // Update the first product name if it has changed
// if ($product_name_data[0]['additional_product_name'] != $first_product_name) {
// $firstProductNameUpdateData = [
// 'additional_product_name' => $first_product_name,
// ];
// $this->additionalProductNameModal
// ->where('product_names_id', $product_name_data[0]['product_names_id'])
// ->set($firstProductNameUpdateData)
// ->update();
// }
// }
$productNameData = [];
if (!empty($product_names) && count($product_names) > 0) {
foreach ($product_names as $index => $name) {
if (!empty($name)) {
$productNameData[] = [
'product_id' => $product_id,
'additional_product_name' => $name,
'product_names_id' => $product_name_id[$index] ?? null,
'model_id' => $model_ids[$index] ?? null
];
}
}
// Filter data for inserts and updates
$insertData = array_filter($productNameData, function ($detail) {
return empty($detail['product_names_id']); // Insert new records only
});
$updateData = array_filter($productNameData, function ($detail) {
return !empty($detail['product_names_id']); // Update existing records
});
// Insert new product names
if (!empty($insertData)) {
$this->additionalProductNameModal->insertBatch($insertData);
}
// Update existing product names
if (!empty($updateData)) {
$this->additionalProductNameModal->updateBatch($updateData, 'product_names_id');
}
if (!empty($product_name_id)) {
$filtering_ids = [];
for ($y = 0; $y < count($product_name_data); $y++) {
$filtering_ids[$y] = $product_name_data[$y]['product_names_id'];
}
if (!empty($filtering_ids)) {
$A = $filtering_ids;
$B = $product_name_id;
$missing_ids = array_diff($A, $B);
if (!empty($missing_ids)) {
$this->additionalProductNameModal
->whereIn('product_names_id', $missing_ids)
->delete();
}
}
}
}
return true;
}
public function delete_product_name($product_id, $product_names_id)
{
if(!empty($product_id) && !empty($product_names_id)){
$this->additionalProductNameModal->where('product_names_id', $product_names_id)->set('isactive', 0)->update();
}
return redirect()->to('new_product/' . $product_id);
}
public function get_product_addtional_details($product_id)
{
$products = $this->ProductModel->where('product_id', $product_id)->get()->getRowArray();
$products['models_id'] = json_decode($products['models_id'], true);
$models = [];
if( $products['models_id'] != null) {
foreach ($products['models_id'] as $model_id) {
$model = $this->BikemodelsModel->select('model_name')->where('model_id', $model_id)->get()->getRow();
array_push($models,$model);
}
}
$data['modelNames'] = $models;
$data['additionalNames'] = $this->additionalProductNameModal->select('additional_product_name')->where('product_id', $product_id)->findAll();
return json_encode($data);
}
public function quick_add()
{
$tax = floatval($this->request->getPost('product_tax')) / 2;
$bid = $this->session->get('logged_user_branch_id');
$ml = 0;
$box = 0;
$qty_per_box = 0;
$barrel = 0;
$ltr_per_barrel = 0;
$per = $this->request->getPost('product_per');
if ($per === 'ml') {
$ml = floatval($this->request->getPost('product_ml') ?? 0);
} elseif ($per === 'box') {
$box = floatval($this->request->getPost('product_box') ?? 0);
$qty_per_box = floatval($this->request->getPost('product_qty_per_box') ?? 0);
} elseif ($per === 'barrel') {
$barrel = floatval($this->request->getPost('product_barrel') ?? 0);
$ltr_per_barrel = floatval($this->request->getPost('product_ltr_per_barrel') ?? 0);
}
$qty_in_stock = floatval($this->request->getPost('product_qty_stock') ?: 0); // Get qty_stock from POST
$purchase_order_level = floor($qty_in_stock / 2); // Calculate purchase reorder level (half of qty in stock)
$purchase_order_level = is_nan($purchase_order_level) ? '' : $purchase_order_level; // Safely assign values (handle invalid numbers)
$reorder_level = is_nan($qty_in_stock) ? '' : $qty_in_stock;
$ccIds = $this->request->getPost('cubic_centimeter_id');
$data = [
'cubic_centimeter_id' => !empty($ccIds) ? json_encode($ccIds) : null,
'product_name' => $this->request->getPost('product_name'),
'product_category' => $this->request->getPost('product_category'),
'total_amount' => $this->request->getPost('product_total_amount'),
'unit_price' => $this->request->getPost('product_unit_price'),
'qty_stock' => $qty_in_stock,
'sgst' => $tax,
'cgst' => $tax,
'per' => $per,
'ml' => $ml,
'box' => $box,
'qty_per_box' => $qty_per_box,
'barrel' => $barrel,
'ltr_per_barrel' => $ltr_per_barrel,
'isactive' => 1,
'branch_id' => $bid,
'purchase_order_level'=> $purchase_order_level,
'reorder_level' => $reorder_level,
'manufacturer_id' => $this->request->getPost('product_manufacturer'),
];
$insertID = $this->ProductModel->insert($data);
if ($insertID) {
$orderNumber = 'TM' . str_pad($insertID, 8, '0', STR_PAD_LEFT);
$this->ProductModel->update($insertID, ['sku_id' => $orderNumber]);
$pD = $this->ProductModel
->select('products.*')
->where('products.product_id', $insertID)
->where('products.branch_id', $bid)
->where('products.isactive', 1)
->first();
return $this->response->setJSON([
'status' => 'success',
'message' => 'Product added successfully!',
'data' => $pD
]);
} else {
return $this->response->setJSON([
'status' => 'error',
'message' => 'Failed to add product.',
]);
}
}
}