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

class Accounts extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('accounts_model','accounts');
	}
	public function index()
	{
		$this->permission_check('accounts_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('accounts_list');
		$this->load->view('accounts/accounts_list',$data);
	}

	public function set_default_account()
	{
		$this->permission_check('accounts_edit');
		
		$account_id = $this->input->post('account_id');
		$store_id = get_current_store_id();
		
		$response = array(
			'success' => false,
			'message' => ''
		);
		
		if (empty($account_id)) {
			$response['message'] = 'Account ID is required.';
			echo json_encode($response);
			return;
		}
		
		// Debug: Log the account_id and store_id
		log_message('debug', 'Setting default account - Account ID: ' . $account_id . ', Store ID: ' . $store_id);
		
		// Verify the account exists and belongs to current store
		$this->db->select('id, account_name, currency_id, store_id, status, delete_bit');
		$this->db->where('id', $account_id);
		$this->db->where('(delete_bit = 0 OR delete_bit = 1)'); // Include both regular and cash accounts
		$account = $this->db->get('ac_accounts')->row();
		
		// Debug: Log account details
		if ($account) {
			log_message('debug', 'Account found - ID: ' . $account->id . ', Name: ' . $account->account_name . ', Store ID: ' . $account->store_id);
		} else {
			log_message('debug', 'Account not found for ID: ' . $account_id);
		}
		
		if (!$account) {
			$response['message'] = 'Account not found.';
			echo json_encode($response);
			return;
		}
		
		// Check if account is active
		if ($account->status != 1) {
			$response['message'] = 'Account is not active.';
			echo json_encode($response);
			return;
		}
		
		// Check if account belongs to current store (for multi-store setups)
		if ($account->store_id != $store_id) {
			$response['message'] = 'Account does not belong to current store.';
			echo json_encode($response);
			return;
		}
		
		// Update the store's default account
		$this->db->where('id', $store_id);
		$update_result = $this->db->update('db_store', array('default_account_id' => $account_id));
		
		if ($update_result) {
			// Also set in session for immediate use
			$this->session->set_userdata('default_account_id', $account_id);
			
			$response['success'] = true;
			$response['message'] = 'Default account set to: ' . $account->account_name;
		} else {
			$response['message'] = 'Failed to update default account.';
		}
		
		echo json_encode($response);
	}

	public function book($account_id)
	{
		$this->belong_to('ac_accounts',$account_id);
		$this->permission_check('accounts_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('account_book');
		$data['account_id']=$account_id;
		$this->load->view('accounts/account_book',$data);
	}
	
	public function statement($account_id)
	{
		$this->belong_to('ac_accounts',$account_id);
		$this->permission_check('accounts_view');
		
		// Get account details
		$account = $this->db->select('a.*, c.currency_name, c.currency_code, c.symbol')
			->from('ac_accounts a')
			->join('db_currency c', 'a.currency_id = c.id', 'left')
			->where('a.id', $account_id)
			->get()->row();
			
		if (!$account) {
			show_error('Account not found', 404);
			return;
		}
		
		// Get date range
		$from_date = $this->input->get('from_date') ?: date('Y-m-01'); // First day of current month
		$to_date = $this->input->get('to_date') ?: date('Y-m-d'); // Today
		
		// Get transactions with currency conversion details
		$this->db->select('a.*, c.currency_name as transaction_currency_name, c.currency_code as transaction_currency_code, c.symbol as transaction_symbol');
		$this->db->from('ac_transactions a');
		$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
		$this->db->where('a.store_id', get_current_store_id());
		$this->db->where("(a.credit_account_id=$account_id or a.debit_account_id=$account_id)");
		$this->db->where('a.transaction_date >=', $from_date);
		$this->db->where('a.transaction_date <=', $to_date);
		$this->db->order_by('a.transaction_date', 'ASC');
		$transactions = $this->db->get()->result();
		
		// Recalculate account balance to ensure it's up to date
		update_account_balance($account_id);
		
		// Refresh account data after balance update
		$account = $this->db->select('a.*, c.currency_name, c.currency_code, c.symbol')
			->from('ac_accounts a')
			->join('db_currency c', 'a.currency_id = c.id', 'left')
			->where('a.id', $account_id)
			->get()->row();
		
		// Calculate opening balance
		$opening_balance = 0;
		$credit_amt = $this->db->select("coalesce(sum(credit_amt),0) as credit_amt")
			->where("credit_account_id", $account_id)
			->where("transaction_date <", $from_date)
			->get("ac_transactions a")->row()->credit_amt;
		$debit_amt = $this->db->select("coalesce(sum(debit_amt),0) as debit_amt")
			->where("debit_account_id", $account_id)
			->where("transaction_date <", $from_date)
			->get("ac_transactions a")->row()->debit_amt;
		$opening_balance = $credit_amt - $debit_amt;
		
		// Get store details
		$store_details = get_store_details();
		
		// Prepare data for statement
		$data = array(
			'account' => $account,
			'from_date' => $from_date,
			'to_date' => $to_date,
			'transactions' => $transactions,
			'opening_balance' => $opening_balance,
			'store_details' => $store_details,
			'base_url' => base_url()
		);
		
		$this->load->view('accounts/account_statement', $data);
	}
	public function cash_transactions()
	{
		$this->permission_check('accounts_view');
		$data=$this->data;
		$data['page_title']=$this->lang->line('cash_transactions');
		$this->load->view('accounts/cash_transactions',$data);
	}

	public function add()
	{
		$this->permission_check('accounts_add');
		$data=$this->data;
		$data['page_title']=$this->lang->line('add_account');
		$this->load->view('accounts/accounts',$data);
	}
	
	
	public function newaccounts(){
		$this->permission_check('accounts_add');
		$this->form_validation->set_rules('account_code', 'Account Code', 'trim|required');
		$this->form_validation->set_rules('account_name', 'Account Name', 'trim|required');
		$this->form_validation->set_rules('currency_id', 'Currency', 'trim|required');
		$this->form_validation->set_rules('opening_balance', 'Opening Balance', 'trim|required');
		
		// Log the form data for debugging
		log_message('debug', 'Account creation attempt - POST data: ' . json_encode($_POST));
		
		if ($this->form_validation->run() == TRUE) {
			// Add timeout and error handling
			set_time_limit(30); // 30 second timeout
			try {
				$result=$this->accounts->verify_and_save();
				log_message('debug', 'Account creation result: ' . $result);
				echo $result;
			} catch (Exception $e) {
				log_message('error', 'Account creation exception: ' . $e->getMessage());
				log_message('error', 'Account creation stack trace: ' . $e->getTraceAsString());
				echo "Error: " . $e->getMessage();
			}
		} else {
			$errors = validation_errors();
			log_message('debug', 'Validation errors: ' . $errors);
			echo "Validation Error: " . $errors;
		}
	}
	public function multi_currency_report()
	{
		$this->permission_check('accounts_view');
		$data=$this->data;
		$data['page_title']='Multi-Currency Accounts Report';
		$this->load->view('accounts/multi_currency_report',$data);
	}
	
	public function get_accounts_by_currency()
	{
		$currency_id = $this->input->post('currency_id');
		
		if (empty($currency_id)) {
			echo json_encode(array('success' => false, 'message' => 'Currency ID is required'));
			return;
		}
		
		$this->db->select('a.account_name, a.account_code, a.balance, c.currency_code, c.symbol');
		$this->db->from('ac_accounts a');
		$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
		$this->db->where('a.currency_id', $currency_id);
		$this->db->where('a.store_id', get_current_store_id());
		$this->db->where('(a.delete_bit = 0 OR a.delete_bit = 1)');
		$this->db->order_by('a.account_name', 'ASC');
		$query = $this->db->get();
		
		$accounts = $query->result();
		
		echo json_encode(array(
			'success' => true,
			'accounts' => $accounts,
			'count' => count($accounts)
		));
	}
	
	public function currency_summary()
	{
		$this->permission_check('accounts_view');
		$data = $this->data;
		$data['page_title'] = 'Multi-Currency Accounts Summary';
		$this->load->view('accounts/currency_summary', $data);
	}
	
	public function get_currency_summary()
	{
		// Only show currencies that are actually being used by accounts
		$this->db->select('c.id, c.currency_name, c.currency_code, c.symbol, 
			COUNT(a.id) as account_count,
			COALESCE(SUM(a.balance), 0) as total_balance,
			COALESCE(SUM(a.base_currency_balance), 0) as total_base_balance');
		$this->db->from('db_currency c');
		$this->db->join('ac_accounts a', 'c.id = a.currency_id AND a.store_id = ' . get_current_store_id() . ' AND (a.delete_bit = 0 OR a.delete_bit = 1)', 'inner');
		$this->db->group_by('c.id, c.currency_name, c.currency_code, c.symbol');
		$this->db->having('COUNT(a.id) > 0'); // Only currencies with accounts
		$this->db->order_by('c.is_base_currency DESC, c.currency_name ASC');
		$query = $this->db->get();
		
		$currencies = $query->result();
		
		echo json_encode(array(
			'success' => true,
			'currencies' => $currencies
		));
	}
	
	public function recalculate_balances()
	{
		$this->permission_check('accounts_edit');
		
		// Recalculate all account balances
		$result = recalculate_all_account_balances();
		
		echo json_encode(array(
			'success' => true,
			'message' => 'Account balances recalculated successfully',
			'updated' => $result['updated'],
			'errors' => $result['errors'],
			'total' => $result['total']
		));
	}
	
	public function update_exchange_rate()
	{
		$this->permission_check('accounts_edit');
		
		$from_currency_id = $this->input->post('from_currency_id');
		$to_currency_id = $this->input->post('to_currency_id');
		$exchange_rate = $this->input->post('exchange_rate');
		$effective_date = $this->input->post('effective_date') ?: date('Y-m-d');
		
		if (empty($from_currency_id) || empty($to_currency_id) || empty($exchange_rate)) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Missing required parameters: from_currency_id, to_currency_id, exchange_rate'
			));
			return;
		}
		
		// Validate currencies exist
		$from_currency = $this->db->select('id, currency_code')->where('id', $from_currency_id)->get('db_currency')->row();
		$to_currency = $this->db->select('id, currency_code')->where('id', $to_currency_id)->get('db_currency')->row();
		
		if (!$from_currency || !$to_currency) {
			echo json_encode(array(
				'success' => false,
				'message' => 'Invalid currency IDs provided'
			));
			return;
		}
		
		$this->db->trans_begin();
		
		try {
			// Check if rate already exists
			$this->db->where('from_currency_id', $from_currency_id);
			$this->db->where('to_currency_id', $to_currency_id);
			$existing_rate = $this->db->get('db_exchange_rates')->row();
			
			if ($existing_rate) {
				// Update existing rate
				$this->db->where('id', $existing_rate->id);
				$this->db->update('db_exchange_rates', array(
					'exchange_rate' => $exchange_rate,
					'effective_date' => $effective_date,
					'status' => 1,
					'rate_type' => 'manual'
				));
			} else {
				// Insert new rate
				$this->db->insert('db_exchange_rates', array(
					'from_currency_id' => $from_currency_id,
					'to_currency_id' => $to_currency_id,
					'exchange_rate' => $exchange_rate,
					'effective_date' => $effective_date,
					'status' => 1,
					'rate_type' => 'manual'
				));
			}
			
			$this->db->trans_commit();
			
			echo json_encode(array(
				'success' => true,
				'message' => 'Exchange rate updated successfully',
				'from_currency' => $from_currency->currency_code,
				'to_currency' => $to_currency->currency_code,
				'exchange_rate' => $exchange_rate
			));
			
		} catch (Exception $e) {
			$this->db->trans_rollback();
			echo json_encode(array(
				'success' => false,
				'message' => 'Error updating exchange rate: ' . $e->getMessage()
			));
		}
	}
	
	public function get_exchange_rates()
	{
		$this->permission_check('accounts_view');
		
		$rates = $this->db->select('er.*, fc.currency_code as from_code, fc.currency_name as from_name, 
									tc.currency_code as to_code, tc.currency_name as to_name')
						  ->from('db_exchange_rates er')
						  ->join('db_currency fc', 'er.from_currency_id = fc.id')
						  ->join('db_currency tc', 'er.to_currency_id = tc.id')
						  ->where('er.status', 1)
						  ->order_by('er.effective_date DESC, fc.currency_code, tc.currency_code')
						  ->get()->result();
		
		echo json_encode(array(
			'success' => true,
			'rates' => $rates
		));
	}
	
	public function system_maintenance()
	{
		$this->permission_check('accounts_edit');
		$data = $this->data;
		$data['page_title'] = 'System Maintenance';
		
		// Get all currencies for the form
		$data['currencies'] = $this->db->select('id, currency_name, currency_code, symbol')
									  ->where('status', 1)
									  ->order_by('currency_name')
									  ->get('db_currency')->result();
		
		$this->load->view('accounts/system_maintenance', $data);
	}
	
	public function get_account_currency()
	{
		$account_id = $this->input->post('account_id');
		
		if (empty($account_id)) {
			echo json_encode(array('success' => false, 'message' => 'Account ID is required'));
			return;
		}
		
		$this->db->select('a.currency_id, a.balance, c.currency_name, c.currency_code, c.symbol');
		$this->db->from('ac_accounts a');
		$this->db->join('db_currency c', 'a.currency_id = c.id', 'left');
		$this->db->where('a.id', $account_id);
		$this->db->where('a.store_id', get_current_store_id());
		$this->db->where('a.delete_bit', 0);
		$query = $this->db->get();
		
		if ($query->num_rows() > 0) {
			$account = $query->row();
			echo json_encode(array(
				'success' => true,
				'currency_id' => $account->currency_id,
				'currency_name' => $account->currency_name,
				'currency_code' => $account->currency_code,
				'currency_symbol' => $account->symbol,
				'balance' => $account->balance
			));
		} else {
			// Fallback to base currency if account not found
			$base_currency = get_base_currency();
			echo json_encode(array(
				'success' => true,
				'currency_id' => $base_currency->id,
				'currency_name' => $base_currency->currency_name,
				'currency_code' => $base_currency->currency_code,
				'currency_symbol' => $base_currency->symbol,
				'balance' => 0
			));
		}
	}
	
	public function get_transfer_summary()
	{
		$from_account_id = $this->input->post('from_account_id');
		$to_account_id = $this->input->post('to_account_id');
		$amount = $this->input->post('amount');
		$currency_id = $this->input->post('currency_id');
		
		if (empty($from_account_id) || empty($to_account_id) || empty($amount) || empty($currency_id)) {
			echo json_encode(array('success' => false, 'message' => 'All parameters are required'));
			return;
		}
		
		// Get from account details
		$this->db->select('a.account_name as from_account_name, a.currency_id as from_currency_id, a.balance as from_balance, 
			c1.currency_name as from_currency_name, c1.currency_code as from_currency_code, c1.symbol as from_symbol');
		$this->db->from('ac_accounts a');
		$this->db->join('db_currency c1', 'a.currency_id = c1.id', 'left');
		$this->db->where('a.id', $from_account_id);
		$this->db->where('a.store_id', get_current_store_id());
		$from_account = $this->db->get()->row();
		
		// Get to account details
		$this->db->select('a.account_name as to_account_name, a.currency_id as to_currency_id, a.balance as to_balance,
			c2.currency_name as to_currency_name, c2.currency_code as to_currency_code, c2.symbol as to_symbol');
		$this->db->from('ac_accounts a');
		$this->db->join('db_currency c2', 'a.currency_id = c2.id', 'left');
		$this->db->where('a.id', $to_account_id);
		$this->db->where('a.store_id', get_current_store_id());
		$to_account = $this->db->get()->row();
		
		// Get transfer currency details
		$this->db->select('currency_name, currency_code, symbol');
		$this->db->from('db_currency');
		$this->db->where('id', $currency_id);
		$transfer_currency = $this->db->get()->row();
		
		// Calculate received amount and new balances
		$received_amount = $amount;
		$new_from_balance = $from_account->from_balance;
		$new_to_balance = $to_account->to_balance;
		
		// If transferring in different currency, calculate conversion
		$conversion_info = '';
		
		// Calculate amount to deduct from from_account
		if ($from_account->from_currency_id != $currency_id) {
			$exchange_rate = get_exchange_rate($currency_id, $from_account->from_currency_id);
			if ($exchange_rate === false) {
				$conversion_info .= '<p class="text-danger"><strong>From Account Conversion:</strong> No exchange rate available for ' . $from_account->from_currency_code . '</p>';
				$new_from_balance = $from_account->from_balance; // Don't change balance if no rate
			} else {
				$converted_amount = $amount * $exchange_rate;
				$new_from_balance = $from_account->from_balance - $converted_amount;
				$conversion_info .= '<p><strong>From Account Conversion:</strong> ' . $from_account->from_symbol . ' ' . number_format($converted_amount, 2) . ' (Rate: ' . number_format($exchange_rate, 4) . ')</p>';
			}
		} else {
			$new_from_balance = $from_account->from_balance - $amount;
		}
		
		// Calculate amount to add to to_account
		if ($to_account->to_currency_id != $currency_id) {
			$exchange_rate = get_exchange_rate($currency_id, $to_account->to_currency_id);
			if ($exchange_rate === false) {
				$conversion_info .= '<p class="text-danger"><strong>To Account Conversion:</strong> No exchange rate available for ' . $to_account->to_currency_code . '</p>';
				$new_to_balance = $to_account->to_balance; // Don't change balance if no rate
			} else {
				$converted_received = $amount * $exchange_rate;
				$new_to_balance = $to_account->to_balance + $converted_received;
				$conversion_info .= '<p><strong>To Account Conversion:</strong> ' . $to_account->to_symbol . ' ' . number_format($converted_received, 2) . ' (Rate: ' . number_format($exchange_rate, 4) . ')</p>';
			}
		} else {
			$new_to_balance = $to_account->to_balance + $amount;
		}
		
		$summary_html = '
		<div class="row">
			<div class="col-md-6">
				<div class="panel panel-danger">
					<div class="panel-heading">
						<h4 class="panel-title"><i class="fa fa-arrow-up"></i> From Account</h4>
					</div>
					<div class="panel-body">
						<p><strong>' . $from_account->from_account_name . '</strong></p>
						<p>Current Balance: ' . $from_account->from_symbol . ' ' . number_format($from_account->from_balance, 2) . '</p>
						<p>Transfer Amount: ' . $transfer_currency->symbol . ' ' . number_format($amount, 2) . ' ' . $conversion_info . '</p>
						<p class="text-danger"><strong>New Balance: ' . $from_account->from_symbol . ' ' . number_format($new_from_balance, 2) . '</strong></p>
					</div>
				</div>
			</div>
			<div class="col-md-6">
				<div class="panel panel-success">
					<div class="panel-heading">
						<h4 class="panel-title"><i class="fa fa-arrow-down"></i> To Account</h4>
					</div>
					<div class="panel-body">
						<p><strong>' . $to_account->to_account_name . '</strong></p>
						<p>Current Balance: ' . $to_account->to_symbol . ' ' . number_format($to_account->to_balance, 2) . '</p>
						<p>Amount Received: ' . $transfer_currency->symbol . ' ' . number_format($received_amount, 2) . '</p>
						<p class="text-success"><strong>New Balance: ' . $to_account->to_symbol . ' ' . number_format($new_to_balance, 2) . '</strong></p>
					</div>
				</div>
			</div>
		</div>';
		
		echo json_encode(array(
			'success' => true,
			'summary_html' => $summary_html
		));
	}
	
	public function get_to_account_calculation()
	{
		$to_account_id = $this->input->post('to_account_id');
		$amount = $this->input->post('amount');
		$currency_id = $this->input->post('currency_id');
		
		if (empty($to_account_id) || empty($amount) || empty($currency_id)) {
			echo json_encode(array('success' => false, 'message' => 'All parameters are required'));
			return;
		}
		
		// Get to account details
		$to_account = $this->db->select('a.account_name, a.currency_id as to_currency_id, a.balance as to_current_balance,
			c.currency_name as to_currency_name, c.currency_code as to_currency_code, c.symbol as to_currency_symbol')
			->from('ac_accounts a')
			->join('db_currency c', 'a.currency_id = c.id', 'left')
			->where('a.id', $to_account_id)
			->where('a.store_id', get_current_store_id())
			->get()->row();
		
		// Get transfer currency details
		$transfer_currency = $this->db->select('currency_name, currency_code, symbol')
			->from('db_currency')
			->where('id', $currency_id)
			->get()->row();
		
		// Calculate amount to add to to_account
		$to_add_amount = $amount;
		$will_receive_display = $transfer_currency->symbol . ' ' . number_format($amount, 2);
		
		if ($to_account->to_currency_id != $currency_id) {
			$exchange_rate = get_exchange_rate($currency_id, $to_account->to_currency_id);
			if ($exchange_rate === false) {
				$will_receive_display = $transfer_currency->symbol . ' ' . number_format($amount, 2) . 
					' <small class="text-danger">(No exchange rate available)</small>';
				$to_add_amount = 0; // Don't add anything if no rate
			} else {
				$to_add_amount = $amount * $exchange_rate;
				$will_receive_display = $transfer_currency->symbol . ' ' . number_format($amount, 2) . 
					' <small class="text-muted">(=' . $to_account->to_currency_symbol . ' ' . number_format($to_add_amount, 2) . ')</small>';
			}
		}
		
		$new_balance = $to_account->to_current_balance + $to_add_amount;
		$new_balance_display = $to_account->to_currency_symbol . ' ' . number_format($new_balance, 2);
		
		echo json_encode(array(
			'success' => true,
			'will_receive_display' => $will_receive_display,
			'new_balance_display' => $new_balance_display
		));
	}

	public function update($id){
		$this->permission_check('accounts_edit');
		$this->belong_to('ac_accounts',$id);
		$data=$this->data;
		$result=$this->accounts->get_details($id,$data);
		$data=array_merge($data,$result);
		$data['page_title']=$this->lang->line('accounts');
		$this->load->view('accounts/accounts', $data);
	}
	public function update_accounts(){
		$this->form_validation->set_rules('account_code', 'Account Code', 'trim|required');
		$this->form_validation->set_rules('account_name', 'Account Name', 'trim|required');
		//$this->form_validation->set_rules('opening_balance', 'Oprning Balance', 'trim|required');

		if ($this->form_validation->run() == TRUE) {
			// Add timeout and error handling
			set_time_limit(30); // 30 second timeout
			try {
				$result=$this->accounts->update_accounts();
				echo $result;
			} catch (Exception $e) {
				log_message('error', 'Account update error: ' . $e->getMessage());
				echo "An error occurred while updating. Please try again.";
			}
		} else {
			echo "Please Fill Compulsory(* marked) Fields.";
		}
	}

	public function ajax_list()
	{
		$list = $this->accounts->get_datatables();
		
		// Debug: Log the count of results
		log_message('debug', 'Accounts ajax_list - Count: ' . count($list));
		
		$data = array();
		$no = $_POST['start'];
		foreach ($list as $accounts) {
			$no++;
			$row = array();
			$row[] = ($accounts->delete_bit) ? '<span data-toggle="tooltip" title="Resticted" class="text-danger fa fa-fw fa-ban"></span>' : '<input type="checkbox" name="checkbox[]" value='.$accounts->id.' class="checkbox column_checkbox" >';
			//$row[] = get_store_name($accounts->store_id);
			$row[] = $accounts->account_code;
			
			// Get currency information and format account name
			$currency_display = 'Base Currency';
			$account_name_display = $accounts->account_name;
			
			if (!empty($accounts->currency_id) && !empty($accounts->currency_name)) {
				$currency_display = $accounts->currency_name . ' (' . $accounts->currency_code . ')';
				// Format account name to include currency
				$account_name_display = $accounts->account_name . ' (' . $accounts->currency_code . ')';
			}
			$row[] = $account_name_display;
			$row[] = get_account_name($accounts->parent_id);
			$row[] = $currency_display;
			
			// Display balance in account's currency with system currency in parentheses
			$account_balance = $accounts->balance;
			$account_currency_id = $accounts->currency_id ?: get_base_currency()->id;
			
			$balance_display = format_currency_with_system($account_balance, $account_currency_id);
			
			$row[] = $balance_display;
			
			$row[] = get_user_name($accounts->created_by);
			
			// Check if this is the default account
			$default_account_id = get_store_details()->default_account_id;
			$is_default = ($accounts->id == $default_account_id) ? true : false;
			
			if ($is_default) {
				$row[] = '<span class="label label-warning"><i class="fa fa-star"></i> Default</span>';
			} else {
				$row[] = '<span class="text-muted">-</span>';
			}
				     $str2 = '<div class="btn-group" title="View Account">
										<a class="btn btn-primary btn-o dropdown-toggle" data-toggle="dropdown" href="#">
											Action <span class="caret"></span>
										</a>
										<ul role="menu" class="dropdown-menu dropdown-light pull-right">';

											if($this->permissions('accounts_edit'))
											$str2.='<li>
												<a data-toggle="tooltip" title="Edit Record ?" href="'.base_url().'accounts/update/'.$accounts->id.'">
													<i class="fa fa-fw fa-edit text-blue"></i>Edit
												</a>
											</li>';

											if($this->permissions('accounts_view'))
											$str2.='<li>
												<a data-toggle="tooltip" title="Click to check Account!" href="'.base_url().'accounts/book/'.$accounts->id.'">
													<i class="fa fa-fw fa-book text-blue"></i>Account Book
												</a>
											</li>';

											if($this->permissions('accounts_delete') && !$accounts->delete_bit)
											$str2.='<li>
												<a style="cursor:pointer" data-toggle="tooltip" title="Delete Record ?" onclick="delete_accounts('.$accounts->id.')">
													<i class="fa fa-fw fa-trash text-red"></i>Delete
												</a>
											</li>
											
										</ul>
									</div>';			
			$row[] = $str2;

			$data[] = $row;
		}

		$output = array(
						"draw" => $_POST['draw'],
						"recordsTotal" => $this->accounts->count_all(),
						"recordsFiltered" => $this->accounts->count_filtered(),
						"data" => $data,
				);
		
		// Debug: Log the output
		log_message('debug', 'Accounts ajax_list - Output: ' . json_encode($output));
		
		//output to json format
		echo json_encode($output);
	}
	
	public function delete_accounts(){
		$this->permission_check_with_msg('accounts_delete');
		$id=$this->input->post('q_id');
		echo $this->accounts->delete_accounts_from_table($id);
	}
	public function multi_delete_accounts(){
		$this->permission_check_with_msg('accounts_delete');
		$ids=implode (",",$_POST['checkbox']);
		echo $this->accounts->delete_accounts_from_table($ids);
	}
	


}
