<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Custom_codes extends CI_Controller{
  public $page_data=array();
  function __construct()
  {
    parent::__construct();
    $this->initial();
  }
  public function initial()
  {
    ini_set('max_execution_time', 5000);
    ini_set("memory_limit", "-1");

    $this->load->model('User_model','User');
    $this->load->model('Project_tasks_model', 'Project_tasks');
    $this->load->model('Work_model', 'Work');
    $this->load->library('Projects_management','projects_management');
    $this->load->model('Client_model', 'Client');
    $this->load->model('Supplier_model', 'Supplier');
    $this->load->model('Purchase_bill_model', 'Purchases');
    $this->load->model('Subcontracts_model', 'Subcontracts');
    $this->load->model('Purchase_order_model', 'Purchase_order');
    $this->load->model('Purchase_request_model', 'Purchase_request');
    $this->load->model('Labour_model', 'Labour');
    $this->load->model('Labour_wages_model', 'Labour_wages');
    $this->load->model('Account_model', 'Account');
    $this->load->model('Stock_model', 'Stock');
    $this->load->model('Material_model', 'Material');
    $this->load->model('Employees_model', 'Employee');
    $this->load->library('Stock_management','stock_management');
    $this->load->model('Settings_model', 'Settings');
    $this->load->model('Bills_model', 'Bills');
    $this->load->library('Bills_management','bills_management');
    $this->load->model('Loan_model', 'Loan');
    // $this->load->library('Projects_management','projects_management');
    $this->load->model('Tools_model', 'Tools');
    $this->load->model('Invoices_model', 'Invoices');
    $this->load->model('Daily_reports_model', 'Daily_reports');
    $this->load->model('Daily_tasks_model', 'Daily_tasks');
    $this->load->model('Documents_model', 'Documents');
    $this->load->model('Project_tasks_model', 'Project_tasks');
    $this->load->model('Travel_allowance_model', 'Travel_allowance');
    $this->load->model('Customers_model', 'Customers');
    $this->load->library('Accounts_management', 'accounts_management');

  }

  /***default function, redirects to login page if no admin logged in yet***/
  public function index()
  {

  }
  public function copy_expense_heads_to_accounts(){

    $expense_types = $this->db->select('*')->from('expense_type')->get()->result();
    $acc_head_data['account_type'] = 11;
    foreach ($expense_types as $key => $value) {
      $data = array();
      $acc_head_data['acc_head_name'] = $value->expense_type_name;
      $acc_head_data['head_editable'] = 1;
      $acc_head_data['created_date'] = date('Y-m-d H:i:s');
      $acc_head_data['created_by'] = 1;
      $result = $this->Account->create_account_head($acc_head_data);
      if ($result['status']==1) {
        $data['credit_ac'] = $result['insert_id'];
        $data['old_expense_type'] = 5555;
        $this->db->where('old_expense_type', $value->expense_type_id);
        $this->db->where('old_expense_type !=',0);
        $query=$this->db->update('expenses', $data);

      }
    }
  }
  public function alter_settings_table(){
    $settings = $this->db->select('*')->from('settings')->get()->row();
    $smtp_port = $settings->smtp_port;
    $smtp_host = $settings->smtp_host;
    $smtp_user = $settings->smtp_user;
    $smtp_pass = $settings->smtp_pass;
    $company_name = $settings->company_name;


    $this->db->where('settings_id',1);
    $query=$this->db->update('settings', array("settings_category"=>"Company Details","settings_name"=>"company_name","value"=>$company_name));
    $query=$this->db->insert('settings', array("settings_category"=>"Company Details","settings_name"=>"company_logo","value"=>""));
    $query=$this->db->insert('settings', array("settings_category"=>"Company Details","settings_name"=>"company_address","value"=>""));
    $query=$this->db->insert('settings', array("settings_category"=>"Company Details","settings_name"=>"company_letter_head","value"=>""));

    $query=$this->db->insert('settings', array("settings_category"=>"SMTP","settings_name"=>"smtp_username","value"=>$smtp_user));
    $query=$this->db->insert('settings', array("settings_category"=>"SMTP","settings_name"=>"smtp_password","value"=>$smtp_pass));
    $query=$this->db->insert('settings', array("settings_category"=>"SMTP","settings_name"=>"smtp_host","value"=>$smtp_host));
    $query=$this->db->insert('settings', array("settings_category"=>"SMTP","settings_name"=>"smtp_port","value"=>$smtp_port));

    $query=$this->db->insert('settings', array("settings_category"=>"Alerts","settings_name"=>"email_for_alerts","value"=>""));

    $query=$this->db->insert('settings', array("settings_category"=>"Maintenance","settings_name"=>"maintenance_mode","value"=>"0"));
    $query=$this->db->insert('settings', array("settings_category"=>"Maintenance","settings_name"=>"maintenance_time","value"=>"00:05:00"));
  }
  public function purchase_order_fix(){
    $orders = $this->Purchase_order->select_purchase_order("order_id,purchase_bill_id")->result();
    foreach ($orders as $key => $value) {
      $purchase_bill = $this->Purchases->select_purchase("purchase_id", array("p.purchase_order_id" =>$value->order_id))->num_rows();
      if($purchase_bill==0){
        $data2['order_id'] = $value->order_id;
        $data2['purchase_bill_id'] = 0;
        $this->Purchase_order->update_purchase_order($data2);
      }
    }
  }
  public function move_logo(){
    rename('template/assets/app/media/img/logos/logo.png', 'uploads/company/logo.png');
  }
  public function insert_stock_locations(){
    $work	= $this->db->select("work_id,work_name")->from('work_contracts w')->get()->result();
    foreach ($work as $key => $value) {
      $loc_data['location_type'] = 'work_site';
      $loc_data['work_id'] = $value->work_id;
      $count	= $this->Stock->select_stock_locations("sl.*",array("sl.location_type"=>$loc_data['location_type'],"sl.work_id"=>$loc_data['work_id']));
      if($count->num_rows()==0){
        $loc_data['location_name'] = $value->work_name;
        $result =  $this->Stock->insert_stock_location($loc_data);
        if($result['status']==1){
          echo "Stock Location Inserted For Work #".$value->work_id."<br/>";
        }else{
          echo "<label style='color:red'>Error While Inserting Stock Location For Work #".$value->work_id."</label><br/>";
        }
      }else{
        echo "<label style='color:blue'>Stock Location Already Exist For Work #".$value->work_id."</label><br/>";
      }
    }
  }
  public function fix_purchase_locations(){
    $purchase_orders	= $this->db->select("po.order_id,po.work_id")->from('purchase_order po')->where("po.location_id",0)->get()->result();
    foreach ($purchase_orders as $key => $value) {
      $order_data['order_id'] = $value->order_id;
      $loc_data = $this->Stock->select_stock_locations('sl.location_id',array("location_type"=>'work_site',"sl.work_id"=>$value->work_id));
      if($loc_data->num_rows()==1){
        $order_data['location_id'] = $loc_data->row()->location_id;
        $result = $this->Purchase_order->update_purchase_order($order_data);
        if($result==1){
          echo "Purchase Order #".$value->order_id." Updated<br/>";
        }else{
          echo "<label style='color:red'>Error While Updating Purchase Order #".$value->order_id."</label><br/>";
        }
      }else{
        echo "<label style='color:red'>Error - Stock Location ID Not Found For Purchase Order #".$value->order_id."</label><br/>";
      }
    }

    $purchase_bills	= $this->db->select("p.purchase_id,p.work_id")->from('purchase_bills p')->where("p.location_id",0)->get()->result();
    foreach ($purchase_bills as $key => $value) {
      $bill_data['purchase_id'] = $value->purchase_id;
      $loc_data = $this->Stock->select_stock_locations('sl.location_id',array("location_type"=>'work_site',"sl.work_id"=>$value->work_id));
      if($loc_data->num_rows()==1){
        $bill_data['location_id'] = $loc_data->row()->location_id;
        $result = $this->Purchases->update_purchase($bill_data);
        if($result==1){
          echo "Purchase Bill #".$value->purchase_id." Updated<br/>";
        }else{
          echo "<label style='color:red'>Error While Updating Purchase Bill #".$value->purchase_id."</label><br/>";
        }
      }else{
        echo "<label style='color:red'>Error - Stock Location ID Not Found For Purchase #".$value->purchase_id."</label><br/>";
      }
    }
  }
  public function check_material_units(){
    $materials	= $this->db->select("*")->from('materials')->get()->result();
    foreach ($materials as $key => $value) {
      $units = array();
      // Select Material Unit From Purchase Bill and Purchase Order
      $purchase_order_items	= $this->db->distinct()->select("unit_id")->from('purchase_order_items')->where('material_id',$value->material_id)->get();
      if($purchase_order_items->num_rows()>0){
        foreach ($purchase_order_items->result() as $key2 => $value2) {
          $units[] = $value2->unit_id;
        }
      }
      $purchase_bill_items	= $this->db->distinct()->select("unit_id")->from('purchase_bill_items')->where('material_id',$value->material_id)->get();
      if($purchase_bill_items->num_rows()>0){
        foreach ($purchase_bill_items->result() as $key3 => $value3) {
          $units[] = $value3->unit_id;
        }
      }
      $units = array_unique($units);
      if(sizeof($units)>1){
        echo "<label style='color:red'>Material #".$value->material_id." (Default Unit:".$value->unit." ) Have More than 1 Unit (".implode(',',$units).")</label><br/>";
      }elseif(sizeof($units)==0){
        if($value->unit==0){
          echo "<label style='color:Orange'>Material #".$value->material_id." Have No Default Unit</label><br/>";
        }
      }elseif(sizeof($units)==1){
        if($units[0]!=$value->unit){
          $mat_data['material_id'] = $value->material_id;
          $mat_data['unit'] = $units[0];
          $result = $this->Material->update_material($mat_data);
          echo "<label style='color:blue'>Material #".$value->material_id." updated with Unit ID #".$units[0]."</label><br/>";
        }
      }
    }
  }
  public function insert_purchase_items_to_stock(){
    // Select Purchase Bill Items

    $total_items = $this->Purchases->select_purchase_items("pi.*,m.material_name,p.location_id", array("pi.delete_status" => 0),array('purchase_date','asc'));
    if($total_items->num_rows()>0){
      foreach ($total_items->result() as $key => $value) {
        $stock_data = array();
        $stock_data['purchase_item_id'] = $value->item_id;
        $stock_data['location_id'] = $value->location_id;
        $stock_data['stock_name'] = $value->material_name;
        $stock_data['material_id'] = $value->material_id;
        $stock_data['unit'] = $value->unit_id;
        $stock_data['unit_price'] = $value->total_amount/$value->quantity;
        $stock_data['total_purchased_qty'] = $value->quantity;
        //  Check Already Exist
        $stock_count = $this->Stock->select_stock_register("",array("sr.purchase_item_id"=>$stock_data['purchase_item_id']));
        if($stock_count->num_rows()==0){
          // Create New Entry
          $stock_data['created_date'] = date('Y-m-d H:i:s');
          $stock_data['created_by'] = $this->session->userdata('user_id');
          $result = $this->Stock->insert_stock_register($stock_data);
          $this->stock_management->calculate_stock_balance($result['insert_id']);
        }else{
          // Update Existing Entry
          $stock_data['updated_date'] = date('Y-m-d H:i:s');
          $stock_data['updated_by'] = $this->session->userdata('user_id');
          $stock_data['stock_id'] = $stock_count->row()->stock_id;
          $result = $this->Stock->update_stock_register($stock_data);
          $this->stock_management->calculate_stock_balance($stock_data['stock_id']);
        }
        echo "Purchase Item #".$value->item_id." Added to Stock<br/>";
      }
    }
  }
  public function insert_subcontract_items(){
    $subcontracts = $this->Subcontracts->select_subcontract("sc.*",array("contract_type"=>""));
    foreach ($subcontracts->result() as $key => $value) {
      $data3['subcontract_id'] = $value->contract_id;
      $data3['work_type'] = $value->work_type_id;
      $data3['est_amount'] = $value->total_budget;
      $data3['created_date'] = $value->created_date;
      $data3['created_by'] = $value->created_by;
      // $data3['remarks'] = $value->description;
      $result3 =  $this->Subcontracts->create_subcontract_work_item($data3);

      $data['contract_id'] = $value->contract_id;
      $data['contract_type'] = 'fixed_rate';
      $result = $this->Subcontracts->update_subcontract($data);
    }
  }
  public function update_stock_supplier(){
    $stock_items = $this->Stock->select_stock_register("",array("purchase_supplier_id"=>0))->result();
    foreach ($stock_items as $key => $value) {
      $purchase_item_id = $value->purchase_item_id;
      if($purchase_item_id!=0){
        $supplier_data = $this->db->select("p.supplier_id")->from('purchase_bill_items pi')->join('purchase_bills p','pi.purchase_id=p.purchase_id')->where("pi.item_id",$purchase_item_id)->get();
        if($supplier_data->num_rows()==1){
          $stock_data['purchase_supplier_id'] = $supplier_data->row()->supplier_id;
          $stock_data['stock_id'] = $value->stock_id;
          $result = $this->Stock->update_stock_register($stock_data);
        }else{
          echo "Stock ID #".$value->stock_id." Have Supplier Error<br/>";
        }

      }else{
        echo "Stock ID #".$value->stock_id." Have No Purchase Item ID<br/>";
      }
    }
  }
  public function update_item_unit_price(){
    $item_data = $this->db->select("*")->from('purchase_bill_items pi')->get();
    foreach ($item_data->result() as $key => $value) {
      $item['item_id'] = $value->item_id;
      $item['unit_price'] = $value->total_amount/$value->quantity;
      $result = $this->Purchases->update_purchase_item($item);
      echo "Item ID #".$item['item_id']." Updated<br/>";
    }
  }
  public function update_payment_modes(){
    $payment_modes = array("NEFT","RTGS","NET BANKING","CHEQUE","CASH","Credit Card","Debit Card","BULK NEFT","POST DATED CHEQUE","GPay","PhonePe","UPI","Credit");
    $settings_data['settings_category'] = "Accounts";
    $settings_data['settings_name'] = "payment_modes";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = serialize($payment_modes);
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "Payment Modes Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }elseif($settings->num_rows()==1){
      $settings_data['settings_id'] = $settings->row()->settings_id;
      $result = $this->Settings->update_settings($settings_data);
      if($result==1){
        echo "Payment Modes Updated Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Some Error Occurred";
    }
  }
  public function update_user_role(){
    $users = $this->db->select("*")->from('users')->get();
    foreach ($users->result() as $key => $value) {
      $user['user_id'] = $value->user_id;
      if($value->user_role=='admin'){
        $user['user_role'] = 2;
      }elseif($value->user_role=='manager'){
        $user['user_role'] = 3;
      }elseif($value->user_role=='supervisor'){
        $user['user_role'] = 7;
      }
      $result = $this->User->update_user($user);
      echo "Role of User ID #".$user['user_id']." Updated<br/>";
    }
  }

  public function create_bills_and_transactions(){
    // Create Expense Bills from Expense Table
    $this->db->select('e.*,ah2.account_type')->from('expenses e');
    $this->db->join('account_heads ah1', 'e.credit_ac=ah1.acc_head_id');
    $this->db->join('account_heads ah2', 'e.debit_ac=ah2.acc_head_id');
    $this->db->where("e.delete_status",0);
    $this->db->where("e.bill_create_status",0);
    $this->db->order_by("expense_id",'asc');
    $expense = $this->db->get()->result();
    foreach ($expense as $key => $value) {
      $expense_update_data = array();
      $bill_data['bill_type'] = 'expense';
      $bill_data['work_id'] = $value->work_id;
      $bill_data['bill_credit_ac'] = $value->credit_ac;
      $bill_data['bill_date'] = $value->expense_date;
      $bill_data['bill_no'] = '';
      $bill_data['bill_gross_amount'] = $value->amount;
      $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
      $bill_data['bill_amount'] = $bill_data['bill_gross_amount'] + $bill_data['bill_tax_amount'];
      $bill_data['bill_payable_amount'] = $bill_data['bill_amount'];
      $bill_data['bill_consignee_name'] = '';
      $bill_data['bill_description'] = '';
      $bill_data['bill_remarks'] = $value->remarks;
      $bill_data['created_date'] = $value->created_date;
      $bill_data['created_by'] = $value->created_by;

      $bill_result =  $this->Bills->create_bills($bill_data);
      $flash_data['status'] = $bill_result['status'];
      if ($flash_data['status'] == 1) {

        $transaction_data['reference_id'] = $bill_result['insert_id'];
        $transaction_data['reference_type'] = $bill_data['bill_type']."_bill";
        $transaction_data['tr_type'] = $bill_data['bill_type']."_bill_transaction";
        $transaction_data['tr_date'] = $value->expense_date;
        $transaction_data['tr_debit_acc'] = $value->debit_ac;
        $transaction_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
        $transaction_data['tr_description'] = ucwords($bill_data['bill_type'])." Bill Transaction";
        $transaction_data['tr_amount'] = $value->amount;
        if($value->account_type=='36'){
          $transaction_data['tr_mode'] = 'BANK TRANSFER';
        }else{
          $transaction_data['tr_mode'] = 'CASH';
        }
        $transaction_data['tr_reference_no'] = '';
        $transaction_data['tr_reference_date'] = '';
        $transaction_data['tr_remarks'] = $value->remarks;
        $transaction_data['created_date'] = $value->created_date;
        $transaction_data['created_by'] = $value->created_by;
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        if($transaction_result['status']==1){
          $expense_update_data['tr_copy_status'] = 1;
          echo "Expense #".$value->expense_id." Bill & Transaction Created Successfully<br/>";
        }else{
          echo "Expense #".$value->expense_id." Bill Created Successfully, Transaction Creation Failed<br/>";
        }
        // Calculate & Update Bill Total
        $this->bills_management->calculate_bill_total($bill_result['insert_id']);

        $expense_update_data['bill_create_status'] = 1;
        $expense_update_data['expense_id'] = $value->expense_id;
        $this->db->where('expense_id', $expense_update_data['expense_id']);
        $query=$this->db->update('expenses', $expense_update_data);
      }else {
        echo "Expense #".$value->expense_id." Bill Creation Failed<br/>";
      }
    }

    // Create Subcontract Bills from Subcontract Table
    $this->db->select('scp.*,sc.contract_id,sc.contractor,sc.sub_work_name,sc.work_id,ah2.account_type')->from('sub_contract_payments scp');
    $this->db->join('sub_contracts sc','scp.sub_contract_id=sc.contract_id');
    $this->db->join('account_heads ah2', 'scp.debit_ac=ah2.acc_head_id');
    $this->db->where("scp.delete_status",0);
    $this->db->where("scp.bill_create_status",0);
    $this->db->order_by("payment_id",'asc');
    $subcontract_payments = $this->db->get()->result();
    foreach ($subcontract_payments as $key => $value) {
      $subcontract_payment_data = array();
      $bill_data['bill_type'] = 'subcontract';
      $bill_data['work_id'] = $value->work_id;
      $bill_data['subcontract_id'] = $value->contract_id;
      $bill_data['bill_credit_ac'] = "8"; //Subcontract Payments
      $bill_data['bill_date'] = $value->paid_date;
      $bill_data['bill_no'] = '';
      $bill_data['bill_gross_amount'] = $value->paid_amount;
      $bill_data['bill_tax_amount'] = $bill_data['bill_tds_amount'] = 0;
      $bill_data['bill_amount'] = $bill_data['bill_gross_amount'] + $bill_data['bill_tax_amount'];
      $bill_data['bill_payable_amount'] = $bill_data['bill_amount'];
      $bill_data['bill_consignee_name'] = $value->contractor;
      $bill_data['bill_description'] = $value->sub_work_name;
      $bill_data['bill_remarks'] = $value->remarks;
      $bill_data['created_date'] = $value->created_date;
      $bill_data['created_by'] = $value->created_by;

      $bill_result =  $this->Bills->create_bills($bill_data);
      $flash_data['status'] = $bill_result['status'];
      if ($flash_data['status'] == 1) {

        $transaction_data['reference_id'] = $bill_result['insert_id'];
        $transaction_data['reference_type'] = $bill_data['bill_type']."_bill";
        $transaction_data['tr_type'] = $bill_data['bill_type']."_bill_transaction";
        $transaction_data['tr_date'] = $value->paid_date;
        $transaction_data['tr_debit_acc'] = $value->debit_ac;
        $transaction_data['tr_credit_acc'] = $bill_data['bill_credit_ac'];
        $transaction_data['tr_description'] = ucwords($bill_data['bill_type'])." Bill Transaction";
        $transaction_data['tr_amount'] = $value->paid_amount;
        if($value->account_type=='36'){
          $transaction_data['tr_mode'] = 'BANK TRANSFER';
        }else{
          $transaction_data['tr_mode'] = 'CASH';
        }
        $transaction_data['tr_reference_no'] = '';
        $transaction_data['tr_reference_date'] = '';
        $transaction_data['tr_remarks'] = $value->remarks;
        $transaction_data['created_date'] = $value->created_date;
        $transaction_data['created_by'] = $value->created_by;
        $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        if($transaction_result['status']==1){
          $subcontract_payment_data['tr_copy_status'] = 1;
          echo "Subcontract Payment #".$value->payment_id." Bill & Transaction Created Successfully<br/>";
        }else{
          echo "Subcontract Payment #".$value->payment_id." Bill Created Successfully, Transaction Creation Failed<br/>";
        }
        // Calculate & Update Bill Total
        $this->bills_management->calculate_bill_total($bill_result['insert_id']);

        $subcontract_payment_data['bill_create_status'] = 1;
        $subcontract_payment_data['payment_id'] = $value->payment_id;
        $this->db->where('payment_id', $subcontract_payment_data['payment_id']);
        $query=$this->db->update('sub_contract_payments', $subcontract_payment_data);
      }else {
        echo "Subcontract Payment #".$value->payment_id." Bill Creation Failed<br/>";
      }
    }

    // Copy user payments to Transactions
    $this->db->select('up.*,ah2.account_type')->from('user_payment_receipts up');
    $this->db->join('account_heads ah2', 'up.debit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("up.delete_status",0);
    $this->db->where("up.tr_copy_status",0);
    $this->db->order_by("up.payment_id",'asc');
    $user_payments = $this->db->get()->result();

    foreach ($user_payments as $key => $value) {
      $user_payment_data = array();
      $transaction_data['reference_id'] = $value->user_id;
      $transaction_data['reference_type'] = "user";
      $transaction_data['tr_type'] = "user_payment_receipt_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = '';
      $transaction_data['tr_amount'] = $value->received_amount;
      $transaction_data['tr_date'] = $value->received_date;
      $transaction_data['tr_debit_acc'] = $value->debit_ac;
      $transaction_data['tr_credit_acc'] = 9;//User Payments
      $transaction_data['tr_description'] = "User Transaction";
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = '';
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = $value->remarks;
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $user_payment_data['payment_id'] = $value->payment_id;
        $user_payment_data['tr_copy_status'] = 1;
        $this->db->where('payment_id', $user_payment_data['payment_id']);
        $query=$this->db->update('user_payment_receipts', $user_payment_data);
        echo "User Payment #".$value->payment_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for User Payment #".$value->payment_id."<br/>";
      }
    }

    // Copy Purchase Order payments to Transactions
    $this->db->select('pop.*,ah2.account_type')->from('purchase_order_payments pop');
    $this->db->join('account_heads ah2', 'pop.debit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("pop.delete_status",0);
    $this->db->where("pop.tr_copy_status",0);
    $this->db->order_by("pop.payment_id",'asc');
    $purchase_order_payments = $this->db->get()->result();

    foreach ($purchase_order_payments as $key => $value) {
      $purchase_order_data = array();
      $transaction_data['reference_id'] = $value->order_id;
      $transaction_data['reference_type'] = "purchase_order";
      $transaction_data['tr_type'] = "purchase_order_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = $value->payment_part;
      $transaction_data['tr_amount'] = $value->paid_amount;
      $transaction_data['tr_date'] = $value->paid_date;
      $transaction_data['tr_debit_acc'] = $value->debit_ac;
      $transaction_data['tr_credit_acc'] = 5;//Supplier Payments
      $transaction_data['tr_description'] = "Purchase Order Transaction";
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = '';
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = '';
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $purchase_order_data['payment_id'] = $value->payment_id;
        $purchase_order_data['tr_copy_status'] = 1;
        $this->db->where('payment_id', $purchase_order_data['payment_id']);
        $query=$this->db->update('purchase_order_payments', $purchase_order_data);
        echo "Purchase Order Payment #".$value->payment_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for Purchase Order Payment #".$value->payment_id."<br/>";
      }
    }

    // Copy Purchase Bill Payments to Transactions
    $this->db->select('pp.*,ah2.account_type')->from('purchase_bill_payments pp');
    $this->db->join('account_heads ah2', 'pp.debit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("pp.delete_status",0);
    $this->db->where("pp.tr_copy_status",0);
    $this->db->order_by("pp.payment_id",'asc');
    $purchase_bill_payments = $this->db->get()->result();

    foreach ($purchase_bill_payments as $key => $value) {
      $purchase_payment_data = array();
      $transaction_data['reference_id'] = $value->purchase_id;
      $transaction_data['reference_type'] = "purchase_bill";
      $transaction_data['tr_type'] = "purchase_bill_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = $value->payment_part;
      $transaction_data['tr_amount'] = $value->paid_amount;
      $transaction_data['tr_date'] = $value->paid_date;
      $transaction_data['tr_debit_acc'] = $value->debit_ac;
      $transaction_data['tr_credit_acc'] = 5;//Supplier Payments
      $transaction_data['tr_description'] = "Purchase Bill Transaction";
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = '';
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = '';
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $purchase_payment_data['payment_id'] = $value->payment_id;
        $purchase_payment_data['tr_copy_status'] = 1;
        $this->db->where('payment_id', $purchase_payment_data['payment_id']);
        $query=$this->db->update('purchase_bill_payments', $purchase_payment_data);
        echo "Purchase Bill Payment #".$value->payment_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for Purchase Bill Payment #".$value->payment_id."<br/>";
      }
    }

    // Copy Client Payments to Transactions
    $this->db->select('pc.*,ah2.account_type')->from('payment_receipts pc');
    $this->db->join('account_heads ah2', 'pc.credit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("pc.delete_status",0);
    $this->db->where("pc.tr_copy_status",0);
    $this->db->order_by("pc.receipt_id",'asc');
    $client_payments = $this->db->get()->result();

    foreach ($client_payments as $key => $value) {
      $client_payment_data = array();
      $transaction_data['reference_id'] = $value->work_id;
      $transaction_data['reference_type'] = "project";
      $transaction_data['tr_type'] = "client_payment_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = '';
      $transaction_data['tr_amount'] = $value->received_amount;
      $transaction_data['tr_date'] = $value->received_date;
      $transaction_data['tr_debit_acc'] = 2;//Client Payment Receipts
      $transaction_data['tr_credit_acc'] = $value->credit_ac;
      $transaction_data['tr_description'] = "Client Payment Transaction";
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = $value->receipt_no;
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = $value->remarks;
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $client_payment_data['receipt_id'] = $value->receipt_id;
        $client_payment_data['tr_copy_status'] = 1;
        $this->db->where('receipt_id', $client_payment_data['receipt_id']);
        $query=$this->db->update('payment_receipts', $client_payment_data);
        echo "Client Payment #".$value->receipt_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for Client Payment #".$value->receipt_id."<br/>";
      }
    }


    // Copy Income Receipt to Transactions
    $this->db->select('ir.*,ah2.account_type')->from('income_receipts ir');
    $this->db->join('account_heads ah2', 'ir.credit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("ir.delete_status",0);
    $this->db->where("ir.tr_copy_status",0);
    $this->db->order_by("ir.receipt_id",'asc');
    $income_receipts = $this->db->get()->result();
    foreach ($income_receipts as $key => $value) {
      $income_receipt_data = array();
      $transaction_data['reference_id'] = 0;
      $transaction_data['reference_type'] = "income_receipt";
      $transaction_data['tr_type'] = "income_receipt_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = '';
      $transaction_data['tr_amount'] = $value->received_amount;
      $transaction_data['tr_date'] = $value->received_date;
      $transaction_data['tr_debit_acc'] = 14;//Income Receipts
      $transaction_data['tr_credit_acc'] = $value->credit_ac;
      $transaction_data['tr_description'] = $value->income_head;
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = $value->receipt_no;
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = $value->remarks;
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $income_receipt_data['receipt_id'] = $value->receipt_id;
        $income_receipt_data['tr_copy_status'] = 1;
        $this->db->where('receipt_id', $income_receipt_data['receipt_id']);
        $query=$this->db->update('income_receipts', $income_receipt_data);
        echo "Income Receipt #".$value->receipt_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for Income Receipt #".$value->receipt_id."<br/>";
      }
    }

    // Copy Labour Wage Payments to Transactions
    $this->db->select('lwp.*,ah2.account_type')->from('labour_wage_payments lwp');
    $this->db->join('account_heads ah2', 'lwp.debit_ac=ah2.acc_head_id');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("lwp.delete_status",0);
    $this->db->where("lwp.tr_copy_status",0);
    $this->db->order_by("lwp.payment_id",'asc');
    $labour_payments = $this->db->get()->result();

    foreach ($labour_payments as $key => $value) {
      $labour_payment_data = array();
      $transaction_data['reference_id'] = $value->labour_id;
      $transaction_data['reference_type'] = "labour";
      $transaction_data['tr_type'] = "labour_transaction";
      $transaction_data['created_date'] = $value->created_date;
      $transaction_data['created_by'] = $value->created_by;
      $transaction_data['tr_payment_part'] = '';
      $transaction_data['tr_amount'] = $value->paid_amount;
      $transaction_data['tr_date'] = $value->paid_date;
      $transaction_data['tr_debit_acc'] = $value->debit_ac;
      $transaction_data['tr_credit_acc'] = 7;//Labour Payments
      $transaction_data['tr_description'] = "Labour Transaction";
      if($value->account_type=='36'){
        $transaction_data['tr_mode'] = 'BANK TRANSFER';
      }else{
        $transaction_data['tr_mode'] = 'CASH';
      }
      $transaction_data['tr_reference_no'] = '';
      $transaction_data['tr_reference_date'] = '';
      $transaction_data['tr_remarks'] = $value->remarks;
      $transaction_result = $this->Account->create_account_transaction($transaction_data);
      if($transaction_result['status']==1){
        $labour_payment_data['payment_id'] = $value->payment_id;
        $labour_payment_data['tr_copy_status'] = 1;
        $this->db->where('payment_id', $labour_payment_data['payment_id']);
        $query=$this->db->update('labour_wage_payments', $labour_payment_data);
        echo "Labour Payment #".$value->payment_id." Copied Successfully<br/>";
      }else{
        echo "Error Occurred for Labour Payment #".$value->payment_id."<br/>";
      }
    }
  }

  public function create_user_account_heads(){
    $users	= $this->User->select_user();
    foreach ($users->result() as $key => $value) {
      $account_head_data = $this->Account->select_account_heads("",array("acc_user_id"=>$value->user_id));
      if($account_head_data->num_rows()==0){
        // CReate Account Head
        $account_data['acc_head_name'] = $value->user_alias."'s Account";
        $account_data['account_type'] = 32; //Cash Account
        $account_data['acc_user_id'] = $value->user_id;
        $account_data['head_editable'] = 0;
        $account_data['op_balance'] = 0;
        $account_data['created_date'] = date('Y-m-d H:i:s');
        $account_data['created_by'] = 1;
        $account_result = $this->Account->create_account_head($account_data);
        echo "Account Head Created For User #".$value->user_id."<br/>";
      }
    }
  }
  public function update_labour_settings(){
    $settings_data['settings_category'] = "Labour";
    $settings_data['settings_name'] = "group_member_payment";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "Labour Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_labour_settings_2(){
    $settings_data['settings_category'] = "Labour";
    $settings_data['settings_name'] = "wage_slip_no_of_labours_field_show";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "Labour Settings 2 Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_hr_settings(){
    $settings_data['settings_category'] = "HR";
    $settings_data['settings_name'] = "attendance_start_due_time";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = "09:00:00";
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "HR Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_tools_settings(){
    $settings_data['settings_category'] = "Tools";
    $settings_data['settings_name'] = "transfer_default_location_name";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = "Office";
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "Tools Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_tools_settings_2(){
    $settings_data['settings_name'] = "tool_transfer_default_location_name";
    $settings = $this->Settings->select_settings("*",$settings_data);
    if($settings->num_rows()==1){
      $settings_data2['settings_id'] = $settings->row()->settings_id;
      $settings_data2['settings_name'] = "transfer_default_location_name";
      $result = $this->Settings->update_settings($settings_data2);
      if($result==1){
        echo "Tools Settings Updated Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Settings Not Exist";
    }
  }
  public function update_hr_settings_2(){
    $settings_data['settings_name'] = "attendance_start_due_time";
    $settings = $this->Settings->select_settings("*",$settings_data);
    if($settings->num_rows()==1){
      $settings_data2['settings_id'] = $settings->row()->settings_id;
      $settings_data2['settings_name'] = "duty_start_time";
      $result = $this->Settings->update_settings($settings_data2);
      if($result==1){
        echo "HR Settings Updated Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Settings Not Exist";
    }

    $settings_data_2['settings_category'] = "HR";
    $settings_data_2['settings_name'] = "duty_end_time";
    $settings = $this->Settings->select_settings("*",$settings_data_2);
    $settings_data_2['value'] = "18:00:00";
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_2);
      if($result['status']==1){
        echo "HR Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data_3['settings_category'] = "User";
    $settings_data_3['settings_name'] = "user_own_data_edit_delete";
    $settings = $this->Settings->select_settings("*",$settings_data_3);
    $settings_data_3['value'] = "1";
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_3);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_user_settings(){
    $settings_data['settings_category'] = "User";
    $settings_data['settings_name'] = "general_manager_data_access_view_all";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_user_settings_2(){
    $settings_data['settings_category'] = "User";
    $settings_data['settings_name'] = "general_manager_hr_data_view_all";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data_2['settings_category'] = "User";
    $settings_data_2['settings_name'] = "general_manager_hr_data_enabled";
    $settings = $this->Settings->select_settings("*",$settings_data_2);
    $settings_data_2['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_2);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data_2['settings_category'] = "User";
    $settings_data_2['settings_name'] = "general_manager_client_payment_view_all";
    $settings = $this->Settings->select_settings("*",$settings_data_2);
    $settings_data_2['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_2);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data_2['settings_category'] = "User";
    $settings_data_2['settings_name'] = "general_manager_show_client_info";
    $settings = $this->Settings->select_settings("*",$settings_data_2);
    $settings_data_2['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_2);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_user_account_head_settings(){
    $settings_data['settings_category'] = "User";
    $settings_data['settings_name'] = "general_manager_user_payments_enable";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data_2['settings_category'] = "User";
    $settings_data_2['settings_name'] = "general_manager_tr_user_accounts_only";
    $settings = $this->Settings->select_settings("*",$settings_data_2);
    $settings_data_2['value'] = 1;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data_2);
      if($result['status']==1){
        echo "User Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_settings_modules(){
    $settings_module_array = array();
    $settings_module_array[0]['module_name'] = 'stock_management';$settings_module_array[0]['active_status'] = 0;
    $settings_module_array[1]['module_name'] = 'daily_task';$settings_module_array[1]['active_status'] = 0;
    $settings_module_array[2]['module_name'] = 'app_user_attendance';$settings_module_array[2]['active_status'] = 0;
    $settings_module_array[3]['module_name'] = 'daily_labour_report';$settings_module_array[3]['active_status'] = 0;
    $settings_module_array[4]['module_name'] = 'daily_notes';$settings_module_array[4]['active_status'] = 0;
    $settings_module_array[5]['module_name'] = 'purchase_order';$settings_module_array[5]['active_status'] = 0;
    $settings_module_array[6]['module_name'] = 'user_payments';$settings_module_array[6]['active_status'] = 0;
    $settings_module_array[7]['module_name'] = 'tools_management';$settings_module_array[7]['active_status'] = 0;
    $settings_module_array[8]['module_name'] = 'boq';$settings_module_array[8]['active_status'] = 0;
    $settings_module_array[9]['module_name'] = 'sales_invoice';$settings_module_array[9]['active_status'] = 0;
    $settings_module_array[10]['module_name'] = 'labours';$settings_module_array[10]['active_status'] = 0;
    $settings_module_array[11]['module_name'] = 'hr';$settings_module_array[11]['active_status'] = 0;
    $settings_module_array[12]['module_name'] = 'vehicle';$settings_module_array[12]['active_status'] = 0;
    $settings_module_array[13]['module_name'] = 'project_schedule';$settings_module_array[13]['active_status'] = 0;
    $settings_module_array[14]['module_name'] = 'project_documents';$settings_module_array[14]['active_status'] = 0;
    $settings_module_array[15]['module_name'] = 'today_salary';$settings_module_array[15]['active_status'] = 0;
    $settings_module_array[16]['module_name'] = 'work_hour_report';$settings_module_array[16]['active_status'] = 0;
    $settings_module_array[17]['module_name'] = 'purchase_request';$settings_module_array[17]['active_status'] = 0;
    $settings_module_array[18]['module_name'] = 'travel_allowance';$settings_module_array[18]['active_status'] = 0;
    $settings_module_array[19]['module_name'] = 'sales_enquiries';$settings_module_array[19]['active_status'] = 0;


    foreach ($settings_module_array as $key => $value) {
      $module_data = array();
      $module_data['module_name'] = $value['module_name'];
      $settings = $this->Settings->select_settings_modules("*",$module_data);
      $module_data['active_status'] = $value['active_status'];
      if($settings->num_rows()==0){
        $result = $this->Settings->insert_settings_modules($module_data);
        if($result['status']==1){
          echo "Settings Module Added Successfully<br/>";
        }else{
          echo "Some Error Occurred<br/>";
        }
      }
    }
    $settings1 = $this->Settings->select_settings_modules("*",array("module_name"=>"office_projects"));
    if($settings1->num_rows()==1){
      $module['module_id'] = $settings1->row()->module_id;
      $this->db->where('module_id', $module['module_id']);
      $query=$this->db->delete('settings_modules', $module);
    }
  }
  public function update_order_item_unit_price(){
    $item_data = $this->db->select("*")->from('purchase_order_items poi')->get();
    foreach ($item_data->result() as $key => $value) {
      $item['item_id'] = $value->item_id;
      $item['unit_price'] = $value->total_amount/$value->quantity;
      $result = $this->Purchase_order->update_purchase_order_item($item);
      echo "Item ID #".$item['item_id']." Updated<br/>";
    }
  }
  public function update_order_transaction(){
    $data['purchase_bill_id !='] = 0;
    $purchase_orders	= $this->Purchase_order->select_purchase_order("po.*,u.user_alias,s.supplier_name,s.supplier_id,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data);
    foreach ($purchase_orders->result() as $key => $value) {

      // Select Bill Payment as Advance
      $bill_advance_payments = $this->Account->select_account_transaction("ats.*", array("ats.reference_id" => $value->purchase_bill_id, "ats.reference_type" => 'purchase_bill', "ats.tr_payment_part" => 0),'purchase_bill');
      foreach ($bill_advance_payments->result() as $key2 => $value2) {
        //        select same amount transaction in order payment
        $order_payment = $this->Account->select_account_transaction("ats.*", array("ats.tr_date" => $value2->tr_date,"ats.tr_amount" => $value2->tr_amount,"ats.reference_id" => $value->order_id, "ats.reference_type" => 'purchase_order'),'purchase_order');
        if($order_payment->num_rows()==1){
          $data_update =array();
          $data_update['transaction_id'] = $order_payment->row()->transaction_id;
          $data_update['tr_amount'] = 0;
          $transaction_Update_result = $this->Account->update_account_transaction($data_update);
          echo "Order Transaction Updated Successfully For Order #".$value->order_id."<br/>";
        }elseif($order_payment->num_rows()==0){
          echo "No Order Transaction Found For Order #".$value->order_id."<br/>";
        }else{
          echo "Order Transaction Update Error For Order #".$value->order_id."<br/>";
        }
      }
    }
  }
  public function update_app_settings(){
    $settings_data['settings_category'] = "User";
    $settings_data['settings_name'] = "project_creation_admin_only";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "App Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data2['settings_category'] = "User";
    $settings_data2['settings_name'] = "client_payment_creation_admin_only";
    $settings2 = $this->Settings->select_settings("*",$settings_data2);
    $settings_data2['value'] = 0;
    if($settings2->num_rows()==0){
      $result2 = $this->Settings->insert_settings($settings_data2);
      if($result2['status']==1){
        echo "App Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_loan_transaction(){
    $loans	= $this->Loan->select_loan("l.*");
    if($loans->num_rows()>0){
      foreach ($loans->result() as $key => $value) {
        $transaction_data = array();
        $transaction_data['tr_type'] = 'loan_receipt_transaction';
        $transaction_data['reference_id'] = $value->loan_id;
        $transaction_data['reference_type'] = 'loan';
        $loan_tr_data = $this->Account->select_account_transaction("ats.*",$transaction_data);
        if($loan_tr_data->num_rows()==0){
          $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
          $transaction_data['tr_reference_no'] = '';
          $transaction_data['tr_remarks'] = $value->loan_title." - ".$value->provider;
          $transaction_data['created_date'] = date('Y-m-d H:i:s');
          $transaction_data['created_by'] = $this->session->userdata('user_id');
          $transaction_data['tr_credit_acc'] = $value->credit_ac;
          $transaction_data['tr_debit_acc'] = 15;//Loan Receipts
          $transaction_data['tr_amount'] = $value->current_balance_payable;
          $transaction_data['tr_date'] = date('Y-m-d');
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
          echo "Transaction For Loan #".$value->loan_id." Inserted Successfully<br/>";
        }else{
          echo "Already Exist";
        }
      }
    }else{
      echo "No Loans Found";
    }
  }
  public function update_user_payment_transaction(){
    $tr_data['tr_type'] = 'user_transaction';
    $tr_data['reference_type'] = 'user';
    $user_tr_data = $this->Account->select_account_transaction("ats.*",$tr_data)->result();
    foreach ($user_tr_data as $key => $value) {
      $transaction_data['transaction_id'] = $value->transaction_id;
      $transaction_data['tr_type'] = 'user_payment_receipt_transaction';
      $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
      $transaction_data['reference_type'] = 'user_account_head';
      $transaction_result =  $this->Account->update_account_transaction($transaction_data);
      echo "User Payment Transaction #".$value->transaction_id." Updated Successfully<br/>";
    }
  }
  public function update_mobile_app_transactions(){
    // select Supervisors
    $users = $this->db->select("*")->from('users')->where('user_role',7)->get();
    foreach ($users->result() as $key => $value) {
      $account_heads_where['ah.delete_status'] = 0;
      $account_heads_where['ah.acc_user_id'] = $value->user_id;
      $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where);
      if($account_heads_data->num_rows()==1){
        $user_acc_head = $account_heads_data->row()->acc_head_id;
        // Select All Expense Transactions Created By user where debit ac != $user_acc_head
        $tr_data['ats.created_by'] = $value->user_id;
        $tr_data['tr_debit_acc !='] = $user_acc_head;
        $tr_data['tr_type !='] = 'client_payment_transaction';
        $transactions = $this->Account->select_account_transaction("ats.*",$tr_data)->result();
        foreach ($transactions as $key => $value) {
          $tr_update_data['transaction_id'] = $value->transaction_id;
          $tr_update_data['tr_debit_acc'] = $user_acc_head;
          $this->Account->update_account_transaction($tr_update_data);
          echo $tr_update_data['transaction_id']." Updated<br/>";
        }
      }else{
        echo "No A/C Heads Found for User:".$value->user_id."<br/>";
      }
    }
  }
  public function tool_rent_fixes(){
    $tool_rent = $this->Tools->select_tool_rent("tr.*");
    foreach ($tool_rent->result() as $key => $value) {
      $rent_data = $return_log = array();
      $rent_data['id'] = $value->id;
      if($value->total_returned_qty>0){
        $return_log[0]['returned_qty'] = $value->total_returned_qty;
        $return_log[0]['returned_date'] = $value->returned_date;
        $return_log[0]['created_date'] = $value->updated_date;
        $return_log[0]['created_by'] = $value->updated_by;
        $rent_data['returned_log'] = serialize($return_log);
      }else{
        $rent_data['returned_log'] = '';
      }
      if($value->total_returned_qty==$value->rented_qty){
        $rent_data['return_status'] = 1;
      }elseif($value->total_returned_qty<$value->rented_qty && $value->total_returned_qty>0){
        $rent_data['return_status'] = 2;
      }else{
        $rent_data['return_status'] = 0;
      }
      $rent_data['balance_to_return'] = $value->rented_qty-$value->total_returned_qty;
      $result = $this->Tools->update_tool_rent($rent_data);
    }
  }
  public function update_mobileapp_settings(){
    $settings_data['settings_category'] = "Mobile App";
    $settings_data['settings_name'] = "client_login";
    $settings = $this->Settings->select_settings("*",$settings_data);
    $settings_data['value'] = 0;
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "MobileApp Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }
  public function update_currency_settings(){
    $settings_data['settings_category'] = "Currency";
    $settings_data['settings_name'] = "currency_format";
    $settings = $this->Settings->select_settings("*",$settings_data);
    // $settings_data['value'] = "";
    $settings_data['value'] = "<i class='fa fa-rupee-sign'></i>";
    if($settings->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data);
      if($result['status']==1){
        echo "Currency Settings Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data2['settings_category'] = "Currency";
    $settings_data2['settings_name'] = "amount_decimals";
    $settings2 = $this->Settings->select_settings("*",$settings_data2);
    $settings_data2['value'] = "0";
    $settings_data2['remarks'] = "for all input & display fields";
    if($settings2->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data2);
      if($result['status']==1){
        echo "Currency Settings 1 Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }

    $settings_data3['settings_category'] = "Currency";
    $settings_data3['settings_name'] = "amount_decimals_2";
    $settings3 = $this->Settings->select_settings("*",$settings_data3);
    $settings_data3['value'] = "2";
    $settings_data3['remarks'] = "for purchase bill/order only";
    if($settings3->num_rows()==0){
      $result = $this->Settings->insert_settings($settings_data3);
      if($result['status']==1){
        echo "Currency Settings 2 Inserted Successfully";
      }else{
        echo "Some Error Occurred";
      }
    }else{
      echo "Already Exist";
    }
  }

  public function update_settings(){
    $settings_data[0]['settings_category'] = "Tax";
    $settings_data[0]['settings_name'] = "tax_enabled";
    $settings_data[0]['value'] = "1";

    $settings_data[1]['settings_category'] = "Tax";
    $settings_data[1]['settings_name'] = "tax_name";
    $settings_data[1]['value'] = "Tax"; //VAT //GST
    $settings_data[1]['remarks'] = "Tax/VAT/GST";

    $settings_data[2]['settings_category'] = "Tax";
    $settings_data[2]['settings_name'] = "tax_percent";
    $settings_data[2]['value'] = "0"; //5 //2.5
    $settings_data[2]['remarks'] = "5/2.5/18..etc";

    $settings_data[3]['settings_category'] = "Tax";
    $settings_data[3]['settings_name'] = "purchase_tax_type";
    $settings_data[3]['value'] = "bill_wise"; // bill_wise //item_wise
    $settings_data[3]['remarks'] = "bill_wise/item_wise";

    $settings_data[4]['settings_category'] = "User";
    $settings_data[4]['settings_name'] = "calendar_date_restriction_enabled";
    $settings_data[4]['value'] = "0";
    $settings_data[4]['remarks'] = "previous date selection restriction";

    $settings_data[5]['settings_category'] = "User";
    $settings_data[5]['settings_name'] = "calendar_date_restriction_start_days";
    $settings_data[5]['value'] = "0";
    $settings_data[5]['remarks'] = "Start date selection in Days";

    $settings_data[6]['settings_category'] = "HR";
    $settings_data[6]['settings_name'] = "daily_working_hour";
    $settings_data[6]['value'] = "8";
    $settings_data[6]['remarks'] = "Daily Duty Hours";

    $settings_data[7]['settings_category'] = "HR";
    $settings_data[7]['settings_name'] = "salary_slip_overtime_types";
    $settings_data[7]['value'] = "Hours";
    $settings_data[7]['remarks'] = "Hours/Days";

    $settings_data[8]['settings_category'] = "User";
    $settings_data[8]['settings_name'] = "mobile_app_project_access_without_duty_sign";
    $settings_data[8]['value'] = "0";
    $settings_data[8]['remarks'] = "Project & data Access in Mobile app Required Duty Sign in";

    $settings_data[9]['settings_category'] = "Company Details";
    $settings_data[9]['settings_name'] = "company_account_details";
    $settings_data[9]['value'] = "";
    $settings_data[9]['remarks'] = "";

    $settings_data[10]['settings_category'] = "HR";
    $settings_data[10]['settings_name'] = "salary_slip_template";
    $settings_data[10]['value'] = "1";
    $settings_data[10]['remarks'] = "Salary Slip Template Type";

    foreach ($settings_data as $key => $value) {
      $settings = $this->Settings->select_settings("*",array("settings_category"=>$value['settings_category'],"settings_name"=>$value['settings_name']));
      if($settings->num_rows()==0){
        $result = $this->Settings->insert_settings($value);
        if($result['status']==1){
          echo "'".$value['settings_name']."' - Settings Inserted Successfully<br/>";
        }else{
          echo "'".$value['settings_name']."' - Some Error Occurred<br/>";
        }
      }else{
        echo "'".$value['settings_name']."' - Already Exist<br/>";
      }
    }

  }
  public function update_project_budget(){
    $projects = $this->Work->select_work("work_id,total_budget_amount,project_tax_amount", array("w.total_budget_amount !="=>0))->result();
    foreach ($projects as $key => $value) {
      $data['work_id'] = $value->work_id;
      $data['est_budget_amt'] = $value->total_budget_amount;
      $data['total_budget_amount'] = $data['est_budget_amt']+$value->project_tax_amount;
      $result2 = $this->Work->update_work($data);
    }
  }

  public function update_user_roles(){
    $role_data[0]['role_id'] = 8;
    $role_data[0]['role_name'] = "general_manager";
    $role_data[0]['role_title'] = "Section Manager";
    $role_data[0]['mobile_app_access'] = "0";
    $role_data[0]['editable_status'] = "0";
    $role_data[0]['active_status'] = "0";

    $role_data[1]['role_id'] = 9;
    $role_data[1]['role_name'] = "supervisor";
    $role_data[1]['role_title'] = "Area Project Manager";
    $role_data[1]['mobile_app_access'] = "0";
    $role_data[1]['editable_status'] = "0";
    $role_data[1]['active_status'] = "0";

    $role_data[2]['role_id'] = 10;
    $role_data[2]['role_name'] = "supervisor";
    $role_data[2]['role_title'] = "Submission";
    $role_data[2]['mobile_app_access'] = "0";
    $role_data[2]['editable_status'] = "0";
    $role_data[2]['active_status'] = "0";

    $role_data[3]['role_id'] = 11;
    $role_data[3]['role_name'] = "supervisor";
    $role_data[3]['role_title'] = "Interior Section";
    $role_data[3]['mobile_app_access'] = "0";
    $role_data[3]['editable_status'] = "0";
    $role_data[3]['active_status'] = "0";

    $role_data[4]['role_id'] = 12;
    $role_data[4]['role_name'] = "staff";
    $role_data[4]['role_title'] = "Custom Role";
    $role_data[4]['mobile_app_access'] = "0";
    $role_data[4]['editable_status'] = "0";
    $role_data[4]['active_status'] = "0";

    $role_data[5]['role_id'] = 13;
    $role_data[5]['role_name'] = "general_manager";
    $role_data[5]['role_title'] = "Supervising";
    $role_data[5]['mobile_app_access'] = "0";
    $role_data[5]['editable_status'] = "0";
    $role_data[5]['active_status'] = "0";

    $role_data[6]['role_id'] = 14;
    $role_data[6]['role_name'] = "supervisor";
    $role_data[6]['role_title'] = "Custom Role";
    $role_data[6]['mobile_app_access'] = "0";
    $role_data[6]['editable_status'] = "0";
    $role_data[6]['active_status'] = "0";

    $role_data[7]['role_id'] = 15;
    $role_data[7]['role_name'] = "general_manager";
    $role_data[7]['role_title'] = "Project Engineer";
    $role_data[7]['mobile_app_access'] = "0";
    $role_data[7]['editable_status'] = "0";
    $role_data[7]['active_status'] = "0";

    $role_data[8]['role_id'] = 16;
    $role_data[8]['role_name'] = "accounts_manager";
    $role_data[8]['role_title'] = "Accounts Manager";
    $role_data[8]['mobile_app_access'] = "0";
    $role_data[8]['editable_status'] = "0";
    $role_data[8]['active_status'] = "0";

    $role_data[9]['role_id'] = 17;
    $role_data[9]['role_name'] = "supervisor";
    $role_data[9]['role_title'] = "Site Engineer";
    $role_data[9]['mobile_app_access'] = "0";
    $role_data[9]['editable_status'] = "0";
    $role_data[9]['active_status'] = "0";

    $role_data[10]['role_id'] = 18;
    $role_data[10]['role_name'] = "supervisor";
    $role_data[10]['role_title'] = "Site Visitor";
    $role_data[10]['mobile_app_access'] = "0";
    $role_data[10]['editable_status'] = "0";
    $role_data[10]['active_status'] = "0";

    $role_data[11]['role_id'] = 19;
    $role_data[11]['role_name'] = "front_office_staff";
    $role_data[11]['role_title'] = "Front Office Staff";
    $role_data[11]['mobile_app_access'] = "0";
    $role_data[11]['editable_status'] = "0";
    $role_data[11]['active_status'] = "0";


    foreach ($role_data as $key => $value) {
      $where ="(role_id=".$value['role_id'].") or (role_name='".$value['role_name']."' and role_title='".$value['role_title']."')";
      $roles = $this->User->select_user_roles("*",$where);
      if($roles->num_rows()==0){
        $result = $this->User->insert_user_role($value);
        if($result['status']==1){
          echo "'".$value['role_title']."' - Role Inserted Successfully<br/>";
        }else{
          echo "'".$value['role_title']."' - Some Error Occurred<br/>";
        }
      }else{
        echo "'".$value['role_title']."' - Already Exist<br/>";
      }
    }

  }
  public function move_purchase_request(){
    $data = array();
    $requests = $this->Purchase_order->select_purchase_request("po.*,u.user_alias,sl.location_name,sl.work_id,sl.location_type,sl.work_id as location_work_id",$data)->result();
    foreach ($requests as $key => $value) {
      $items = $this->Purchase_order->select_purchase_order_items('',array('poi.order_id'=>$value->order_id))->result();

      $request_data['location_id'] = $value->location_id;
      $request_data['request_date'] = $value->order_date;
      $request_data['remarks'] = $value->remarks;
      $request_data['created_date'] = $value->created_date;
      $request_data['created_by'] = $value->created_by;
      $result = $this->Purchase_request->insert_purchase_request($request_data);
      if($result['status']==1){
        foreach ($items as $key => $value) {
          $item_data = array();
          $item_data['request_id'] = $result['insert_id'];
          $item_data['material_id'] = $value->material_id;
          $item_data['unit_price'] = $value->unit_price;
          $item_data['unit_id'] = $value->unit_id;
          $item_data['total_amount'] = $value->total_amount;
          $item_data['quantity'] = $value->quantity;
          $item_data['description'] = $value->description;
          $result2 = $this->Purchase_request->create_purchase_request_item($item_data);
        }

      }
    }
  }

  public function check_bill_balance_issue(){
    // $data['b.bill_type'] = 'expense';
    $data = array();
    $result	= $this->Bills->select_bills("b.*,ah1.acc_head_name as expense_head_name,u.user_alias,wc.work_name",$data)->result();
    foreach($result as $key=>$value){
      $transaction_data['ats.reference_id'] = $value->bill_id;
      $transaction_data['ats.reference_type'] = $value->bill_type.'_bill';
      $total_paid_amount	= $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$transaction_data,$transaction_data['ats.reference_type'])->row()->total_amount;
      if(($value->bill_payable_amount-$value->bill_total_paid)!=$value->bill_balance_amount){
        $bill_data['bill_balance_amount'] = $value->bill_payable_amount-$value->bill_total_paid;
        if($bill_data['bill_balance_amount']>0){
          if($bill_data['bill_balance_amount']==$value->bill_payable_amount){
            $bill_data['bill_payment_status'] = 0;
          }else{
            $bill_data['bill_payment_status'] = 2;
          }
        }else{
          $bill_data['bill_payment_status'] = 1;
        }
        $bill_data['bill_id'] = $value->bill_id;
        $result = $this->Bills->update_bills($bill_data);
        echo "Bill #".$value->bill_id." - Balance Amount Updated<br/>";
      }
    }
  }
  public function create_supplier_account_head(){
    // Create Supplier Account in Account Heads
    $suppliers	= $this->Supplier->select_supplier('*');
    foreach ($suppliers->result() as $key => $value) {
      $account_head_data = $this->Account->select_account_heads("",array("acc_supplier_id"=>$value->supplier_id));
      if($account_head_data->num_rows()==0){
        // CReate Account Head
        $account_data['acc_head_name'] = $value->supplier_name."'s Account";
        $account_data['account_type'] = 12; //Direct Expense
        $account_data['acc_supplier_id'] = $value->supplier_id;
        $account_data['head_editable'] = 0;
        $account_data['op_balance'] = 0;
        $account_data['created_date'] = date('Y-m-d H:i:s');
        $account_data['created_by'] = 1;
        $account_result = $this->Account->create_account_head($account_data);
        echo "Account Head Created For Supplier #".$value->supplier_id."<br/>";
      }
    }
  }
  public function fix_client_payments(){
    $data['ats.tr_type'] = 'client_payment_transaction';
    $data['ats.reference_type'] = 'project';
    $data['ats.invoice_id'] = 0;
    $result	= $this->Account->select_account_transaction("ats.*,c.client_email,c.client_id,c.client_name,wc.work_id,wc.work_name,u1.user_alias as created_user,u2.user_alias as updated_user,ah2.acc_head_name as credit_account",$data,'client_payment');
    foreach ($result->result() as $key => $value) {
      $received_amount = $value->tr_amount;
      $tax_inclusive = $value->tax_inclusive;
      $taxable_amount = $value->taxable_amount;
      $tax_percent = $value->tax_percent;
      $tax_amount = $value->tax_amount;
      if($tax_inclusive==0){
        if($tax_percent==0 && $taxable_amount!=$received_amount){
          $update_data['transaction_id'] = $value->transaction_id;
          $update_data['taxable_amount'] = $received_amount;
          $transaction_result =  $this->Account->update_account_transaction($update_data);
          echo "Transaction Updated ".$value->transaction_id."<br/>";
        }elseif($tax_percent!=0 && $taxable_amount==0){
          echo "Check Transaction ".$value->transaction_id." (1)<br/>";
        }
      }elseif($tax_inclusive==1 && $tax_percent!=0 && $taxable_amount==0){
        echo "Check Transaction ".$value->transaction_id." (2)<br/>";
      }
    }

  }
  public function fix_supplier_transactions(){
    $this->db->select('*')->from('account_transactions ats');
    $this->db->where("ats.delete_status",0);
    $this->db->where("ats.reference_type",'supplier');
    $result = $this->db->get()->result();
    foreach ($result as $key => $value) {
      $account_head_data = $this->Account->select_account_heads("",array("acc_supplier_id"=>$value->reference_id));
      if($account_head_data->num_rows()==1){
        $update_data['transaction_id'] = $value->transaction_id;
        $update_data['tr_credit_acc'] = $account_head_data->row()->acc_head_id;
        if($account_head_data->row()->acc_head_id!= $value->tr_credit_acc){
          $transaction_result =  $this->Account->update_account_transaction($update_data);
          echo "Transaction Updated ".$value->transaction_id."<br/>";
        }
      }else{
        echo "Supplier Account Error ".$value->transaction_id."<br/>";
      }
    }
  }
  public function fix_user_roles(){
    $value1['role_id'] = 4;
    $value1['active_status'] = 0;
    $this->User->update_user_role($value1);

    $value2['role_id'] = 5;
    $value2['active_status'] = 0;
    $this->User->update_user_role($value2);

    $value3['role_id'] = 6;
    $value3['active_status'] = 0;
    $this->User->update_user_role($value3);
  }
  public function check_purchase_expense_bills(){
    // Check Expense Bills for Deleted Purchase Bills
    $this->db->select('bill_id')->from('bills b');
    $this->db->join('purchase_bills p','p.purchase_id=b.purchase_id');
    $this->db->where("p.delete_status",0);
    $this->db->where("b.delete_status",1);
    $result = $this->db->get()->result();
    foreach ($result as $key => $value) {
      $data['bill_id'] = $value->bill_id;
      $data['delete_status'] = 1;
      $this->Bills->update_bills($data);
      echo "Bill ID #".$data['bill_id']." Deleted<br/>";
    }
  }
  public function fix_supplier_account_head(){
    // Create Supplier Account in Account Heads
    $this->db->select('*')->from('suppliers s');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("s.delete_status",1);
    $suppliers = $this->db->get();
    foreach ($suppliers->result() as $key => $value) {
      $account_head_data = $this->Account->select_account_heads("",array("acc_supplier_id"=>$value->supplier_id,"delete_status"=>0));
      if($account_head_data->num_rows()==1){
        // CReate Account Head
        $account_data['acc_head_id'] = $account_head_data->row()->acc_head_id;
        $account_data['delete_status'] = 1;
        $account_result = $this->Account->update_account_head($account_data);
        echo "Account Head Deleted For Supplier #".$value->supplier_id."<br/>";
      }
    }
  }
  public function fix_loan(){
    $this->db->select('*')->from('loans l');
    if(!empty($data)){
      $this->db->where($data);
    }
    $this->db->where("l.delete_status",0);
    $this->db->where("l.total_loan_amount != l.current_balance_payable");
    $loans = $this->db->get();

    foreach ($loans->result() as $key => $value) {
      echo "Loan ID #".$value->loan_id." Have Issue <br/>";
    }
  }

  public function fix_invoice(){
    $invoices = $this->Invoices->select_invoices("i.*")->result();
    foreach ($invoices as $key => $value) {
      $invoice_update_data['invoice_id'] = $value->invoice_id;
      $invoice_tax_inclusive = $value->invoice_tax_inclusive;
      $invoice_taxable_amount = $value->invoice_taxable_amount;
      $invoice_tax_percent = $value->invoice_tax_percent;
      $invoice_discount_amount = $value->invoice_discount_amount;
      $invoice_total_amount = $value->invoice_total_amount;
      $iem_total = $this->Invoices->select_invoice_items("COALESCE(SUM(ii.total_amount),0) as item_total_amount",array("ii.invoice_id"=>$value->invoice_id))->row()->item_total_amount;
      if($invoice_tax_inclusive==1){
        $invoice_update_data['invoice_taxable_amount'] = round(($iem_total*100/($invoice_tax_percent+100)),$this->config->item('Currency_amount_decimals_2'));
        $invoice_update_data['invoice_tax_amount'] = $iem_total-$invoice_update_data['invoice_taxable_amount'];
      }else{
        $invoice_update_data['invoice_taxable_amount'] = $iem_total;
        $invoice_update_data['invoice_tax_amount'] = round(($invoice_update_data['invoice_taxable_amount']*$invoice_tax_percent/100),$this->config->item('Currency_amount_decimals_2'));
      }
      $transaction_data['ats.invoice_id'] = $value->invoice_id;
      $total_paid_amount  = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_amount",$transaction_data,$transaction_data['ats.invoice_id'])->row()->total_amount;

      $invoice_update_data['total_paid'] = $total_paid_amount;
      $invoice_total_amount = $value->invoice_total_amount;
      $invoice_update_data['balance_amount'] = $invoice_total_amount-$total_paid_amount;
      if($invoice_update_data['balance_amount']>0){
        if($invoice_update_data['balance_amount']==$invoice_total_amount){
          $invoice_update_data['payment_status'] = 0;//not paid
        }else{
          $invoice_update_data['payment_status'] = 2;//partially paid
        }
      }else{
        $invoice_update_data['payment_status'] = 1;//paid
      }
      $result = $this->Invoices->update_invoice($invoice_update_data);
    }
  }
  public function update_stock_register_purchase($bill_id=''){

    // Select Purchase Bill Items
    if($bill_id!=''){
      $this->db->where('pi.purchase_id',$bill_id);
    }
    $total_items = $this->Purchases->select_purchase_items("pi.*,m.material_name,p.location_id,p.supplier_id,p.delete_status as bill_delete_status,pi.delete_status as item_delete_status,p.created_by,p.updated_by",'','','','all');
    foreach ($total_items->result() as $key => $value) {
      $stock_data = array();
      $stock_data['purchase_item_id'] = $value->item_id;
      $stock_data['purchase_supplier_id'] = $value->supplier_id;
      $stock_data['location_id'] = $value->location_id;
      $stock_data['stock_name'] = $value->material_name;
      $stock_data['material_id'] = $value->material_id;
      $stock_data['unit'] = $value->unit_id;
      if($value->quantity!=0){
        $stock_data['unit_price'] = $value->total_amount/$value->quantity;
      }else{
        $stock_data['unit_price'] = 0;
      }
      if($value->bill_delete_status==1 || $value->item_delete_status==1){
        $stock_data['total_purchased_qty'] = 0;
      }else{
        $stock_data['total_purchased_qty'] = $value->quantity;
      }

      //  Check Already Exist
      $stock_count = $this->Stock->select_stock_register("",array("sr.purchase_item_id"=>$stock_data['purchase_item_id']),'','all','all');
      if($stock_count->num_rows()==0){
        // Create New Entry
        $stock_data['created_date'] = date('Y-m-d H:i:s');
        $stock_data['created_by'] = $value->created_by;
        $result = $this->Stock->insert_stock_register($stock_data);
        $this->stock_management->calculate_stock_balance($result['insert_id']);
      }else{
        // Update Existing Entry
        $stock_data['updated_date'] = date('Y-m-d H:i:s');
        $stock_data['updated_by'] = $value->updated_by;
        $stock_data['stock_id'] = $stock_count->row()->stock_id;
        $result = $this->Stock->update_stock_register($stock_data);
        $this->stock_management->calculate_stock_balance($stock_data['stock_id']);
      }
    }
  }

  public function create_default_project_stages()
  {
    $projects = $this->Work->select_work("*")->result();
    foreach ($projects as $key => $value) {
      $stage_count = $this->Work->select_project_stage('*',array('ps.project_id'=>$value->work_id))->num_rows();
      if($stage_count==0){
        // Default Stage
        $stage_data['project_id'] = $value->work_id;
        $stage_data['stage_no'] = 1;
        $stage_data['stage_active_status'] = 1;
        $stage_data['stage_name'] = 'First Stage';
        $stage_data['stage_budget'] = $value->est_budget_amt;

        $stage_data['stage_start_date'] = $value->planned_date_of_start;
        $stage_data['stage_end_date'] = $value->planned_date_of_completion;

        $stage_data['stage_description'] = 'First Stage ';
        $stage_data['created_date'] = date('Y-m-d H:i:s');
        $stage_data['created_by'] = $this->session->userdata('user_id');
        $result_stage = $this->Work->insert_project_stage($stage_data);
        $stage_id = $result_stage['insert_id'];

        $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_work_id' => $value->work_id ))->result();
        foreach ($account_transactions as $key => $at) {
          $transaction_data['transaction_id'] = $at->transaction_id;
          $transaction_data['tr_project_stage_id'] = $stage_id;
          $transaction_result =  $this->Account->update_account_transaction($transaction_data);
        }

        $bills  = $this->Bills->select_bills("b.*",array('b.work_id'=>$value->work_id))->result();
        foreach ($bills as $key => $b) {
          $bill_data['bill_id'] = $b->bill_id;
          $bill_data['project_stage_id'] = $stage_id;
          $bill_result =  $this->Bills->update_bills($bill_data);

          $reference_type = $b->bill_type."_bill";
          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.reference_type' => $reference_type,'ats.reference_id' => $b->bill_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }



        }

        $daily_notes = $this->Daily_reports->select_daily_notes("dn.*",array('dn.work_id'=>$value->work_id))->result();
        foreach ($daily_notes as $key => $dn) {
          $dn_data['note_id'] = $dn->note_id ;
          $dn_data['project_stage_id'] = $stage_id;
          $dn_result =  $this->Daily_reports->update_daily_note($dn_data);
        }

        $daily_tasks = $this->Daily_reports->select_task_report("dt.*",array('dt.work_id'=>$value->work_id))->result();
        foreach ($daily_tasks as $key => $dt) {
          $dt_data['task_id'] = $dt->task_id ;
          $dt_data['project_stage_id'] = $stage_id;
          $dt_result = $this->Daily_tasks->update($dt_data);
        }

        $documents = $this->Documents->select_documents("pd.*",array('pd.work_id'=>$value->work_id))->result();
        foreach ($documents as $key => $d) {
          $d_data['id'] = $d->id ;
          $d_data['project_stage_id'] = $stage_id;
          $d_result = $this->Documents->update_document($d_data);
        }

        $invoices = $this->Invoices->select_invoices("i.*",array('i.project_id'=>$value->work_id))->result();
        foreach ($invoices as $key => $i) {
          $i_data['invoice_id'] = $i->invoice_id ;
          $i_data['project_stage_id'] = $stage_id;
          $i_result = $this->Invoices->update_invoice($i_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.invoice_id' => $i->invoice_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }

        }

        $labour_wages = $this->Labour_wages->select_labour_wages("lw.*",array('lw.work_id'=>$value->work_id))->result();
        foreach ($labour_wages as $key => $lw) {
          $lw_data['wage_id'] = $lw->wage_id ;
          $lw_data['project_stage_id'] = $stage_id;
          $lw_result = $this->Labour_wages->update_labour_wage($lw_data);



          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'labour_transaction','ats.reference_id' => $lw->labour_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }


        }

        $loans = $this->Loan->select_loan("l.*",array('l.work_id'=>$value->work_id))->result();
        foreach ($loans as $key => $l) {
          $l_data['loan_id'] = $l->loan_id ;
          $l_data['project_stage_id'] = $stage_id;
          $lw_result = $this->Loan->update_loan($l_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'loan_receipt_transaction','ats.reference_id' => $l->loan_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }


        }

        $project_tasks = $this->Project_tasks->select_tasks("pt.*",array('pt.work_id'=>$value->work_id))->result();
        foreach ($project_tasks as $key => $pt) {
          $pt_data['task_id'] = $pt->task_id ;
          $pt_data['project_stage_id'] = $stage_id;
          $pt_result = $this->Project_tasks->update_task($pt_data);
        }

        $purchase_orders = $this->Purchase_order->select_purchase_order("po.*",array('sl.work_id'=>$value->work_id))->result();
        foreach ($purchase_orders as $key => $po) {
          $po_data['order_id'] = $po->order_id ;
          $po_data['project_stage_id'] = $stage_id;
          $po_result = $this->Purchase_order->update_purchase_order($po_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'purchase_order_transaction','ats.reference_id' => $po->order_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }


        }

        $purchases = $this->Purchases->select_purchase("p.*",array('sl.work_id'=>$value->work_id))->result();
        foreach ($purchases as $key => $p) {
          $p_data['purchase_id'] = $p->purchase_id ;
          $p_data['project_stage_id'] = $stage_id;
          $p_result = $this->Purchases->update_purchase($p_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'purchase_bill_transaction','ats.reference_id' => $p->purchase_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }

        }

        $salary_slips = $this->Salary_slips->select_salary_slips("ss.*",array('ss.work_id'=>$value->work_id))->result();
        foreach ($salary_slips as $key => $ss) {
          $ss_data['salary_id'] = $ss->salary_id ;
          $ss_data['project_stage_id'] = $stage_id;
          $ss_result = $this->Salary_slips->update_salary_slip($ss_data);




          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'salary_slip_transaction','ats.reference_id' => $ss->salary_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }

        }

        $subcontracts = $this->Subcontracts->select_subcontract("sc.*",array('sc.work_id'=>$value->work_id))->result();
        foreach ($subcontracts as $key => $sc) {
          $sc_data['contract_id'] = $sc->contract_id ;
          $sc_data['project_stage_id'] = $stage_id;
          $sc_result = $this->Subcontracts->update_subcontract($sc_data);

        }

        $vehicle_work_slips = $this->Vehicle_work_slips->select_vehicle_work_slips("vws.*",array('vws.vehicle_work_id'=>$value->work_id))->result();
        foreach ($vehicle_work_slips as $key => $vws) {
          $vws_data['work_slip_id'] = $vws->work_slip_id ;
          $vws_data['project_stage_id'] = $stage_id;
          $sc_result = $this->Vehicle_work_slips->update_vehicle_work_slip($vws_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.tr_type' => 'vehicle_work_slip_transaction','ats.reference_id' => $vws->work_slip_id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }

        }

        $tool_transfers_from = $this->Tools->select_tool_transfers("tt.*",array('tt.transfer_from'=>$value->work_id,'tt.transfer_from!=',0))->result();
        foreach ($tool_transfers_from as $key => $ttf) {
          $ttf_data['transfer_id'] = $ttf->transfer_id ;
          $ttf_data['project_stage_id'] = $stage_id;
          $ttf_result = $this->Tools->update_tool_transfer($ttf_data);
        }

        $tool_transfers_to = $this->Tools->select_tool_transfers("tt.*",array('tt.transfer_to'=>$value->work_id,'tt.transfer_from'=>0))->result();
        foreach ($tool_transfers_to as $key => $ttt) {
          $ttt_data['transfer_id'] = $ttt->transfer_id ;
          $ttt_data['project_stage_id'] = $stage_id;
          $ttt_result = $this->Tools->update_tool_transfer($ttt_data);
        }

        $tool_rents = $this->Tools->select_tool_rent("tr.return_status,tr.id,tr.rented_from,tr.rented_qty,tr.rented_date,tr.total_returned_qty,tr.balance_to_return,tr.returned_log")->result();
        foreach ($tool_rents as $key => $tr) {
          $tr_data['id'] = $tr->id ;
          $tr_data['project_stage_id'] = $stage_id;
          $tr_result = $this->Tools->update_tool_rent($tr_data);


          $account_transactions = $this->Account->select_account_transaction("ats.transaction_id",array('ats.reference_type' => 'tool_rent','ats.reference_id' => $tr->id ))->result();
          foreach ($account_transactions as $key => $at) {
            $transaction_data['transaction_id'] = $at->transaction_id;
            $transaction_data['tr_project_stage_id'] = $stage_id;
            $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          }


        }

        $stock_transfers = $this->Stock->select_stock_transfers("st.*")->result();
        foreach ($stock_transfers as $key => $st) {
          $st_data['transfer_id'] = $st->transfer_id;
          $work_data_1=$this->Work->select_work("w.work_id",array("work_id"=>$st->transferred_to_loc_id));
          if($work_data_1->num_rows()==1){
            $st_data['transfer_to_project_stage_id'] = $st->transferred_to_loc_id;
          }
          $work_data_2=$this->Work->select_work("w.work_id",array("work_id"=>$st->transferred_from_loc_id));
          if($work_data_2->num_rows()==1){
            $st_data['transfer_from_project_stage_id'] = $st->transferred_to_loc_id;
          }
          $stock_transfer_result = $this->Stock->update_stock_transfer($st_data);
        }

        print_r($stage_count);
      }
    }
  }
  public function update_project_stock(){
    $projects = $this->Work->select_work("work_id,total_budget_amount,project_tax_amount")->result();
    foreach ($projects as $key => $value) {
      $this->stock_management->calculate_stock_balance_by_project($value->work_id);
    }
  }
  public function fix_user_account_heads(){
    $account_data['account_type'] = 32;
    $account_data['acc_user_id !='] = 0;
    $account_details = $this->Account->select_account_heads("*",$account_data);
    if($account_details->num_rows()==1){
      // Check user deleted
      $count = $this->User->select_user('',array("user_id"=>$account_details->row()->acc_user_id))->num_rows();
      if($count==0){
        $account_data['acc_head_id'] = $account_details->row()->acc_head_id;
        $account_data['delete_status'] = 1;
        $this->Account->update_account_head($account_data);
      }

    }
  }
  public function update_bill_transaction_heads(){
    // Update Head(tr_credit_acc) in Transaction
    $this->db->select('ats.transaction_id,b.bill_credit_ac,ats.tr_credit_acc')->from('account_transactions ats');
    $this->db->join('bills b','ats.reference_id=b.bill_id','left');
    $this->db->where('ats.reference_type','expense_bill');
    $this->db->where('ats.tr_type','expense_bill_transaction');
    $bill_transactions = $this->db->get()->result();
    foreach ($bill_transactions as $key => $value) {
      if($value->bill_credit_ac!=$value->tr_credit_acc){
        $transaction_update_data['transaction_id'] = $value->transaction_id;
        $transaction_update_data['tr_credit_acc'] = $value->bill_credit_ac;
        // var_dump($transaction_update_data);
        $this->Account->update_account_transaction($transaction_update_data);
      }
    }
  }
  public function update_tool_rent_price(){
    $result = $this->Tools->select_tool_rent("tr.*,t.price")->result();
    foreach($result as $row){
      $rent_update_data['id'] = $row->id;
      $rent_update_data['rent_price'] = $row->price;
      $result = $this->Tools->update_tool_rent($rent_update_data);
    }
  }
  public function travel_allowance_transactions(){
    $data = array();
    $result = $this->Travel_allowance->select_ta("ta.*,u1.user_alias AS ta_created_by",$data)->result();
    foreach($result as $row){
      $ta_transaction_where['ats.reference_type'] = 'travel_allowance';
      $ta_transaction_where['ats.tr_type'] = 'travel_allowance_transaction';
      $ta_transaction_where['ats.reference_id'] = $row->ta_id;
      $ta_transactions = $this->Account->select_account_transaction("ats.transaction_id", $ta_transaction_where,'travel_allowance');
      if($ta_transactions->num_rows()==0){
        // Insert to Account Transaction
        $account_heads_where['ah.delete_status'] = 0;
        $account_heads_where['ah.acc_user_id'] = $row->user_id;
        $account_heads_data	= $this->Account->select_account_heads("acc_head_id",$account_heads_where);
        if($account_heads_data->num_rows()==1){
          $account_heads_data = $account_heads_data->row();
          $transaction_data['tr_debit_acc'] = $account_heads_data->acc_head_id;
          $transaction_data['reference_id'] = $row->ta_id;
          $transaction_data['reference_type'] = "travel_allowance";
          $transaction_data['tr_type'] = $transaction_data['reference_type']."_transaction";
          $transaction_data['tr_date'] = $row->ta_date;
          $transaction_data['tr_credit_acc'] = 22;
          $transaction_data['tr_description'] = ucwords(str_replace('_',' ',$transaction_data['tr_type']));
          $transaction_data['tr_amount'] = $row->amount;
          $transaction_data['tr_mode'] = 'CASH';
          $transaction_data['created_date'] = $row->created_date;
          $transaction_data['created_by'] = $row->created_by;
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
        }

      }
    }
  }
  public function update_bill_tax_percent_to_item(){
    $data['p.bill_tax_percent !='] = 0;
    $purchase_bills = $this->Purchases->select_purchase("p.*",$data)->result();
    foreach ($purchase_bills as $key1 => $row) {
      $items = $this->Purchases->select_purchase_items("pi.*",array("pi.purchase_id"=>$row->purchase_id))->result();
      $total_bill_tax_amount = 0;
      foreach ($items as $key => $value) {
        $item_data['item_id'] = $value->item_id;
        // if($value->tax_percent==0 && $value->tax_amount==0){
        $item_data['tax_percent'] = $row->bill_tax_percent;
        $total_amount = $value->total_amount;
        $unit_price = $value->unit_price;
        $qty = $value->quantity;
        $item_data['tax_amount'] = round(($value->quantity*$value->unit_price*$item_data['tax_percent']/100),$this->config->item('Currency_amount_decimals_2'));
        $total_bill_tax_amount += $item_data['tax_amount'];
        $item_data['total_amount'] = $total_amount + $item_data['tax_amount'];
        $item_result =  $this->Purchases->update_purchase_item($item_data);
      }
      // }
      if(round($total_bill_tax_amount) != round($row->bill_tax_amount)){
        echo "Issue found for Purchase Bill - ".$row->purchase_id." Item Total Tax=".$total_bill_tax_amount.", Bill Tax=".$row->bill_tax_amount."<br/>";
      }
    }
  }

  public function fix_supplier_return_payments(){
    $supplier_advance_payments = $this->Account->select_advance_return_transaction("art.*,u.user_alias as created_user")->result();
    foreach ($supplier_advance_payments as $key => $value) {
      if($value->reference_type=='purchase_bill' && $value->tr_type=='purchase_bill_transaction'){
        $purchase_bill = $this->Purchases->select_purchase("*,p.created_by as purchase_created_by", array("p.purchase_id" =>$value->reference_id ));
        if($purchase_bill->num_rows()==1){
          $this->bills_management->calculate_purchase_bill_total($purchase_bill->row()->purchase_id);
          echo "Purchase Bill ".$purchase_bill->row()->purchase_id." Updated <br/>";
        }else{
          $advance_return_transaction['tr_id'] = $value->tr_id;
          $advance_return_transaction['delete_status'] = 1;
          $this->Account->update_advance_return_transaction($advance_return_transaction);
          echo "TR ID".$value->tr_id." Deleted <br/>";
        }
      }elseif($value->reference_type=='purchase_order' && $value->tr_type=='purchase_order_transaction'){
        $purchase_order = $this->Purchase_order->select_purchase_order("*,po.created_by as order_created_by", array("po.order_id" =>$value->reference_id ));
        if($purchase_order->num_rows()==1){
          echo "Purchase Order".$purchase_order->row()->order_id." Updated <br/>";
        }else{
          $advance_return_transaction['tr_id'] = $value->tr_id;
          $advance_return_transaction['delete_status'] = 1;
          $this->Account->update_advance_return_transaction($advance_return_transaction);
          echo "TR ID".$value->tr_id." Deleted <br/>";
        }
      }else{
        echo "error for TR ID".$value->tr_id."<br/>";
      }
    }

  }
  public function loan_provider_head(){
    $loans	= $this->Loan->select_loan("l.*,u.user_alias as created_user,ah1.acc_head_name,wc.work_name",array("provider_id"=>0))->result();
    foreach ($loans as $key => $value) {
      $update_data['loan_id'] = $value->loan_id;
      $provider_data = $this->Loan->select_loan_provider("",array("loan_provider_name"=>$value->provider));
      if($provider_data->num_rows()>0){
        $update_data['provider_id'] = $provider_data->row()->loan_provider_id;
      }else{
        $data['loan_provider_name'] = $value->provider;
        $result = $this->Loan->create_loan_provider($data);
        $update_data['provider_id'] = $result['insert_id'];
      }
      $result2 = $this->Loan->update_loan($update_data);
      echo "Loan #".$value->loan_id."  Updated<br/>";
    }
  }
  public function salary_advance_project(){
    $salary_advance_transactions = $this->Account->select_account_transaction("ats.*",array('ats.tr_type' => 'salary_advance_transaction','ats.tr_work_id' =>0 ))->result();
    foreach ($salary_advance_transactions as $key => $row) {
      // Select Salary Slip of this Month
      $salary_slip_where['ss.employee_id'] = $row->reference_id;
      $salary_slip_where['ss.month'] = $row->tr_other_data."-01";
      $salary_slips = $this->Salary_slips->select_salary_slips("ss.*",$salary_slip_where);
      if($salary_slips->num_rows()==1){
        $transaction_update_data['tr_work_id'] = $salary_slips->row()->work_id;
        $transaction_update_data['transaction_id'] = $row->transaction_id;
        $transaction_Update_result = $this->Account->update_account_transaction($transaction_update_data);
        echo "Success: Work ID Updated For Transaction #".$row->transaction_id."<br/>";
      }elseif($salary_slips->num_rows()==0){
        echo "Not Found : No Salary Slip Generated For Transaction #".$row->transaction_id."<br/>";
      }else{
        echo "Error: Multiple Salary Slip Found For Transaction #".$row->transaction_id."<br/>";
      }
    }
  }
  public function subcontract_contractor_update(){
    $subcontracts = $this->db->select('*')->from('sub_contracts sc')->get();
    foreach ($subcontracts->result() as $key => $value) {
      if (is_numeric($value->contractor)) {

      }else {
        $data['contractor_name'] = $value->contractor;
        $count = $this->Subcontracts->select_contractors("",$data);
        if($count->num_rows() == 0) {
          $result = $this->Subcontracts->create_contractor($data);
          $update_data['contractor'] = $result['insert_id'];
        }else{
          $update_data['contractor'] = $count->row()->contractor_id;
        }
        $update_data['contract_id'] = $value->contract_id;
        $result = $this->Subcontracts->update_subcontract($update_data);
      }
    }
  }
  public function check_date_format_issues(){
    $account_transactions = $this->db->select('*')->from('account_transactions')->where("tr_date like '%1970%'")->get()->result();
    foreach ($account_transactions as $key => $value) {
      echo "Date Issue Found, Type=Account Transaction, ID:".$value->transaction_id."<br/>";
    }
    $bills = $this->db->select('*')->from('bills')->where("bill_date like '%1970%'")->get()->result();
    foreach ($bills as $key => $value) {
      echo "Date Issue Found, Type=Bills, ID:".$value->bill_id."<br/>";
    }
    $boq_daily_progress = $this->db->select('*')->from('boq_daily_progress')->where("date like '%1970%'")->get()->result();
    foreach ($boq_daily_progress as $key => $value) {
      echo "Date Issue Found, Type=BOQ Daily Progress, ID:".$value->id."<br/>";
    }
    $client_invoices = $this->db->select('*')->from('client_invoices')->where("invoice_date like '%1970%'")->get()->result();
    foreach ($client_invoices as $key => $value) {
      echo "Date Issue Found, Type=Client Invoice, ID:".$value->invoice_id."<br/>";
    }
    $daily_labour_report = $this->db->select('*')->from('daily_labour_report')->where("report_date like '%1970%'")->get()->result();
    foreach ($daily_labour_report as $key => $value) {
      echo "Date Issue Found, Type=Daily Labour Report, ID:".$value->report_id."<br/>";
    }
    $daily_notes = $this->db->select('*')->from('daily_notes')->where("note_date like '%1970%'")->get()->result();
    foreach ($daily_notes as $key => $value) {
      echo "Date Issue Found, Type=Daily Note, ID:".$value->note_id."<br/>";
    }
    $daily_tasks = $this->db->select('*')->from('daily_tasks')->where("task_due_date like '%1970%'")->get()->result();
    foreach ($daily_tasks as $key => $value) {
      echo "Date Issue Found, Type=Daily Tasks, ID:".$value->task_id."<br/>";
    }
    $daily_task_report = $this->db->select('*')->from('daily_task_report')->where("report_date like '%1970%'")->get()->result();
    foreach ($daily_task_report as $key => $value) {
      echo "Date Issue Found, Type=Daily Task Report, ID:".$value->report_id."<br/>";
    }
    $employee_attendance = $this->db->select('*')->from('employee_attendance')->where("attendance_date like '%1970%'")->get()->result();
    foreach ($employee_attendance as $key => $value) {
      echo "Date Issue Found, Type=Employee Attendance, ID:".$value->attendance_id."<br/>";
    }
    $enquiries = $this->db->select('*')->from('enquiries')->where("enquiry_date like '%1970%'")->get()->result();
    foreach ($enquiries as $key => $value) {
      echo "Date Issue Found, Type=Enquiruies, ID:".$value->enquiry_id."<br/>";
    }
    $enquiry_followups = $this->db->select('*')->from('enquiry_followups')->where("followup_date like '%1970%'")->get()->result();
    foreach ($enquiry_followups as $key => $value) {
      echo "Date Issue Found, Type=Enquiry Followups, ID:".$value->followup_id."<br/>";
    }
    $labour_wages = $this->db->select('*')->from('labour_wages')->where("work_date like '%1970%'")->get()->result();
    foreach ($labour_wages as $key => $value) {
      echo "Date Issue Found, Type=Labour Wages, ID:".$value->wage_id."<br/>";
    }
    $loans = $this->db->select('*')->from('loans')->where("loan_date like '%1970%'")->get()->result();
    foreach ($loans as $key => $value) {
      echo "Date Issue Found, Type=Loans, ID:".$value->loan_id."<br/>";
    }
    $payment_schedules = $this->db->select('*')->from('payment_schedules')->where("scheduled_date like '%1970%'")->get()->result();
    foreach ($loans as $key => $value) {
      echo "Date Issue Found, Type=Payment Schedule, ID:".$value->schedule_id."<br/>";
    }
    $project_document_revisions = $this->db->select('*')->from('project_document_revisions')->where("send_date like '%1970%'")->get()->result();
    foreach ($project_document_revisions as $key => $value) {
      echo "Date Issue Found, Type=Project Document Revisions, ID:".$value->revision_id."<br/>";
    }
    $project_stages = $this->db->select('*')->from('project_stages')->where("(stage_start_date like '%1970%' or stage_end_date like '%1970%')")->get()->result();
    foreach ($project_stages as $key => $value) {
      echo "Date Issue Found, Type=Project Stages, ID:".$value->stage_id."<br/>";
    }
    $project_tasks = $this->db->select('*')->from('project_tasks')->where("(planned_start_date like '%1970%' or planned_end_date like '%1970%' or actual_start_date like '%1970%' or actual_end_date like '%1970%')")->get()->result();
    foreach ($project_tasks as $key => $value) {
      echo "Date Issue Found, Type=Project Tasks, ID:".$value->task_id."<br/>";
    }
    $project_task_activities = $this->db->select('*')->from('project_task_activities')->where("activity_date like '%1970%'")->get()->result();
    foreach ($project_task_activities as $key => $value) {
      echo "Date Issue Found, Type=Project Task Activities, ID:".$value->id."<br/>";
    }
    $purchase_bills = $this->db->select('*')->from('purchase_bills')->where("purchase_date like '%1970%'")->get()->result();
    foreach ($purchase_bills as $key => $value) {
      echo "Date Issue Found, Type=Purchase Bill, ID:".$value->purchase_id."<br/>";
    }
    $purchase_order = $this->db->select('*')->from('purchase_order')->where("order_date like '%1970%'")->get()->result();
    foreach ($purchase_order as $key => $value) {
      echo "Date Issue Found, Type=Purchase Order, ID:".$value->order_id."<br/>";
    }
    $purchase_request = $this->db->select('*')->from('purchase_request')->where("request_date like '%1970%'")->get()->result();
    foreach ($purchase_request as $key => $value) {
      echo "Date Issue Found, Type=Purchase Request, ID:".$value->request_id."<br/>";
    }
    $salary_slips = $this->db->select('*')->from('salary_slips')->where("month like '%1970%'")->get()->result();
    foreach ($salary_slips as $key => $value) {
      echo "Date Issue Found, Type=Salary Slip, ID:".$value->salary_id."<br/>";
    }
    $sales_invoices = $this->db->select('*')->from('sales_invoices')->where("invoice_date like '%1970%'")->get()->result();
    foreach ($sales_invoices as $key => $value) {
      echo "Date Issue Found, Type=Sales Invoice, ID:".$value->invoice_id."<br/>";
    }
    $stock_consumption = $this->db->select('*')->from('stock_consumption')->where("consumption_date like '%1970%'")->get()->result();
    foreach ($stock_consumption as $key => $value) {
      echo "Date Issue Found, Type=Stock Consumption, ID:".$value->cons_id."<br/>";
    }
    $stock_transfers = $this->db->select('*')->from('stock_transfers')->where("transfer_date like '%1970%'")->get()->result();
    foreach ($stock_transfers as $key => $value) {
      echo "Date Issue Found, Type=Stock Transfer, ID:".$value->transfer_id."<br/>";
    }
    $sub_contract_labour_attendance = $this->db->select('*')->from('sub_contract_labour_attendance')->where("date like '%1970%'")->get()->result();
    foreach ($sub_contract_labour_attendance as $key => $value) {
      echo "Date Issue Found, Type=Subcontract Labour Attendance, ID:".$value->attendance_id."<br/>";
    }
    $supplier_advance_redeem = $this->db->select('*')->from('supplier_advance_redeem')->where("tr_date like '%1970%'")->get()->result();
    foreach ($supplier_advance_redeem as $key => $value) {
      echo "Date Issue Found, Type=Supplier Advance Redeem, ID:".$value->tr_id."<br/>";
    }
    $tools_purchase = $this->db->select('*')->from('tools_purchase')->where("purchased_date like '%1970%'")->get()->result();
    foreach ($tools_purchase as $key => $value) {
      echo "Date Issue Found, Type=Tools Purchase, ID:".$value->purchase_id."<br/>";
    }
    $tools_transfers = $this->db->select('*')->from('tools_transfers')->where("transfer_date like '%1970%'")->get()->result();
    foreach ($tools_transfers as $key => $value) {
      echo "Date Issue Found, Type=Tools Transfer, ID:".$value->transfer_id."<br/>";
    }
    $tool_rent = $this->db->select('*')->from('tool_rent')->where("rented_date like '%1970%'")->get()->result();
    foreach ($tool_rent as $key => $value) {
      echo "Date Issue Found, Type=Tools Rent, ID:".$value->id."<br/>";
    }
    $travel_allowance = $this->db->select('*')->from('travel_allowance')->where("ta_date like '%1970%'")->get()->result();
    foreach ($travel_allowance as $key => $value) {
      echo "Date Issue Found, Type=Travel Allowance, ID:".$value->ta_id."<br/>";
    }
    $user_attendance = $this->db->select('*')->from('user_attendance')->where("attendance_date like '%1970%'")->get()->result();
    foreach ($user_attendance as $key => $value) {
      echo "Date Issue Found, Type=User Attendance, ID:".$value->attendance_id."<br/>";
    }
    $user_attendance_project_wise = $this->db->select('*')->from('user_attendance_project_wise')->where("attendance_date like '%1970%'")->get()->result();
    foreach ($user_attendance_project_wise as $key => $value) {
      echo "Date Issue Found, Type=User Attendance Project Wise, ID:".$value->attendance_id."<br/>";
    }
    $user_leave_applications = $this->db->select('*')->from('user_leave_applications')->where("leave_date like '%1970%'")->get()->result();
    foreach ($user_leave_applications as $key => $value) {
      echo "Date Issue Found, Type=User Leave Application, ID:".$value->application_id."<br/>";
    }
    $vehicle_work_slips = $this->db->select('*')->from('vehicle_work_slips')->where("worked_date like '%1970%'")->get()->result();
    foreach ($vehicle_work_slips as $key => $value) {
      echo "Date Issue Found, Type=Wehicle Work Slip, ID:".$value->work_slip_id."<br/>";
    }
    $work_contracts = $this->db->select('*')->from('work_contracts')->where("(planned_date_of_start like '%1970%' or planned_date_of_completion like '%1970%' or actual_start_date like '%1970%' or actual_end_date like '%1970%' or project_completed_date like '%1970%')")->get()->result();
    foreach ($work_contracts as $key => $value) {
      echo "Date Issue Found, Type=Work Contracts, ID:".$value->work_id."<br/>";
    }
  }
  public function purchase_bill_payment_part_update(){
    $purchase_bill_payments = $this->Account->select_account_transaction("ats.*,p.purchase_order_id,p.created_date as bill_created_date", array("ats.tr_payment_part" => 0,"ats.tr_copy_from" => 0, "ats.reference_type" => 'purchase_bill'),'purchase_bill')->result();
    foreach ($purchase_bill_payments as $key => $value) {
      if($value->created_date>$value->bill_created_date){
        $transaction_data['transaction_id'] = $value->transaction_id;
        $transaction_data['tr_payment_part'] = 2;
        $transaction_result =  $this->Account->update_account_transaction($transaction_data);
        echo "Transaction #".$value->transaction_id." Updated<br/>";
      }
    }
  }
  public function link_purchase_bill_order_payments(){
    $purchase_bill_payments = $this->Account->select_account_transaction("ats.*,p.purchase_order_id", array("ats.tr_payment_part" => 0,"ats.tr_copy_from" => 0,"p.purchase_order_id !=" => 0, "ats.reference_type" => 'purchase_bill'),'purchase_bill')->result();
    foreach ($purchase_bill_payments as $key => $value) {
      $purchase_order_payment_where['ats.reference_id'] = $value->purchase_order_id;
      $purchase_order_payment_where['ats.reference_type'] = 'purchase_order';
      $purchase_order_payment_where['ats.tr_date'] = $value->tr_date;
      $purchase_order_payment_where['ats.tr_debit_acc'] = $value->tr_debit_acc;
      $purchase_order_payment_where['ats.tr_mode'] = $value->tr_mode;
      $purchase_order_payment_where['ats.tr_reference_no'] = $value->tr_reference_no;
      $purchase_order_payment_where['ats.tr_reference_date'] = $value->tr_reference_date;
      $purchase_order_payment_where['ats.tr_remarks'] = $value->tr_remarks;
      $purchase_order_payments = $this->Account->select_account_transaction("ats.*", $purchase_order_payment_where,'purchase_order');
      if($purchase_order_payments->num_rows()>0){
        if($purchase_order_payments->num_rows()==1){
          $transaction_data['transaction_id'] = $value->transaction_id;
          $transaction_data['tr_copy_from'] = $purchase_order_payments->row()->transaction_id;
          $transaction_result =  $this->Account->update_account_transaction($transaction_data);
          echo "Transaction #".$value->transaction_id." Updated<br/>";
        }else{
          echo "Multiple Expected Match Found For TR ID: #".$value->transaction_id."; Order ID:".$value->purchase_order_id."<br/>";
        }
      }
    }
  }
  public function tax_config_updates(){
    $tax_percent = $this->Settings->select_settings('*',array("settings_name"=>'tax_percent'))->row()->value;
    $tax_percent = explode(",",$tax_percent);
    foreach($tax_percent as $row){
      $settings_data = array();
      $settings_data['tax_percentage'] = $row;
      $settings = $this->Settings->select_tax_types("*",$settings_data);
      if($settings->num_rows()==0){
        $settings_data['tax_id'] = $row;
        $result = $this->Settings->insert_tax_types($settings_data);
      }

    }
    $update_data['tax_id'] = 0;
    $this->db->where('tax_percentage', 0);
    $query=$this->db->update('tax_types', $update_data);
  }
  public function fix_mobile_app_purchase_bill(){
    // Fix Purchase bill Gross Amount And Payable Amount Entered from Mobile
    $purchase_bills	= $this->db->select("p.purchase_id,p.work_id")->from('purchase_bills p')->where("p.created_by !=",1)->get()->result();
    foreach ($purchase_bills as $key => $value) {

    }
  }
  public function check_stock_transfer_date(){
    $this->db->where('(st.transfer_date="0000-00-00" or st.transfer_date="1970-01-01")');
    $stock_transfers = $this->Stock->select_stock_transfers("st.*")->result();
    foreach ($stock_transfers as $key => $st) {
      $st_data['transfer_id'] = $st->transfer_id;
      $st_data['transfer_date'] = date('Y-m-d',strtotime($st->created_date));
      $stock_transfer_result = $this->Stock->update_stock_transfer($st_data);
      echo "Stock Transfer #".$st_data['transfer_id']." Date Updated<br/>";
    }
  }
  public function fix_vehicle_work_slip($check=''){
    $data = array();
    $work_slips	= $this->Vehicle_work_slips->select_vehicle_work_slips("u.*,v.*,wc.*,vws.*,vws.basic_charge AS vws_basic_charge,vws.remarks AS vws_remarks,vws.balance AS vws_balance,vws.created_by AS vws_created_by,vws.created_date AS vws_created_date,vws.updated_by AS vws_updated_by,vws.updated_date AS vws_updated_date",$data,"","","","","")->result();
    foreach ($work_slips as $key => $value) {
      $total_paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $value->work_slip_id, "ats.reference_type" => 'vehicle_work_slip'),'vehicle_work_slip')->row()->total_paid_amount;

      $data['work_slip_id']=$value->work_slip_id;
      $bill_payable_amount=$value->total_payable_amount;
      if($value->total_paid!=0 && $value->balance==0 && $value->total_paid!=$total_paid_amount){
        if($total_paid_amount==0){
          $transaction_data['reference_id'] = $value->work_slip_id;
          $transaction_data['reference_type'] = "vehicle_work_slip";
          $transaction_data['tr_type'] = "vehicle_work_slip_transaction";
          $transaction_data['tr_date'] = $value->worked_date;
          $transaction_data['tr_debit_acc'] = 1;
          $transaction_data['tr_credit_acc'] = 12;//vehicle work slip
          $transaction_data['tr_description'] = "Vehicle Work Slip Transaction";
          $transaction_data['tr_amount'] = $value->total_paid;
          $transaction_data['tr_mode'] = 'CASH';
          $transaction_data['tr_reference_no'] = '';
          $transaction_data['tr_remarks'] = '';
          $transaction_data['created_date'] = $value->created_date;
          $transaction_data['created_by'] = $value->created_by;

          if($check=='fix'){
            $transaction_result =  $this->Account->create_account_transaction($transaction_data);
            echo "Transaction Added for Slip #".$value->work_slip_id."<br/>";
          }else{
            echo "Transaction Need to Add for Slip #".$value->work_slip_id."<br/>";
          }
        }else{
          echo "Error with Slip #".$value->work_slip_id."<br/>";
        }
      }elseif($value->total_paid==0 && $value->balance==0 && $value->total_payable_amount!=0){
        $transaction_data['reference_id'] = $value->work_slip_id;
        $transaction_data['reference_type'] = "vehicle_work_slip";
        $transaction_data['tr_type'] = "vehicle_work_slip_transaction";
        $transaction_data['tr_date'] = $value->worked_date;
        $transaction_data['tr_debit_acc'] = 1;
        $transaction_data['tr_credit_acc'] = 12;//vehicle work slip
        $transaction_data['tr_description'] = "Vehicle Work Slip Transaction";
        $transaction_data['tr_amount'] = $value->total_payable_amount;
        $transaction_data['tr_mode'] = 'CASH';
        $transaction_data['tr_reference_no'] = '';
        $transaction_data['tr_remarks'] = '';
        $transaction_data['created_date'] = $value->created_date;
        $transaction_data['created_by'] = $value->created_by;

        if($check=='fix'){
          $transaction_result =  $this->Account->create_account_transaction($transaction_data);
          echo "Transaction Added for Slip #".$value->work_slip_id."<br/>";
        }else{
          echo "Transaction Need to Add for Slip #".$value->work_slip_id."<br/>";
        }
      }

      if($check=='fix'){
        $total_paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $value->work_slip_id, "ats.reference_type" => 'vehicle_work_slip'),'vehicle_work_slip')->row()->total_paid_amount;
        if($value->total_paid!=$total_paid_amount){
          $bill_payable_amount=$value->total_payable_amount;
          $data['total_paid']=$total_paid_amount;
          $data['balance']=$bill_payable_amount-$data['total_paid'];
          $result1 = $this->Vehicle_work_slips->update_vehicle_work_slip($data);
          echo " Slip #".$value->work_slip_id." Updated<br/>";
        }
        $this->bills_management->calculate_vehicle_work_slip_total($value->work_slip_id);
      }



    }
  }
  public function update_invoice_from(){
    $company_address = $this->config->item('company_name')."<br/>".$this->config->item('company_address');
    $company_address = str_replace('<br />','<br/>',$company_address);
    $company_address = str_replace('<br/>','<br/>',$company_address);
    $company_address = str_replace('<br>','<br/>',$company_address);

    $invoices = $this->Invoices->select_invoices("i.*")->result();
    foreach ($invoices as $key => $value) {
      $invoice_update_data['invoice_id'] = $value->invoice_id;
      $invoice_update_data['invoice_from'] = $company_address;
      $result = $this->Invoices->update_invoice($invoice_update_data);
    }
  }
  public function user_employee_link(){
    // Update Existing User Linked Employee Data
    $user_linked_employees = $this->db->select('*')->from('employees e')->where("user_id !=",0)->get()->result();
    foreach ($user_linked_employees as $key => $value) {
      $user_data = $this->User->select_user("",array("u.user_id"=>$value->user_id));
      if($user_data->num_rows()==1){
        $user_data = $user_data->row();
        if($value->delete_status==1){
          echo "User Linked Employee Found as Deleted : ".$value->employee_id."<br/>";
        }else{
          // Update Employee A/C
          $employee_update_data['employee_id'] = $value->employee_id;
          $employee_update_data['employee_name'] = $user_data->user_alias;
          $employee_update_data['user_designation'] = $user_data->user_designation;
          $employee_update_data['phone_no'] = $user_data->phone_no;
          $employee_result = $this->Employee->update_employee($employee_update_data);
          echo "Employee Details Updated : ".$value->employee_id."<br/>";
        }
      }else{
        echo "User Details Not Found For Employee : ".$value->employee_id."<br/>";
      }
    }

    // Create Employee For Non Existing Users
    $user_data = $this->User->select_user("")->result();
    foreach ($user_data as $key => $value) {
      $employee_count = $this->db->select('*')->from('employees e')->where("user_id",$value->user_id)->get();
      if($employee_count->num_rows()==0){
        // Create Employee A/C
        $employee_data['user_id'] = $value->user_id;
        $employee_data['employee_name'] = $value->user_alias;
        $employee_data['user_designation'] = $value->user_designation;
        $employee_data['phone_no'] = $value->phone_no;
        $employee_data['basic_wage_type'] = 'Monthly';
        $employee_data['basic_wage_fixed'] = 1;
        $employee_data['created_by'] = 1;
        $employee_data['created_date'] = $value->created_date;
        $employee_result = $this->Employee->create_employee($employee_data);
        echo "Employee Created For User : ".$value->user_id."<br/>";
      }
    }

  }
  public function vehicle_consignee_create(){
    $vehicles = $this->db->select('*')->from('vehicles v')->where("consignee",0)->get()->result();
    foreach ($vehicles as $key => $value) {
      if($value->consignee_name!=''){
        // Create Consignee or Get ID of Existing
        $consignee_data['consignee_name'] = $consignee_where['consignee_name'] = $value->consignee_name;
        $count = $this->Vehicle->select_consignee("",$consignee_where);
        if($count->num_rows()==0) {
          $consignee_result = $this->Vehicle->create_consignee($consignee_data);
          $vehicle_update_data['consignee'] = $consignee_result['insert_id'];
        }else{
          $vehicle_update_data['consignee'] = $count->result()[0]->consignee_id;
        }
        $vehicle_update_data['id'] = $value->id;
        $this->Vehicle->update_vehicle($vehicle_update_data);
        echo "Vehicle Consignee Updated For :".$value->id."<br/>";
      }
    }
  }
  public function vehicle_drivers_to_employee(){
    $vehicle_drivers = $this->db->select("*")->from('vehicle_drivers vd')->where("moved_status",0)->get()->result();
    foreach ($vehicle_drivers as $key => $value) {
      // Create Employee A/C
      $employee_data['employee_name'] = $value->driver_name;
      $employee_data['address'] = $value->driver_place;
      $employee_data['user_designation'] = 'Driver';
      $employee_data['department'] = 1;
      $employee_data['phone_no'] = $value->driver_mobile;
      $employee_data['assigned_vehicles'] = $value->assigned_vehicles;
      $employee_data['created_by'] = $value->created_by;
      $employee_data['created_date'] = $value->created_date;
      $employee_result = $this->Employee->create_employee($employee_data);

      // Update in Work Slip
      $work_slips	= $this->Vehicle_work_slips->select_vehicle_work_slips("vws.work_slip_id",array("vws.driver_id"=>$value->driver_id))->result();
      foreach ($work_slips as $key2 => $value2) {
        $work_slips_update_data['work_slip_id'] = $value2->work_slip_id;
        $work_slips_update_data['driver_id'] =$employee_result['insert_id'];
        $this->Vehicle_work_slips->update_vehicle_work_slip($work_slips_update_data);
      }
      // Vehicle Allocation
      $allocations	= $this->Vehicle->select_vehicle_allocations("va.allocation_id",array("va.driver_id"=>$value->driver_id))->result();
      foreach ($allocations as $key3 => $value3) {
        $allocations_update_data['allocation_id'] = $value3->allocation_id;
        $allocations_update_data['driver_id'] =$employee_result['insert_id'];
        $this->Vehicle->update_vehicle_allocation($allocations_update_data);
      }

      // $driver_update_data['driver_id'] = $value->driver_id;
      // $driver_update_data['moved_status'] =1;
      // $this->Vehicle->update_driver($driver_update_data);
      echo "Driver: #".$value->driver_id." Moved.<br/>";
    }
  }
  public function user_acc_head_to_employee(){

    $this->db->select('u.*')->from('users u');
    $this->db->where('u.delete_status',0);
    $this->db->order_by('u.user_id','desc');
    $user_data = $this->db->get()->result();
    foreach ($user_data as $key => $value) {
      $this->db->select("*")->from('employees e');
      $this->db->where("e.delete_status",0);
      $this->db->where("e.user_id",$value->user_id);
      $employee_data = $this->db->get();
      if($employee_data->num_rows()==1){
        $employee_data = $employee_data->row();
        // Update Employee A/C

        // Get Account Heads
        $this->db->select('*')->from('account_heads ah');
        $this->db->where("ah.delete_status",0);
        $this->db->where("ah.acc_user_id",$value->user_id);
        $account_head_data = $this->db->get();
        if($account_head_data->num_rows()==1){
          // Update Account Head
          $account_data['acc_employee_id'] = $employee_data->employee_id;
          $account_data['acc_head_id'] = $account_head_data->row()->acc_head_id;
          $account_result = $this->Account->update_account_head($account_data);
        }else{
          echo "Account Head Data Not Found for User #".$value->user_id."<br/>";
        }
      }else{
        echo "Employee Data Not Found for User #".$value->user_id."<br/>";
      }

    }
  }
  public function create_employee_account_head(){
    $this->db->select("*")->from('employees e');
    $this->db->where("e.delete_status",0);
    $employee_data = $this->db->get()->result();
    foreach ($employee_data as $key => $value) {
      // Get Account Heads
      $this->db->select('*')->from('account_heads ah');
      $this->db->where("ah.delete_status",0);
      $this->db->where("ah.acc_employee_id",$value->employee_id);
      $account_head_count = $this->db->get()->num_rows();
      if($account_head_count==0){

        // CReate Account Head
        $account_data['acc_head_name'] = $value->employee_name."'s Account";
        $account_data['account_type'] = 32; //Cash Account
        $account_data['acc_employee_id'] = $value->employee_id;
        $account_data['head_editable'] = 0;
        $account_data['op_balance'] = 0;
        $account_data['created_date'] = date('Y-m-d H:i:s');
        $account_data['created_by'] = 1;
        $account_result = $this->Account->create_account_head($account_data);
      }
    }
  }
  public function update_user_acc_head(){
    $this->db->select('u.*')->from('users u');
    $this->db->where('u.delete_status',0);
    $this->db->order_by('u.user_id','desc');
    $user_data = $this->db->get()->result();
    foreach ($user_data as $key => $value) {
      $this->db->select("*")->from('employees e');
      $this->db->where("e.delete_status",0);
      $this->db->where("e.user_id",$value->user_id);
      $employee_data = $this->db->get();
      if($employee_data->num_rows()==1){
        $employee_data = $employee_data->row();
        // Update Employee A/C

        // Get Account Heads
        $this->db->select('*')->from('account_heads ah');
        $this->db->where("ah.delete_status",0);
        $this->db->where("ah.acc_user_id",$value->user_id);
        $account_head_data = $this->db->get();
        if($account_head_data->num_rows()==1){
          // Update Account Head
          $account_data['acc_employee_id'] = $employee_data->employee_id;
          $account_data['acc_head_id'] = $account_head_data->row()->acc_head_id;
          $account_data['acc_head_name'] = $value->user_alias."'s Account";
          $account_result = $this->Account->update_account_head($account_data);
        }else{
          echo "Account Head Data Not Found for User #".$value->user_id."<br/>";
        }
      }else{
        echo "Employee Data Not Found for User #".$value->user_id."<br/>";
      }

    }
  }
  public function move_user_leave_applications(){
    $this->db->select('*')->from('user_leave_applications ula');
    $result  = $this->db->get()->result();
    foreach ($result as $key => $value) {
      $employee_data	= $this->Employee->select_employee("e.*",array("e.user_id"=>$value->user_id));
      if ($employee_data->num_rows() == 1) {
        // Move to Leave Application
        $data2['employee_id'] = $employee_data->row()->employee_id;
        $data2['leave_type'] = 1;
        $data2['leave_date_from'] = $value->leave_date;
        $data2['leave_date_to'] = $value->leave_date;
        $data2['no_of_days'] = 1;
        $data2['leave_reason'] = $value->reason;
        $data2['created_by'] = $value->created_by;
        $data2['created_date'] = $value->created_date;
        $data2['approval_status_1'] = $value->approval_status;
        $data2['approved_by_1'] = $value->approved_by;
        $data2['approved_remarks_1'] = $value->approval_remarks;

        $result2 = $this->Employee->create_employee_leave_applications($data2);

        // Delete
        $this->db->where('application_id', $value->application_id);
        $query = $this->db->delete('user_leave_applications');
        echo "Moved #".$value->application_id."<br/>";
      }else{
        echo "User-Employee error #".$value->user_id."<br/>";
      }
    }
  }
  public function move_employee_attendance_to_site_visit(){
    $this->db->select('*')->from('employee_attendance');
    $result  = $this->db->get()->result();
    foreach ($result as $key => $value) {
      $site_visit['employee_id'] = $value->employee_id;
      $site_visit['project_id'] = $value->project_id;
      $site_visit['visit_date'] = $value->attendance_date;
      $site_visit['created_date'] = $value->created_date;
      $site_visit['created_by'] = $value->created_by;
      $result = $this->Employee->create_employee_site_vist($site_visit);

      $this->db->where('attendance_id', $value->attendance_id);
      $query = $this->db->delete('employee_attendance');
      echo "Moved #".$value->attendance_id."<br/>";
    }
  }
  public function supplier_account_head_fix(){
    $suppliers = $this->Supplier->select_supplier("*")->result();
    foreach ($suppliers as $key => $value) {
      $account_head_where['account_type'] = 12; //Direct Expense
      $account_head_where['acc_supplier_id'] = $value->supplier_id;
      $count = $this->Account->select_account_heads("", $account_head_where)->num_rows();
      if($count==0){
        // Create supplier Account Head
        $account_data['acc_head_name'] = $value->supplier_name . "'s Account";
        $account_data['account_type'] = 12; //Direct Expense
        $account_data['acc_supplier_id'] = $value->supplier_id;
        $account_data['head_editable'] = 0;
        $account_data['op_balance'] = 0;
        $account_data['created_date'] = date('Y-m-d H:i:s');
        $account_data['created_by'] = 1;

        $account_result = $this->Account->create_account_head($account_data);
      }
    }
  }
  public function project_budget_multiple(){
    if($this->config->item('Project_multiple_budget')==1){
      $data['project_budget_details'] = '';
      $projects	= $this->Work->select_work("*",$data)->result();
      foreach ($projects as $key => $value) {

        $budget_new = array();
        $i=0;
        $budget_new[$i]['section'] = '';
        $budget_new[$i]['amount'] = $value->est_budget_amt;
        $budget_new[$i]['tax_percent'] = $value->project_tax_percent;
        $budget_new[$i]['tax_amount'] = $value->project_tax_amount;
        $budget_new[$i]['total'] = $value->est_budget_amt+$value->project_tax_amount;

        $data2['project_budget_details'] = serialize($budget_new);
        $data2['work_id'] = $value->work_id;
        $data2['est_budget_amt'] = 0;
        $data2['project_tax_percent'] = 0;
        $data2['project_tax_amount'] = 0;
        $result2 = $this->Work->update_work($data2);
      }
    }
  }
  public function fix_salary_slips(){
    $salary_slips = $this->Salary_slips->select_salary_slips("ss.*")->result();
    foreach ($salary_slips as $key => $ss) {
      $this->bills_management->calculate_salary_slip_total($ss->salary_id);
    }
  }
  public function fix_invoice_suffix(){
    $invoices = $this->Invoices->select_invoices("i.*")->result();
    foreach ($invoices as $key => $value) {
      $fin_year = '';
      $invoice_update_data['invoice_id'] = $value->invoice_id;
      $invoice_date = $value->invoice_date;
      $invoice_month = date('m',strtotime($value->invoice_date));
      $invoice_year = date('Y',strtotime($value->invoice_date));
      if($invoice_month>=4){
        $fin_year_name = $invoice_year.'-'.($invoice_year+1);
        $fin_year_short = date('y',strtotime($invoice_year)).'-'.(date('y',strtotime($invoice_year))+1);
      }else{
        $fin_year_name = ($invoice_year-1).'-'.($invoice_year);
        $fin_year_short = (date('y',strtotime($invoice_year))-1).'-'.date('y',strtotime($invoice_year));
      }
      $fin_year_data = $this->Settings->select_finyear('',array("fin_year"=>$fin_year_name));
      if($fin_year_data->num_rows()==1){
        $invoice_update_data['finyear'] = $fin_year_data->row()->finyear_id;
        $fin_year = $fin_year_data->row()->fin_year;
      }elseif($fin_year_data->num_rows()==0){
        $fin_year = $insert_data['fin_year'] = $fin_year_name;
        $insert_data['fin_year_short'] = $fin_year_short;
        $insert_data['active_status'] = 0;
        $fin_year_insert_result = $this->Settings->insert_finyear($insert_data);
        $invoice_update_data['finyear'] = $fin_year_insert_result['insert_id'];
      }else{
        echo 'Duplication in Financial Year<br/>';
      }

      if($fin_year!=''){
        if($this->config->item('client_invoice_suffix')=='/d/m/Y'){
          $invoice_update_data['invoice_suffix'] = "/".date('d/m/Y',strtotime($value->invoice_date));
        }elseif($this->config->item('client_invoice_suffix')=='/fy'){
          $fin_year_array = explode("-",$fin_year);
          $fin_year_2 = $fin_year_array[0];
          $fin_year_2 = substr( $fin_year_2, -2);
          $invoice_update_data['invoice_suffix'] = "/".$fin_year_2;
        }elseif($this->config->item('client_invoice_suffix')=='/fy-y'){
          $fin_year_array = explode("-",$fin_year);
          $fin_year_2 = $fin_year_array[0];
          $fin_year_2 = substr( $fin_year_2, -2);
          $fin_year_3 = $fin_year_array[1];
          $fin_year_3 = substr( $fin_year_3, -2);
          $invoice_update_data['invoice_suffix'] = "/".$fin_year_2.'-'.$fin_year_3;
        }elseif($this->config->item('client_invoice_suffix')=='/y'){
          $invoice_update_data['invoice_suffix'] = "/".date('Y',strtotime($value->invoice_date));
        }
      }
      $result = $this->Invoices->update_invoice($invoice_update_data);
    }
  }
  public function purchase_request_status_update(){
    $requests = $this->Purchase_request->select_purchase_request("")->result();
    foreach ($requests as $key => $value) {
      $this->bills_management->update_purchase_request_closed_status($value->request_id);
    }
  }
  public function fix_purchase_bills(){
    $purchase_bill = $this->Purchases->select_purchase("*,p.created_by as purchase_created_by",'','all','','','all')->result();
    foreach ($purchase_bill as $key => $value) {
      $this->bills_management->calculate_purchase_bill_total($value->purchase_id);
      // $total_paid_amount = $this->Account->select_account_transaction("COALESCE(SUM(ats.tr_amount),0) as total_paid_amount", array("ats.reference_id" => $value->purchase_id, "ats.reference_type" => 'purchase_bill'),'purchase_bill','','','','','','all')->row()->total_paid_amount;
      // echo "Purchase #".$value->purchase_id." - Total Paid :".$total_paid_amount."<br/>";
    }
  }
  public function fix_bills(){
    $bills = $this->Bills->select_bills("b.*,ah1.acc_head_id,ah1.acc_head_name as credit_account,u.user_alias,wc.work_name,c.contractor_name,sc.contractor,sc.sub_work_name,sc.contract_id,v.id,v.vehicle_no,v.vehicle_name,vc.consignee_name as vehicle_consignee_name",'','','','','all','all')->result();
    foreach ($bills as $key => $value) {
      $this->bills_management->calculate_bill_total($value->bill_id);
    }
  }
  public function copy_clients_to_customer(){
    $client_where['customer_id'] = 0;
    $result	= $this->Client->select_client("",$client_where)->result();
    foreach ($result as $key => $value) {
      $data['customer_phone']=$customer_where['customer_phone']=$value->client_contact;
      $count = $this->Customers->select_customer("",$customer_where)->num_rows();
      if($count == 0) {
        $data['customer_name'] = $value->client_name;
        $data['contact_person'] = $value->contact_person;
        $data['customer_location'] = $value->client_address;
        $data['customer_email'] = $value->client_email;
        $data['customer_tax_no'] = $value->tax_no;
        if($this->input->post('state_id')){
          $data['customer_tax_state'] = $value->tax_state_id;
        }
        $data['created_date'] = date('Y-m-d H:i:s');
        $data['created_by'] = $this->session->userdata('user_id');
        $result2 = $this->Customers->create_customer($data);
        // Update Customer ID in Client
        $update_client_data['client_id'] = $value->client_id;
        $update_client_data['customer_id'] = $result2['insert_id'];
        $result3 = $this->Client->update_client($update_client_data);
      }
    }
  }
  public function expense_bill_items_fix(){

  }
  public function invoice_tax_to_items(){

  }
  public function move_project(){

  }
  public function stock_transfer_amount_update(){

  }
  public function create_stock_transfer_bills(){

  }
  public function test(){
    $amount = 0.57;
    echo $amount."-<br/>";
    echo $this->amount_in_words($amount);
  }
  
}
