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

class Store_profile extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load_global();
		$this->load->model('store_profile_model','store');
	}

	public function update($id){
		//if not admin
		if(!is_admin()){
			if($id!=get_current_store_id()){
				show_error("Access Denied", 403, $heading = "You Don't Have Enough Permission!!");exit();
			}
		}

		$this->permission_check('store_edit');
		$data=$this->store->get_details($id);
		$data['page_title']=$this->lang->line('store');
		$this->load->view('store', $data);
	}
	public function update_store(){
		$result=$this->store->update_store();
		
		// Check if result is JSON (currency blocking response)
		if (is_string($result) && json_decode($result) !== null) {
			echo $result;
		} else {
			// Regular response
			echo $result;
		}
	}

	public function check_currency_blockers(){
		// Check what's blocking currency changes
		$store_id = $this->input->get('store_id') ?: get_current_store_id();
		
		$CI =& get_instance();
		$tables_to_check = [
			'db_sales' => 'store_id',
			'db_purchase' => 'store_id', 
			'db_salesreturn' => 'store_id',
			'db_purchasereturn' => 'store_id',
			'db_expense' => 'store_id',
			'db_quotation' => 'store_id',
			'db_salespayments' => 'store_id',
			'db_purchasepayments' => 'store_id',
			'db_custadvance' => 'store_id',
			'ac_transactions' => 'store_id'
		];
		
		$blocking_tables = [];
		
		foreach ($tables_to_check as $table => $column) {
			$CI->db->select('COUNT(*) as count');
			$CI->db->from($table);
			$CI->db->where($column, $store_id);
			$result = $CI->db->get()->row();
			
			if ($result && $result->count > 0) {
				$blocking_tables[] = [
					'table' => $table,
					'count' => $result->count
				];
			}
		}
		
		header('Content-Type: application/json');
		echo json_encode([
			'store_id' => $store_id,
			'blocking_tables' => $blocking_tables,
			'can_change_currency' => empty($blocking_tables)
		]);
	}

	public function clear_transactions_for_currency_change(){
		// Clear all transactions to allow currency change
		$store_id = $this->input->post('store_id') ?: get_current_store_id();
		
		if (!is_admin()) {
			echo json_encode(['success' => false, 'message' => 'Access denied. Admin only.']);
			return;
		}
		
		$cleared_tables = clear_all_transactions_for_currency_change($store_id);
		
		if ($cleared_tables !== false) {
			echo json_encode([
				'success' => true, 
				'message' => 'All transactions cleared successfully.',
				'cleared_tables' => $cleared_tables
			]);
		} else {
			echo json_encode(['success' => false, 'message' => 'Failed to clear transactions.']);
		}
	}

}