<?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();
		echo $result;	
	}

	public function clear_data(){
		// Only allow admin or store admin access
		if(!is_admin() && !is_store_admin()){
			echo json_encode(array('success' => false, 'message' => 'Access denied. Admin or Store Admin privileges required.'));
			return;
		}

		// Temporarily comment out permission check
		// $this->permission_check('store_edit');

		// Temporarily comment out permission check
		// $this->permission_check('store_edit');
		
		// Check if request is POST
		if($this->input->method() !== 'post') {
			echo json_encode(array('success' => false, 'message' => 'Only POST requests allowed.'));
			return;
		}
		
		$action = $this->input->post('action');
		
		// Log the action for security purposes
		log_message('info', 'Data clearing action attempted by user: ' . $this->session->userdata('inv_username') . ', Action: ' . $action);
		
		try {
			if($action == 'clear_selected') {
				$tables = $this->input->post('tables');
				if(empty($tables) || !is_array($tables)) {
					echo json_encode(array('success' => false, 'message' => 'No tables selected.'));
					return;
				}
				
				log_message('info', 'Selected tables to clear: ' . implode(', ', $tables));
				$result = $this->clear_selected_tables($tables);
				echo json_encode($result);
				
			} elseif($action == 'clear_all') {
				log_message('warning', 'ALL DATA clearing action attempted by user: ' . $this->session->userdata('inv_username'));
				$result = $this->clear_all_tables();
				echo json_encode($result);
			} else {
				echo json_encode(array('success' => false, 'message' => 'Invalid action.'));
			}
		} catch (Exception $e) {
			log_message('error', 'Data clearing error: ' . $e->getMessage());
			echo json_encode(array('success' => false, 'message' => 'Error: ' . $e->getMessage()));
		}
	}

	public function create_backup(){
		// Only allow admin or store admin access
		if(!is_admin() && !is_store_admin()){
			echo json_encode(array('success' => false, 'message' => 'Access denied. Admin or Store Admin privileges required.'));
			return;
		}

		// Temporarily comment out permission check
		// $this->permission_check('store_edit');
		
		// Check if request is POST
		if($this->input->method() !== 'post') {
			echo json_encode(array('success' => false, 'message' => 'Only POST requests allowed.'));
			return;
		}

		try {
			// Load database utility
			$this->load->dbutil();
			
			// Get database configuration
			$db_config = $this->db->database;
			$db_name = $this->db->database;
			
			// Create filename with timestamp
			$filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
			$backup_path = FCPATH . 'dbbackup/' . $filename;
			
			// Ensure backup directory exists
			if (!is_dir(FCPATH . 'dbbackup/')) {
				mkdir(FCPATH . 'dbbackup/', 0755, true);
			}
			
			// Create backup using mysqldump command
			$mysql_path = 'c:\wamp64\bin\mysql\mysql9.1.0\bin\mysqldump.exe';
			$command = '"' . $mysql_path . '" -u root --single-transaction --routines --triggers ' . $db_name . ' > "' . $backup_path . '"';
			
			log_message('info', 'Creating backup with command: ' . $command);
			
			// Execute the command
			$output = array();
			$return_var = 0;
			exec($command . ' 2>&1', $output, $return_var);
			
			if ($return_var === 0 && file_exists($backup_path)) {
				log_message('info', 'Backup created successfully: ' . $filename);
				echo json_encode(array(
					'success' => true, 
					'message' => 'Backup created successfully!',
					'filename' => $filename,
					'path' => $backup_path,
					'download_url' => base_url('dbbackup/' . $filename)
				));
			} else {
				$error_msg = 'Backup failed. Output: ' . implode('\n', $output);
				log_message('error', $error_msg);
				echo json_encode(array('success' => false, 'message' => $error_msg));
			}
			
		} catch (Exception $e) {
			log_message('error', 'Backup error: ' . $e->getMessage());
			echo json_encode(array('success' => false, 'message' => 'Error: ' . $e->getMessage()));
		}
	}

	private function clear_selected_tables($tables) {
		// List of allowed tables to prevent SQL injection
		$allowed_tables = array(
			'db_sales', 'db_salesitems', 'db_salespayments', 'db_salesreturn', 
			'db_salesitemsreturn', 'db_salespaymentsreturn',
			'db_purchase', 'db_purchaseitems', 'db_purchasepayments', 'db_purchasereturn',
			'db_purchaseitemsreturn', 'db_purchasepaymentsreturn',
			'db_quotation', 'db_quotationitems',
			'db_customers', 'db_custadvance', 'db_custbulkpayments', 'db_customer_coupons',
			'db_suppliers', 'db_items', 'db_category', 'db_brands', 'db_units', 'db_variants',
			'db_expense', 'db_expense_category',
			'db_stockadjustment', 'db_stockadjustmentitems', 'db_stocktransfer', 'db_stocktransferitems'
		);

		$cleared_tables = array();
		$errors = array();

		try {
			// Disable foreign key checks to allow truncating tables with foreign key constraints
			$this->db->query('SET FOREIGN_KEY_CHECKS = 0');
			
			foreach($tables as $table) {
				if(in_array($table, $allowed_tables)) {
					try {
						// Use direct SQL query instead of truncate() method for better foreign key handling
						$this->db->query("TRUNCATE TABLE `$table`");
						$cleared_tables[] = $table;
						log_message('info', "Successfully cleared table: $table");
					} catch (Exception $e) {
						$errors[] = "Failed to clear $table: " . $e->getMessage();
						log_message('error', "Failed to clear table $table: " . $e->getMessage());
					}
				} else {
					$errors[] = "Table $table is not allowed to be cleared.";
					log_message('warning', "Attempt to clear unauthorized table: $table");
				}
			}
			
		} catch (Exception $e) {
			$errors[] = "Database error: " . $e->getMessage();
			log_message('error', "Database error during table clearing: " . $e->getMessage());
		} finally {
			// Always re-enable foreign key checks
			try {
				$this->db->query('SET FOREIGN_KEY_CHECKS = 1');
			} catch (Exception $e) {
				log_message('error', "Failed to re-enable foreign key checks: " . $e->getMessage());
			}
		}

		if(count($errors) > 0) {
			return array(
				'success' => false, 
				'message' => 'Some tables could not be cleared: ' . implode(', ', $errors),
				'cleared_tables' => $cleared_tables
			);
		} else {
			return array(
				'success' => true, 
				'message' => 'Successfully cleared ' . count($cleared_tables) . ' tables.',
				'cleared_tables' => $cleared_tables
			);
		}
	}

	private function clear_all_tables() {
		// Define all main data tables (excluding system tables like users, store settings, etc.)
		$all_tables = array(
			'db_sales', 'db_salesitems', 'db_salespayments', 'db_salesreturn', 
			'db_salesitemsreturn', 'db_salespaymentsreturn',
			'db_purchase', 'db_purchaseitems', 'db_purchasepayments', 'db_purchasereturn',
			'db_purchaseitemsreturn', 'db_purchasepaymentsreturn',
			'db_quotation', 'db_quotationitems',
			'db_customers', 'db_custadvance', 'db_custbulkpayments', 'db_customer_coupons',
			'db_suppliers', 'db_items', 'db_category', 'db_brands', 'db_units', 'db_variants',
			'db_expense', 'db_expense_category',
			'db_stockadjustment', 'db_stockadjustmentitems', 'db_stocktransfer', 'db_stocktransferitems',
			'db_coupons', 'db_hold', 'db_holditems'
		);

		return $this->clear_selected_tables($all_tables);
	}

}