<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Store_profile_model extends CI_Model {

	public function update_store(){

		//Filtering XSS and html escape from user inputs 
		extract($this->security->xss_clean(html_escape(array_merge($this->data,$_POST,$_GET))));
		 	//echo "<pre>";print_r($this->security->xss_clean(html_escape(array_merge($this->data,$_POST))));exit();

		//if not admin
		if(!is_admin()){
			if($q_id!=get_current_store_id()){
				echo "Something Went Wrong";exit();
			}
		}

		$this->db->trans_begin();
		
		$store_logo='';
		if(!empty($_FILES['store_logo']['name'])){
			$config['upload_path']          = './uploads/store/';
	        $config['allowed_types']        = 'gif|jpg|jpeg|png';
	        $config['max_size']             = 1000;
	        $config['max_width']            = 1000;
	        $config['max_height']           = 1000;

	        $this->load->library('upload', $config);

	        if ( ! $this->upload->do_upload('store_logo'))
	        {
	                $error = array('error' => $this->upload->display_errors());
	                return $error['error'];
	                exit();
	        }
	        else
	        {
	        	   $store_logo='uploads/store/'.$this->upload->data('file_name');
	        }
		}

		$signature='';
		if(!empty($_FILES['signature']['name'])){
			$config['upload_path']          = './uploads/signature/';
	        $config['allowed_types']        = 'gif|jpg|jpeg|png';
	        $config['max_size']             = 1000;
	        $config['max_width']            = 1000;
	        $config['max_height']           = 1000;

	        $this->load->library('upload', $config);

	        if ( ! $this->upload->do_upload('signature'))
	        {
	                $error = array('error' => $this->upload->display_errors());
	                return $error['error'];
	                exit();
	        }
	        else
	        {
	        	   $signature='uploads/signature/'.$this->upload->data('file_name');
	        }
		}


		$change_return = (isset($change_return)) ? 1 : 0;
		$mrp_column = (isset($mrp_column)) ? 1 : 0;
		$show_signature = (isset($show_signature)) ? 1 : 0;
		$previous_balance_bit = (isset($previous_balance_bit)) ? 1 : 0;
		$round_off = (isset($round_off)) ? 1 : 0;

		

		$data = array(
		    				'store_code'				=> $store_code,
		    				'store_name'				=> $store_name,
		    				'store_website'				=> $store_website,
		    				'mobile'					=> $mobile,
		    				'phone'						=> $phone,
		    				'email'						=> $email,
		    				'country'					=> $country,
		    				'state'						=> $state,
		    				'city'						=> $city,
		    				'address'					=> $address,
		    				'postcode'					=> $postcode,
		    				'bank_details'				=> $bank_details,
		    				'category_init'				=> $category_init,
		    				'item_init'					=> $item_init,
		    				'supplier_init'				=> $supplier_init,
		    				'purchase_init'				=> $purchase_init,
		    				'purchase_return_init'		=> $purchase_return_init,
		    				'customer_init'				=> $customer_init,
		    				'sales_init'				=> $sales_init,
		    				'sales_return_init'			=> $sales_return_init,
		    				'expense_init'				=> $expense_init,
		    				'quotation_init'			=> $quotation_init,
		    				'money_transfer_init'		=> $money_transfer_init,
		    				'accounts_init'				=> $accounts_init,
		    				'currency_id'				=> $currency,
		    				'currency_placement'		=> $currency_placement,
		    				'timezone'					=> $timezone,
		    				'date_format'				=> $date_format,
		    				'time_format'				=> $time_format,
		    				'sales_discount'			=> $sales_discount,
		    				'sales_discount'			=> $sales_discount,
		    				'change_return'				=> $change_return,
		    				'sales_invoice_format_id'	=> $sales_invoice_format_id,
		    				'pos_invoice_format_id'		=> $pos_invoice_format_id,
		    				'sales_invoice_footer_text'	=> $sales_invoice_footer_text,
		    				'invoice_terms'				=> $invoice_terms,
		    				'round_off'					=> $round_off,
		    				'language_id'				=> $language_id,
		    				'decimals'					=> $decimals,
		    				'qty_decimals'					=> $qty_decimals,
		    				'sales_payment_init'		=> $sales_payment_init,
		    				'sales_return_payment_init'	=> $sales_return_payment_init,
		    				'purchase_payment_init'		=> $purchase_payment_init,
		    				'purchase_return_payment_init'	=> $purchase_return_payment_init,
		    				'expense_payment_init'	=> $expense_payment_init,
		    				'cust_advance_init'	=> $cust_advance_init,
		    				'mrp_column'	=> $mrp_column,
		    				'show_signature'	=> $show_signature,
		    				'previous_balance_bit'	=> $previous_balance_bit,
		    				't_and_c_status'	=> $t_and_c_status,
		    				't_and_c_status_pos'	=> $t_and_c_status_pos,
		    				'number_to_words'	=> $number_to_words,
		    				'default_account_id'	=> (isset($default_account_id) && !empty($default_account_id))?$default_account_id:null,
		    			);

		if(!empty($store_logo)){
			$data['store_logo']=$store_logo;
		}
		if(!empty($signature)){
			$data['signature']=$signature;
		}
		/*custom helper*/
		if(gst_number()){
			$data['gst_no']=$gst_no;
		}
		if(vat_number()){
			$data['vat_no']=$vat_no;
		}
		if(pan_number()){
			$data['pan_no']=$pan_no;
		}
		/*end*/

		
			$store_code_count=$this->db->query("select count(*) as store_code_count from db_store where upper(store_code)=upper('$store_code') and id<>$q_id")->row()->store_code_count;
			if($store_code_count>0){
				echo "Sorry! Store Code Already Exist!\nPlease Change Store Code";exit();
			}

			$q1 = $this->db->where('id',$q_id)->update('db_store', $data);
			if($q1){
				$this->db->trans_commit();
				$this->session->unset_userdata('currency');
				//$this->session->set_flashdata('success', 'Success!! Record Updated Successfully! ');
				echo "success";
			}

		

		exit();
	}

	//Get store_details
	public function get_details($id){
		$data=$this->data;

		$query1=$this->db->query("select * from db_store where upper(id)=upper('$id')");
		if($query1->num_rows()==0){
			show_404();exit;
		}
		else{
			/* QUERY 1*/
			$data['q_id']=$query1->row()->id;
			return array_merge($data,$query1->row_array());
			return $data;
		}
	}

	//Delete data based on type
	public function delete_data($data_type, $store_id){
		
		$this->db->trans_begin();
		
		try {
			switch($data_type) {
				case 'sales':
					// Delete sales and related data
					$this->db->where('store_id', $store_id)->delete('db_salespayments');
					$this->db->where('store_id', $store_id)->delete('db_salesitems');
					$this->db->where('store_id', $store_id)->delete('db_sales');
					break;
					
				case 'sales_return':
					// Delete sales returns and related data
					$this->db->where('store_id', $store_id)->delete('db_salespaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_salesitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_salesreturn');
					break;
					
				case 'purchase':
					// Delete purchases and related data
					$this->db->where('store_id', $store_id)->delete('db_purchasepayments');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitems');
					$this->db->where('store_id', $store_id)->delete('db_purchase');
					break;
					
				case 'purchase_return':
					// Delete purchase returns and related data
					$this->db->where('store_id', $store_id)->delete('db_purchasepaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchasereturn');
					break;
					
				case 'expense':
					// Delete expenses
					$this->db->where('store_id', $store_id)->delete('db_expense');
					break;
					
				case 'quotations':
					// Delete quotations and related data
					$this->db->where('store_id', $store_id)->delete('db_quotationitems');
					$this->db->where('store_id', $store_id)->delete('db_quotation');
					break;
					
				case 'customers':
					// Delete customers and related data
					$this->db->where('store_id', $store_id)->delete('db_customer_coupons');
					$this->db->where('store_id', $store_id)->delete('db_customer_payments');
					$this->db->where('store_id', $store_id)->delete('db_custadvance');
					$this->db->where('store_id', $store_id)->delete('db_customers');
					break;
					
				case 'customers_advance':
					// Delete customer advance payments only
					$this->db->where('store_id', $store_id)->delete('db_custadvance');
					break;
					
				case 'coupons':
					// Delete coupons and customer coupons
					$this->db->where('store_id', $store_id)->delete('db_customer_coupons');
					$this->db->where('store_id', $store_id)->delete('db_coupons');
					break;
					
				case 'payments':
					// Delete all payment records
					$this->db->where('store_id', $store_id)->delete('db_salespayments');
					$this->db->where('store_id', $store_id)->delete('db_salespaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchasepayments');
					$this->db->where('store_id', $store_id)->delete('db_purchasepaymentsreturn');
					// Check if these tables exist
					if ($this->db->table_exists('db_cash_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_cash_transactions');
					}
					if ($this->db->table_exists('db_account_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_account_transactions');
					}
					break;
					
				case 'customer_payments':
					// Delete customer payments only
					$this->db->where('store_id', $store_id)->delete('db_customer_payments');
					break;
					
				case 'items':
					// Delete items (WARNING: This affects all transactions)
					$this->db->where('store_id', $store_id)->delete('db_items');
					break;
					
				case 'suppliers':
					// Delete suppliers
					$this->db->where('store_id', $store_id)->delete('db_suppliers');
					break;
					
				case 'categories_brands':
					// Delete categories and brands
					$this->db->where('store_id', $store_id)->delete('db_category');
					$this->db->where('store_id', $store_id)->delete('db_brands');
					break;
					
				case 'stock_adjustments':
					// Delete stock adjustments and transfers
					$this->db->where('store_id', $store_id)->delete('db_stockadjustmentitems');
					$this->db->where('store_id', $store_id)->delete('db_stockadjustment');
					$this->db->where('store_id', $store_id)->delete('db_stocktransferitems');
					$this->db->where('store_id', $store_id)->delete('db_stocktransfer');
					if ($this->db->table_exists('db_stockentry')) {
						$this->db->where('store_id', $store_id)->delete('db_stockentry');
					}
					break;
					
				case 'all_transactions':
					// Delete all sales, purchases, expenses and payments
					$this->db->where('store_id', $store_id)->delete('db_salespayments');
					$this->db->where('store_id', $store_id)->delete('db_salespaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_salesitems');
					$this->db->where('store_id', $store_id)->delete('db_salesitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_sales');
					$this->db->where('store_id', $store_id)->delete('db_salesreturn');
					
					$this->db->where('store_id', $store_id)->delete('db_purchasepayments');
					$this->db->where('store_id', $store_id)->delete('db_purchasepaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitems');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchase');
					$this->db->where('store_id', $store_id)->delete('db_purchasereturn');
					
					$this->db->where('store_id', $store_id)->delete('db_expense');
					
					// Check if these tables exist
					if ($this->db->table_exists('db_cash_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_cash_transactions');
					}
					if ($this->db->table_exists('db_account_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_account_transactions');
					}
					break;
					
				case 'all_data':
					// Delete all business data except users and store settings
					$this->db->where('store_id', $store_id)->delete('db_salespayments');
					$this->db->where('store_id', $store_id)->delete('db_salespaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_salesitems');
					$this->db->where('store_id', $store_id)->delete('db_salesitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_sales');
					$this->db->where('store_id', $store_id)->delete('db_salesreturn');
					
					$this->db->where('store_id', $store_id)->delete('db_purchasepayments');
					$this->db->where('store_id', $store_id)->delete('db_purchasepaymentsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitems');
					$this->db->where('store_id', $store_id)->delete('db_purchaseitemsreturn');
					$this->db->where('store_id', $store_id)->delete('db_purchase');
					$this->db->where('store_id', $store_id)->delete('db_purchasereturn');
					
					$this->db->where('store_id', $store_id)->delete('db_expense');
					
					$this->db->where('store_id', $store_id)->delete('db_customer_coupons');
					$this->db->where('store_id', $store_id)->delete('db_customer_payments');
					$this->db->where('store_id', $store_id)->delete('db_custadvance');
					$this->db->where('store_id', $store_id)->delete('db_customers');
					
					$this->db->where('store_id', $store_id)->delete('db_coupons');
					
					// Items and inventory
					$this->db->where('store_id', $store_id)->delete('db_items');
					$this->db->where('store_id', $store_id)->delete('db_suppliers');
					$this->db->where('store_id', $store_id)->delete('db_category');
					$this->db->where('store_id', $store_id)->delete('db_brands');
					
					// Stock adjustments
					$this->db->where('store_id', $store_id)->delete('db_stockadjustmentitems');
					$this->db->where('store_id', $store_id)->delete('db_stockadjustment');
					$this->db->where('store_id', $store_id)->delete('db_stocktransferitems');
					$this->db->where('store_id', $store_id)->delete('db_stocktransfer');
					
					// Check if these tables exist
					if ($this->db->table_exists('db_cash_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_cash_transactions');
					}
					if ($this->db->table_exists('db_account_transactions')) {
						$this->db->where('store_id', $store_id)->delete('db_account_transactions');
					}
					if ($this->db->table_exists('db_quotation')) {
						$this->db->where('store_id', $store_id)->delete('db_quotationitems');
						$this->db->where('store_id', $store_id)->delete('db_quotation');
					}
					if ($this->db->table_exists('db_hold')) {
						$this->db->where('store_id', $store_id)->delete('db_holditems');
						$this->db->where('store_id', $store_id)->delete('db_hold');
					}
					if ($this->db->table_exists('db_stockentry')) {
						$this->db->where('store_id', $store_id)->delete('db_stockentry');
					}
					break;
					
				default:
					return "Invalid data type";
					break;
			}
			
			if ($this->db->trans_status() === FALSE) {
				$this->db->trans_rollback();
				return "Error occurred while deleting data";
			} else {
				$this->db->trans_commit();
				return "success";
			}
			
		} catch (Exception $e) {
			$this->db->trans_rollback();
			return "Error: " . $e->getMessage();
		}
	}
	
	//Get count of records for confirmation
	public function get_data_count($data_type, $store_id){
		
		$count = 0;
		
		switch($data_type) {
			case 'sales':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_sales');
				break;
			case 'sales_return':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_salesreturn');
				break;
			case 'purchase':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_purchase');
				break;
			case 'purchase_return':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_purchasereturn');
				break;
			case 'expense':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_expense');
				break;
			case 'quotations':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_quotation');
				break;
			case 'customers':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_customers');
				break;
			case 'customers_advance':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_custadvance');
				break;
			case 'coupons':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_coupons');
				break;
			case 'items':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_items');
				break;
			case 'suppliers':
				$count = $this->db->where('store_id', $store_id)->count_all_results('db_suppliers');
				break;
			default:
				$count = 0;
				break;
		}
		
		return $count;
	}

}
