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

class Exchange_rates extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load_global();
        $this->load->model('exchange_rates_model', 'exchange_rates');
        $this->load->helper('currency');
        $this->load->helper('multi_currency');
    }
    
    public function index() {
        $this->permission_check('exchange_rates_view');
        $data = $this->data;
        $data['page_title'] = 'Exchange Rates Management';
        $data['currencies'] = get_currency_list();
        $data['base_currency'] = get_base_currency();
        
        $this->load->view('exchange_rates', $data);
    }
    
    public function add() {
        $this->permission_check('exchange_rates_add');
        $data = $this->data;
        $data['page_title'] = 'Add Exchange Rate';
        $data['currencies'] = get_currency_list();
        $data['base_currency'] = get_base_currency();
        
        $this->load->view('exchange_rates_form', $data);
    }
    
    public function save() {
        $this->permission_check('exchange_rates_add');
        $this->form_validation->set_rules('from_currency_id', 'From Currency', 'required|numeric');
        $this->form_validation->set_rules('to_currency_id', 'To Currency', 'required|numeric');
        $this->form_validation->set_rules('exchange_rate', 'Exchange Rate', 'required|numeric|greater_than[0]');
        $this->form_validation->set_rules('effective_date', 'Effective Date', 'required');
        
        if ($this->form_validation->run() == TRUE) {
            $create_bidirectional = $this->input->post('create_bidirectional') == 'true';
            
            if ($create_bidirectional) {
                // Save both directions
                $result = $this->exchange_rates->save_bidirectional();
                echo $result;
            } else {
                // Save single direction only
                $result = $this->exchange_rates->save();
                echo $result;
            }
        } else {
            echo "Please fill all required fields correctly!";
        }
    }
    
    
    public function delete($id) {
        $this->permission_check('exchange_rates_delete');
        $result = $this->exchange_rates->delete($id);
        echo $result;
    }
    
    
    
    public function can_delete($id) {
        $can_delete = !$this->exchange_rates->is_rate_used_in_transactions($id);
        echo json_encode(['can_delete' => $can_delete]);
    }
    
    public function check_delete_all() {
        // Get all manual exchange rates
        $this->db->where('rate_type', 'manual');
        $rates = $this->db->get('db_exchange_rates')->result();
        
        $can_delete_all = true;
        foreach ($rates as $rate) {
            if ($this->exchange_rates->is_rate_used_in_transactions($rate->id)) {
                $can_delete_all = false;
                break;
            }
        }
        
        echo json_encode(['can_delete_all' => $can_delete_all]);
    }
    
    public function debug_transactions($rate_id) {
        // Debug method to see what transactions exist
        $rate = $this->db->where('id', $rate_id)->get('db_exchange_rates')->row();
        
        $debug = array(
            'rate' => $rate,
            'sales_payments_all' => $this->db->where('payment_currency_id', $rate->from_currency_id)->get('db_salespayments')->result(),
            'sales_payments_exact' => $this->db->where('payment_currency_id', $rate->from_currency_id)->where('exchange_rate', $rate->exchange_rate)->get('db_salespayments')->result(),
            'account_transactions_all' => $this->db->where('currency_id', $rate->from_currency_id)->get('ac_transactions')->result(),
            'account_transactions_exact' => $this->db->where('currency_id', $rate->from_currency_id)->where('exchange_rate', $rate->exchange_rate)->get('ac_transactions')->result()
        );
        
        echo json_encode($debug);
    }
    
    public function get_rates() {
        try {
            $list = $this->exchange_rates->get_datatables();
            $data = array();
            $no = $_POST['start'];
        
        foreach ($list as $rate) {
            $no++;
            $row = array();
            
            // Check if rate can be deleted
            $can_delete = !$this->exchange_rates->is_rate_used_in_transactions($rate->id);
            
            $from_currency_text = $rate->from_currency_name . ' (' . $rate->from_currency_code . ')';
            $to_currency_text = $rate->to_currency_name . ' (' . $rate->to_currency_code . ')';
            
            // Add lock icon if rate is used in transactions
            if (!$can_delete) {
                $from_currency_text .= ' <i class="fa fa-lock text-warning" title="Rate used in transactions - locked for data integrity"></i>';
                $to_currency_text .= ' <i class="fa fa-lock text-warning" title="Rate used in transactions - locked for data integrity"></i>';
            }
            
            $row[] = $from_currency_text;
            $row[] = $to_currency_text;
            $row[] = number_format($rate->exchange_rate, 6);
            $row[] = $rate->effective_date;
            $row[] = ($rate->rate_type == 'api') ? '<span class="label label-info"><i class="fa fa-cloud"></i> API</span>' : '<span class="label label-primary"><i class="fa fa-edit"></i> Manual</span>';
            $row[] = ($rate->status == 1) ? '<span class="label label-success">Active</span>' : '<span class="label label-danger">Inactive</span>';
            
            // Get transaction count for this rate
            $transaction_count = $this->exchange_rates->get_transaction_count_for_rate($rate->id);
            $row[] = '<span class="badge bg-blue">' . $transaction_count . '</span>';
            
            // Create action button - only delete (no edit)
            if ($can_delete) {
                $delete_button = '<button type="button" class="btn btn-danger btn-sm" onclick="delete_exchange_rate(' . $rate->id . ')" title="Delete Exchange Rate">
                    <i class="fa fa-trash"></i>
                </button>';
            } else {
                $delete_button = '<button type="button" class="btn btn-default btn-sm" disabled title="Cannot delete - rate is used in transactions">
                    <i class="fa fa-lock"></i>
                </button>';
            }
            
            $actions = '<div class="btn-group">
                ' . $delete_button . '
            </div>';
            $row[] = $actions;
            
            $data[] = $row;
        }
        
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->exchange_rates->count_all(),
            "recordsFiltered" => $this->exchange_rates->count_filtered(),
            "data" => $data
        );
        
        echo json_encode($output);
        } catch (Exception $e) {
            $output = array(
                "draw" => $_POST['draw'],
                "recordsTotal" => 0,
                "recordsFiltered" => 0,
                "data" => array(),
                "error" => "Error loading data: " . $e->getMessage()
            );
            echo json_encode($output);
        }
    }
    
    public function get_rate_by_currencies() {
        $from_currency_id = $this->input->post('from_currency_id');
        $to_currency_id = $this->input->post('to_currency_id');
        $date = $this->input->post('date') ?: date('Y-m-d');
        
        if (empty($from_currency_id) || empty($to_currency_id)) {
            echo json_encode(array('error' => 'Please select both currencies'));
            return;
        }
        
        $rate = get_exchange_rate($from_currency_id, $to_currency_id, null, $date);
        
        if ($rate == 1.000000 && $from_currency_id != $to_currency_id) {
            // Get currency names for better error message
            $from_currency = get_currency_by_id($from_currency_id);
            $to_currency = get_currency_by_id($to_currency_id);
            $from_name = $from_currency ? $from_currency->currency_name : 'Unknown';
            $to_name = $to_currency ? $to_currency->currency_name : 'Unknown';
            
            echo json_encode(array('error' => "No exchange rate set between {$from_name} and {$to_name}. Please add an exchange rate first."));
            return;
        }
        
        echo json_encode(array(
            'success' => true,
            'rate' => $rate
        ));
    }
    
    public function check_exchange_rate() {
        $from_currency_id = $this->input->post('from_currency_id');
        $to_currency_id = $this->input->post('to_currency_id');
        $date = $this->input->post('date') ?: date('Y-m-d');
        
        if (empty($from_currency_id) || empty($to_currency_id)) {
            echo json_encode(array('error' => 'Please select both currencies'));
            return;
        }
        
        $result = check_exchange_rate_exists($from_currency_id, $to_currency_id, $date);
        echo json_encode($result);
    }
    
    public function validate_customer_exchange_rate() {
        try {
            $customer_id = $this->input->post('customer_id');
            $base_currency = get_base_currency();
            
            if (!$base_currency) {
                echo json_encode(array('valid' => false, 'message' => 'Base currency not found'));
                return;
            }
            
            $base_currency_id = $base_currency->id;
            
            if (empty($customer_id)) {
                echo json_encode(array('valid' => true, 'message' => 'No customer selected'));
                return;
            }
            
            // Get customer's trading currency
            $customer_currency = get_customer_trading_currency($customer_id);
            
            if (!$customer_currency || $customer_currency->id == $base_currency_id) {
                echo json_encode(array('valid' => true, 'message' => 'Customer uses base currency'));
                return;
            }
            
            // Check if exchange rate exists
            error_log('Checking exchange rate between customer currency ID: ' . $customer_currency->id . ' and base currency ID: ' . $base_currency_id);
            $result = check_exchange_rate_exists($customer_currency->id, $base_currency_id);
            error_log('Exchange rate check result: ' . json_encode($result));
            
            if ($result['exists']) {
                echo json_encode(array('valid' => true, 'message' => 'Exchange rate found'));
            } else {
                echo json_encode(array(
                    'valid' => false, 
                    'message' => $result['message'],
                    'from_currency' => $result['from_currency'],
                    'to_currency' => $result['to_currency']
                ));
            }
        } catch (Exception $e) {
            error_log('Exchange rate validation error: ' . $e->getMessage());
            echo json_encode(array('valid' => false, 'message' => 'Error validating exchange rate: ' . $e->getMessage()));
        }
    }
    
    public function validate_supplier_exchange_rate() {
        $supplier_id = $this->input->post('supplier_id');
        $base_currency_id = get_base_currency()->id;
        
        if (empty($supplier_id)) {
            echo json_encode(array('valid' => true, 'message' => 'No supplier selected'));
            return;
        }
        
        // Get supplier's trading currency
        $supplier_currency = get_supplier_trading_currency($supplier_id);
        
        if (!$supplier_currency || $supplier_currency->id == $base_currency_id) {
            echo json_encode(array('valid' => true, 'message' => 'Supplier uses base currency'));
            return;
        }
        
        // Check if exchange rate exists
        $result = check_exchange_rate_exists($supplier_currency->id, $base_currency_id);
        
        if ($result['exists']) {
            echo json_encode(array('valid' => true, 'message' => 'Exchange rate found'));
        } else {
            echo json_encode(array(
                'valid' => false, 
                'message' => $result['message'],
                'from_currency' => $result['from_currency'],
                'to_currency' => $result['to_currency']
            ));
        }
    }
    
    public function fetch_api_rates() {
        $base_currency_code = $this->input->post('base_currency_code') ?: 'USD';
        $date = $this->input->post('date') ?: date('Y-m-d');
        
        // Fetch rates from API
        $api_result = $this->exchange_rates->fetch_rates_from_api($base_currency_code);
        
        if (!$api_result['success']) {
            echo json_encode($api_result);
            return;
        }
        
        // Save rates to database
        $save_result = $this->exchange_rates->save_api_rates(
            $api_result['rates'], 
            $base_currency_code, 
            $date
        );
        
        echo json_encode(array(
            'success' => $save_result['success'],
            'message' => $save_result['message'],
            'api_info' => array(
                'base_currency' => $api_result['base_currency'],
                'date' => $api_result['date'],
                'total_rates' => count($api_result['rates'])
            ),
            'save_info' => array(
                'saved_count' => $save_result['saved_count'],
                'skipped_count' => $save_result['skipped_count'],
                'error_count' => $save_result['error_count']
            )
        ));
    }
    
    public function check_internet_connection() {
        $result = $this->exchange_rates->check_internet_connection();
        echo json_encode(array('connected' => $result));
    }
    
    public function clean_unused_rates() {
        $this->permission_check('exchange_rates_delete');
        
        try {
            $cleaned_count = 0;
            $locked_count = 0;
            $total_rates = 0;
            
            // Get all exchange rates
            $rates = $this->db->query("SELECT * FROM db_exchange_rates")->result();
            $total_rates = count($rates);
            
            foreach ($rates as $rate) {
                // Check if this rate is locked (used in transactions)
                if ($this->exchange_rates->is_rate_used_in_transactions($rate->id)) {
                    $locked_count++;
                    continue; // Skip locked rates - don't delete them
                }
                
                $is_used = false;
                
                // Check if this exchange rate is used in sales payments
                if (!$is_used) {
                    $sales_check = $this->db->query("SELECT COUNT(*) as count FROM db_salespayments WHERE payment_currency_id = ?", array($rate->from_currency_id))->row();
                    if ($sales_check && $sales_check->count > 0) {
                        $is_used = true;
                    }
                }
                
                // Check if this exchange rate is used in purchase payments
                if (!$is_used) {
                    $purchase_check = $this->db->query("SELECT COUNT(*) as count FROM db_purchasepayments WHERE payment_currency_id = ?", array($rate->from_currency_id))->row();
                    if ($purchase_check && $purchase_check->count > 0) {
                        $is_used = true;
                    }
                }
                
                // Check if this exchange rate is used in sales (transaction_currency_id)
                if (!$is_used) {
                    $sales_currency_check = $this->db->query("SELECT COUNT(*) as count FROM db_sales WHERE transaction_currency_id = ?", array($rate->from_currency_id))->row();
                    if ($sales_currency_check && $sales_currency_check->count > 0) {
                        $is_used = true;
                    }
                }
                
                // Check if this exchange rate is used in purchases (transaction_currency_id)
                if (!$is_used) {
                    $purchase_currency_check = $this->db->query("SELECT COUNT(*) as count FROM db_purchase WHERE transaction_currency_id = ?", array($rate->from_currency_id))->row();
                    if ($purchase_currency_check && $purchase_currency_check->count > 0) {
                        $is_used = true;
                    }
                }
                
                // Check if this exchange rate is used in quotations (transaction_currency_id)
                if (!$is_used) {
                    $quotation_currency_check = $this->db->query("SELECT COUNT(*) as count FROM db_quotation WHERE transaction_currency_id = ?", array($rate->from_currency_id))->row();
                    if ($quotation_currency_check && $quotation_currency_check->count > 0) {
                        $is_used = true;
                    }
                }
                
                // If not used anywhere and not locked, delete it
                if (!$is_used) {
                    $this->db->query("DELETE FROM db_exchange_rates WHERE id = ?", array($rate->id));
                    $cleaned_count++;
                }
            }
            
            $message = "Cleaned " . $cleaned_count . " unused exchange rates out of " . $total_rates . " total rates.";
            if ($locked_count > 0) {
                $message .= " " . $locked_count . " rates were locked (used in transactions) and preserved.";
            }
            
            echo json_encode([
                'success' => true,
                'message' => $message,
                'cleaned_count' => $cleaned_count,
                'locked_count' => $locked_count,
                'total_count' => $total_rates
            ]);
            
        } catch (Exception $e) {
            echo json_encode([
                'success' => false,
                'message' => 'Error cleaning exchange rates: ' . $e->getMessage()
            ]);
        }
    }
    
    public function fetch_single_api_rate() {
        $this->permission_check('exchange_rates_add');
        $from_currency_id = $this->input->post('from_currency_id');
        $to_currency_id = $this->input->post('to_currency_id');
        $date = $this->input->post('date') ?: date('Y-m-d');
        $expiry_date = $this->input->post('expiry_date');
        $preview_only = $this->input->post('preview_only');
        
        if (empty($from_currency_id) || empty($to_currency_id)) {
            echo json_encode(array(
                'success' => false,
                'message' => 'Please select both from and to currencies'
            ));
            return;
        }
        
        if ($from_currency_id == $to_currency_id) {
            echo json_encode(array(
                'success' => false,
                'message' => 'From and To currencies cannot be the same'
            ));
            return;
        }
        
        // Fetch rate from API
        $api_result = $this->exchange_rates->fetch_single_rate_from_api($from_currency_id, $to_currency_id, $date);
        
        if (!$api_result['success']) {
            echo json_encode($api_result);
            return;
        }
        
        // If preview only, return the rate data
        if ($preview_only) {
            echo json_encode(array(
                'success' => true,
                'rate' => $api_result['rate'],
                'from_currency_name' => $api_result['from_currency_name'],
                'to_currency_name' => $api_result['to_currency_name'],
                'from_currency_code' => $api_result['from_currency_code'],
                'to_currency_code' => $api_result['to_currency_code'],
                'date' => $api_result['date'],
                'message' => $api_result['message']
            ));
            return;
        }
        
        // Check if bidirectional creation is enabled
        $create_bidirectional = $this->input->post('create_bidirectional') == 'true';
        
        if ($create_bidirectional) {
            // Save both directions
            $save_result = $this->exchange_rates->save_single_api_rate_bidirectional(
                $from_currency_id, 
                $to_currency_id, 
                $api_result['rate'], 
                $date, 
                $expiry_date
            );
        } else {
            // Save single direction only
            $save_result = $this->exchange_rates->save_single_api_rate(
                $from_currency_id, 
                $to_currency_id, 
                $api_result['rate'], 
                $date, 
                $expiry_date
            );
        }
        
        echo json_encode($save_result);
    }
    
    public function bulk_update() {
        $rates = $this->input->post('rates');
        
        if (empty($rates) || !is_array($rates)) {
            echo "No rates provided!";
            return;
        }
        
        $success_count = 0;
        $error_count = 0;
        
        foreach ($rates as $rate_data) {
            if (isset($rate_data['from_currency_id']) && 
                isset($rate_data['to_currency_id']) && 
                isset($rate_data['exchange_rate']) && 
                isset($rate_data['effective_date'])) {
                
                $result = update_exchange_rate(
                    $rate_data['from_currency_id'],
                    $rate_data['to_currency_id'],
                    $rate_data['exchange_rate'],
                    null,
                    $rate_data['effective_date']
                );
                
                if ($result) {
                    $success_count++;
                } else {
                    $error_count++;
                }
            } else {
                $error_count++;
            }
        }
        
        echo json_encode(array(
            'success' => true,
            'message' => "Updated {$success_count} rates successfully. {$error_count} errors occurred.",
            'success_count' => $success_count,
            'error_count' => $error_count
        ));
    }
    
    /**
     * Fetch all bidirectional exchange rates for all currency pairs
     */
    public function fetch_all_bidirectional_rates() {
        $this->permission_check('exchange_rates_add');
        
        $date = $this->input->post('date') ?: date('Y-m-d');
        
        // Fetch all bidirectional rates
        $fetch_result = $this->exchange_rates->fetch_all_bidirectional_rates($date);
        
        if (!$fetch_result['success']) {
            echo json_encode($fetch_result);
            return;
        }
        
        // Save all rates to database
        $save_result = $this->exchange_rates->save_all_bidirectional_rates($fetch_result['rates'], $date);
        
        echo json_encode(array(
            'success' => $save_result['success'],
            'message' => $save_result['message'],
            'fetch_info' => array(
                'total_currencies' => $fetch_result['statistics']['total_currencies'],
                'fetched_rates' => $fetch_result['statistics']['success_count'],
                'fetch_errors' => $fetch_result['statistics']['error_count'],
                'skipped_rates' => $fetch_result['statistics']['skipped_count']
            ),
            'save_info' => array(
                'saved_count' => $save_result['saved_count'],
                'skipped_count' => $save_result['skipped_count'],
                'error_count' => $save_result['error_count']
            ),
            'errors' => array_merge($fetch_result['errors'], $save_result['errors'])
        ));
    }
    
    /**
     * Validate bidirectional rates completeness
     */
    public function validate_bidirectional_rates() {
        $this->permission_check('exchange_rates_view');
        
        $date = $this->input->post('date') ?: date('Y-m-d');
        
        $validation_result = $this->exchange_rates->validate_bidirectional_rates($date);
        
        echo json_encode($validation_result);
    }
    
    /**
     * Get all available currencies
     */
    public function get_all_currencies() {
        $this->permission_check('exchange_rates_view');
        
        $currencies = $this->exchange_rates->get_all_currencies();
        
        echo json_encode(array(
            'success' => true,
            'currencies' => $currencies,
            'count' => count($currencies)
        ));
    }
    
    /**
     * Get currencies that are actually used by customers, suppliers, and base currency
     */
    public function get_used_currencies() {
        $this->permission_check('exchange_rates_view');
        
        try {
            $currencies = $this->exchange_rates->get_used_currencies();
            
            echo json_encode(array(
                'success' => true,
                'currencies' => $currencies,
                'count' => count($currencies)
            ));
        } catch (Exception $e) {
            log_message('error', 'Error in get_used_currencies controller: ' . $e->getMessage());
            echo json_encode(array(
                'success' => false,
                'message' => 'Error loading currencies: ' . $e->getMessage(),
                'currencies' => array(),
                'count' => 0
            ));
        }
    }
    
    /**
     * Get rate validation status for UI display
     */
    public function get_rate_status() {
        $this->permission_check('exchange_rates_view');
        
        $date = $this->input->get('date') ?: date('Y-m-d');
        
        $validation_result = $this->exchange_rates->validate_bidirectional_rates($date);
        
        echo json_encode(array(
            'success' => true,
            'is_complete' => $validation_result['is_complete'],
            'total_currencies' => $validation_result['total_currencies'],
            'expected_pairs' => $validation_result['expected_pairs'],
            'missing_count' => $validation_result['missing_count'],
            'completion_percentage' => $validation_result['expected_pairs'] > 0 ? 
                round((($validation_result['expected_pairs'] - $validation_result['missing_count']) / $validation_result['expected_pairs']) * 100, 2) : 100
        ));
    }
    
}
