<!DOCTYPE html>
<html>
<head>
    <?php include "comman/code_css.php"; ?>
    <style>
        .datepicker {
            cursor: pointer;
        }
        
        .input-group-addon {
            cursor: pointer;
            background-color: #f5f5f5;
            border-color: #ccc;
        }
        
        .input-group-addon:hover {
            background-color: #e6e6e6;
        }
        
        .datepicker table tr td.active.active {
            background-color: #337ab7;
            border-color: #2e6da4;
        }
        
        .datepicker table tr td.today {
            background-color: #ffc107;
            color: #000;
        }
        
        /* Modal styling */
        .modal-header .modal-title {
            font-weight: bold;
        }
        
        .modal-body .alert {
            margin-bottom: 15px;
        }
        
        .modal-footer .btn {
            margin-left: 5px;
        }
        
        .modal-footer .btn:first-child {
            margin-left: 0;
        }
    </style>
</head>
<body class="hold-transition skin-blue sidebar-mini">
    <div class="wrapper">
        <?php include "sidebar.php"; ?>
        
        <!-- Content Wrapper. Contains page content -->
        <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <section class="content-header">
                <h1>
                    <i class="fa fa-exchange"></i> <?= $page_title ?>
                </h1>
                <ol class="breadcrumb">
                    <li><a href="<?= $base_url ?>dashboard"><i class="fa fa-dashboard"></i> Home</a></li>
                    <li class="active"><?= $page_title ?></li>
                </ol>
            </section>

            <!-- Main content -->
            <section class="content">
                <div class="row">
                    <!-- Alert Messages -->
                    <?php include "comman/code_flashdata.php"; ?>
                </div>

                <div class="row">
                    <!-- Exchange Rates Management -->
                    <div class="col-md-12">
                        <div class="box box-primary">
                            <div class="box-header with-border">
                                <h3 class="box-title">
                                    <i class="fa fa-list"></i> Exchange Rates
                                </h3>
                                <div class="box-tools pull-right">
                                    <button type="button" class="btn btn-success btn-sm" onclick="add_exchange_rate()">
                                        <i class="fa fa-plus"></i> Add Manual Rate
                                    </button>
                                    <button type="button" class="btn btn-info btn-sm" onclick="fetch_api_rates()">
                                        <i class="fa fa-cloud-download"></i> Fetch API Rate
                                    </button>
                                    <button type="button" class="btn btn-danger btn-sm" onclick="clean_unused_rates()">
                                        <i class="fa fa-trash"></i> Clean Unused Rates
                                    </button>
                                </div>
                            </div>
                            <div class="box-body">
                                <div class="table-responsive">
                                    <table id="exchange_rates_table" class="table table-bordered table-striped">
                                        <thead>
                                            <tr>
                                                <th>From Currency</th>
                                                <th>To Currency</th>
                                                <th>Exchange Rate</th>
                                                <th>Effective Date</th>
                                                <th>Rate Type</th>
                                                <th>Status</th>
                                                <th>Transaction Count</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Quick Rate Update -->
            </section>
        </div>
    </div>


    <!-- Delete Single Exchange Rate Modal -->
    <div class="modal fade" id="delete_single_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">
                        <i class="fa fa-trash text-danger"></i> Delete Exchange Rate
                    </h4>
                </div>
                <div class="modal-body">
                    <p>Are you sure you want to delete this exchange rate?</p>
                    <p>This action cannot be undone.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">
                        <i class="fa fa-times"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-danger" onclick="confirm_delete_single()">
                        <i class="fa fa-trash"></i> Delete
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Fetch API Rate Modal -->
    <div class="modal fade" id="api_rates_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">
                        <i class="fa fa-cloud-download"></i> Fetch Exchange Rate from API
                    </h4>
                </div>
                <form id="api_rates_form">
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fa fa-info-circle"></i> <strong>Note:</strong> This feature requires an internet connection to fetch real-time exchange rates from an external API.
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="api_from_currency">From Currency <span class="text-danger">*</span></label>
                                    <select class="form-control" name="api_from_currency" id="api_from_currency" required>
                                        <option value="">Select From Currency</option>
                                        <?php foreach($currencies as $currency): ?>
                                            <option value="<?= $currency->id ?>"><?= $currency->currency_name ?> (<?= $currency->currency_code ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="api_to_currency">To Currency <span class="text-danger">*</span></label>
                                    <select class="form-control" name="api_to_currency" id="api_to_currency" required>
                                        <option value="">Select To Currency</option>
                                        <?php foreach($currencies as $currency): ?>
                                            <option value="<?= $currency->id ?>"><?= $currency->currency_name ?> (<?= $currency->currency_code ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="api_effective_date">Effective Date <span class="text-danger">*</span></label>
                                    <div class="input-group date">
                                        <input type="text" class="form-control datepicker" name="api_effective_date" id="api_effective_date" 
                                               value="<?= date('Y-m-d') ?>" required>
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="api_expiry_date">Expiry Date</label>
                                    <div class="input-group date">
                                        <input type="text" class="form-control datepicker" name="api_expiry_date" id="api_expiry_date" 
                                               placeholder="Select expiry date">
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                    </div>
                                    <small class="text-muted">Leave empty for no expiry</small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <div class="alert alert-info">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="api_create_bidirectional" id="api_create_bidirectional" checked>
                                            <strong>Create Both Directions</strong> - Automatically create reverse rate (B→A) when fetching A→B rate
                                        </label>
                                    </div>
                                    <small class="text-muted">
                                        <i class="fa fa-info-circle"></i> 
                                        This will fetch A→B rate from API and automatically create B→A rate (1/rate).
                                    </small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="alert alert-warning">
                            <i class="fa fa-exclamation-triangle"></i> <strong>Internet Required:</strong> 
                            <span id="internet_status">Checking internet connection...</span>
                        </div>
                        
                        <div id="api_rate_preview" style="display: none;">
                            <div class="alert alert-success">
                                <h5><i class="fa fa-info-circle"></i> Rate Preview:</h5>
                                <div id="api_rate_details">
                                    <!-- Rate details will be populated here -->
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="button" class="btn btn-info" onclick="preview_api_rate()">
                            <i class="fa fa-eye"></i> Preview Rate
                        </button>
                        <button type="submit" class="btn btn-primary" id="fetch_api_btn">
                            <i class="fa fa-cloud-download"></i> Fetch & Save Rate
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <!-- Clean Unused Exchange Rates Modal -->
    <div class="modal fade" id="clean_unused_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <div class="modal-header bg-warning">
                    <h4 class="modal-title">
                        <i class="fa fa-trash"></i> Clean Unused Rates
                    </h4>
                </div>
                <div class="modal-body">
                    <div class="alert alert-warning">
                        <strong>⚠️ WARNING: This will permanently delete unused exchange rates!</strong>
                        <p class="mb-0">Rates not used in any transactions will be cleaned.</p>
                    </div>
                    <div class="alert alert-danger">
                        <strong>This action cannot be undone!</strong>
                    </div>
                    <div class="form-group">
                        <label for="confirmCleanText">Type "CLEAN" to confirm:</label>
                        <input type="text" class="form-control" id="confirmCleanText" placeholder="Type exactly: CLEAN">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">
                        <i class="fa fa-times"></i> Cancel
                    </button>
                    <button type="button" class="btn btn-warning" onclick="proceedCleanUnused()" id="confirmCleanBtn" disabled>
                        <i class="fa fa-trash"></i> Clean Rates
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Add/Edit Exchange Rate Modal -->
    <div class="modal fade" id="exchange_rate_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title" id="modal_title">Add Exchange Rate</h4>
                </div>
                <form id="exchange_rate_form">
                    <div class="modal-body">
                        <input type="hidden" name="id" id="rate_id">
                        <input type="hidden" name="<?php echo $this->security->get_csrf_token_name();?>" value="<?php echo $this->security->get_csrf_hash();?>">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="from_currency_id">From Currency <span class="text-danger">*</span></label>
                                    <select class="form-control" name="from_currency_id" id="from_currency_id" required>
                                        <option value="">Select Currency</option>
                                        <?php foreach($currencies as $currency): ?>
                                            <option value="<?= $currency->id ?>"><?= $currency->currency_name ?> (<?= $currency->currency_code ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="to_currency_id">To Currency <span class="text-danger">*</span></label>
                                    <select class="form-control" name="to_currency_id" id="to_currency_id" required>
                                        <option value="">Select Currency</option>
                                        <?php foreach($currencies as $currency): ?>
                                            <option value="<?= $currency->id ?>"><?= $currency->currency_name ?> (<?= $currency->currency_code ?>)</option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="exchange_rate">Exchange Rate <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" name="exchange_rate" id="exchange_rate" 
                                           placeholder="0.000000" step="0.000001" required>
                                    <small class="text-muted">Rate to convert from currency to to currency</small>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="effective_date">Effective Date <span class="text-danger">*</span></label>
                                    <div class="input-group date">
                                        <input type="text" class="form-control datepicker" name="effective_date" id="effective_date" 
                                               value="" required>
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <div class="alert alert-info">
                                    <div class="checkbox">
                                        <label>
                                            <input type="checkbox" name="create_bidirectional" id="create_bidirectional" checked>
                                            <strong>Create Both Directions</strong> - Automatically create reverse rate (B→A) when adding A→B rate
                                        </label>
                                    </div>
                                    <small class="text-muted">
                                        <i class="fa fa-info-circle"></i> 
                                        This will create both A→B and B→A rates. The reverse rate will be calculated as 1/rate.
                                    </small>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="expiry_date">Expiry Date</label>
                                    <div class="input-group date">
                                        <input type="text" class="form-control datepicker" name="expiry_date" id="expiry_date" 
                                               placeholder="Select expiry date">
                                        <span class="input-group-addon">
                                            <i class="fa fa-calendar"></i>
                                        </span>
                                    </div>
                                    <small class="text-muted">Leave empty for no expiry</small>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary" id="save_btn">
                            <i class="fa fa-save"></i> Save
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <?php include "comman/code_js.php"; ?>

    <script>
    var base_url = '<?= $base_url ?>';
    var csrf_token_name = '<?php echo $this->security->get_csrf_token_name(); ?>';
    var csrf_token_value = '<?php echo $this->security->get_csrf_hash(); ?>';

    $(document).ready(function() {
        load_exchange_rates();
        
        
        // Form submission
        $('#exchange_rate_form').on('submit', function(e) {
            e.preventDefault();
            save_exchange_rate();
        });
        
    });

    function load_exchange_rates() {
        $('#exchange_rates_table').DataTable({
            "processing": true,
            "serverSide": true,
            "ajax": {
                "url": base_url + "exchange_rates/get_rates",
                "type": "POST",
                "data": function(d) {
                    d[csrf_token_name] = csrf_token_value;
                },
                "error": function(xhr, error, thrown) {
                    console.error('DataTable AJAX Error:', error, thrown);
                    console.error('Response:', xhr.responseText);
                    toastr.error('Error loading exchange rates: ' + error);
                }
            },
            "columns": [
                {"data": 0, "title": "From Currency"},
                {"data": 1, "title": "To Currency"},
                {"data": 2, "title": "Exchange Rate"},
                {"data": 3, "title": "Effective Date"},
                {"data": 4, "title": "Rate Type"},
                {"data": 5, "title": "Status"},
                {"data": 6, "title": "Transaction Count"},
                {"data": 7, "title": "Actions", "orderable": false, "searchable": false}
            ],
            "pageLength": 25,
            "language": {
                "processing": "Loading exchange rates...",
                    "emptyTable": "No exchange rates found. Click 'Add Manual Rate' or 'Auto Fetch API Rate' to get started.",
                "zeroRecords": "No matching exchange rates found"
            }
        });
    }

    function add_exchange_rate() {
        $('#exchange_rate_form')[0].reset();
        $('#rate_id').val('');
        $('#modal_title').text('Add Exchange Rate');
        
        // Set today's date as default using JavaScript
        var today = new Date();
        var todayString = today.getFullYear() + '-' + 
                         String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                         String(today.getDate()).padStart(2, '0');
        
        $('#exchange_rate_modal').modal('show');
        
        // Wait for modal to be fully shown, then initialize datepickers
        $('#exchange_rate_modal').on('shown.bs.modal', function() {
            // Set the date value
            $('#effective_date').val(todayString);
            $('#expiry_date').val('');
            
            // Initialize datepickers with current date
            $('#effective_date').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayHighlight: true,
                orientation: 'bottom auto',
                todayBtn: 'linked',
                clearBtn: true,
                startDate: '1900-01-01',
                endDate: '2100-12-31'
            });
            
            $('#expiry_date').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayHighlight: true,
                orientation: 'bottom auto',
                todayBtn: 'linked',
                clearBtn: true,
                startDate: '1900-01-01',
                endDate: '2100-12-31'
            });
            
            // Force set the date after initialization
            $('#effective_date').datepicker('setDate', today);
        });
    }

    function edit_exchange_rate(id) {
        // First check if the rate can be edited
        $.ajax({
            url: base_url + 'exchange_rates/can_edit/' + id,
            type: 'GET',
            success: function(response) {
                var data = JSON.parse(response);
                if (data.can_edit) {
                    // Rate can be edited, proceed with edit
                    $.ajax({
                        url: base_url + 'exchange_rates/edit/' + id,
                        type: 'GET',
                        success: function(response) {
                            // Handle response and populate form
                            $('#exchange_rate_modal').modal('show');
                        }
                    });
                } else {
                    // Rate cannot be edited
                    toastr.warning('This exchange rate cannot be edited because it has been used in transactions!');
                }
            },
            error: function() {
                toastr.error('Error checking edit permissions!');
            }
        });
    }

    function save_exchange_rate() {
        var formData = new FormData($('#exchange_rate_form')[0]);
        formData.append(csrf_token_name, csrf_token_value);
        
        // Check if bidirectional creation is enabled
        var createBidirectional = $('#create_bidirectional').is(':checked');
        formData.append('create_bidirectional', createBidirectional);
        
        $.ajax({
            url: base_url + 'exchange_rates/save',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response == 'success') {
                    var message = createBidirectional ? 
                        'Exchange rates saved successfully! Both directions (A→B and B→A) have been created.' : 
                        'Exchange rate saved successfully!';
                    toastr.success(message);
                    $('#exchange_rate_modal').modal('hide');
                    $('#exchange_rates_table').DataTable().ajax.reload();
                } else {
                    toastr.error(response);
                }
            }
        });
    }

    var delete_rate_id = null;

    function delete_exchange_rate(id) {
        $.ajax({
            url: '<?php echo base_url(); ?>exchange_rates/delete/' + id,
            type: 'POST',
            dataType: 'text',
            success: function(response) {
                if (response === 'success') {
                    toastr.success('Exchange rate deleted successfully!', 'Success', {
                        timeOut: 3000,
                        closeButton: true
                    });
                    // Reload the table
                    $('#example1').DataTable().ajax.reload();
                } else {
                    toastr.error(response, 'Delete Failed', {
                        timeOut: 5000,
                        closeButton: true
                    });
                }
            },
            error: function() {
                toastr.error('An error occurred while deleting the exchange rate.', 'Error', {
                    timeOut: 5000,
                    closeButton: true
                });
            }
        });
    }

    function confirm_delete_single() {
        if (delete_rate_id) {
            // Close the modal first
            $('#delete_single_modal').modal('hide');
            
            // Show loading state
            toastr.info('Checking if exchange rate can be deleted...');
            
            $.ajax({
                url: base_url + 'exchange_rates/delete/' + delete_rate_id,
                type: 'GET',
                success: function(response) {
                    if (response == 'success') {
                        toastr.success('Exchange rate deleted successfully!');
                        $('#exchange_rates_table').DataTable().ajax.reload();
                    } else {
                        // Show error with longer duration for important messages
                        toastr.error(response, 'Cannot Delete Exchange Rate', {
                            timeOut: 8000,
                            extendedTimeOut: 2000,
                            closeButton: true
                        });
                    }
                },
                error: function() {
                    toastr.error('Error deleting exchange rate!');
                }
            });
            
            // Reset the ID
            delete_rate_id = null;
        }
    }

    
    function debug_rate(rate_id) {
        $.ajax({
            url: base_url + 'exchange_rates/debug_transactions/' + rate_id,
            type: 'GET',
            success: function(response) {
                var data = JSON.parse(response);
                console.log('Debug data for rate ' + rate_id + ':', data);
                alert('Debug info logged to console. Check browser console (F12) for details.');
            },
            error: function() {
                alert('Error getting debug info!');
            }
        });
    }

    // API Rate Functions
    function fetch_api_rates() {
        $('#api_rates_modal').modal('show');
        
        // Check internet connection when modal opens
        check_internet_connection();
        
        // Wait for modal to be fully shown, then initialize datepicker
        $('#api_rates_modal').on('shown.bs.modal', function() {
            // Set today's date as default
            var today = new Date();
            var todayString = today.getFullYear() + '-' + 
                             String(today.getMonth() + 1).padStart(2, '0') + '-' + 
                             String(today.getDate()).padStart(2, '0');
            $('#api_effective_date').val(todayString);
            
            // Destroy any existing datepicker to avoid conflicts
            $('#api_effective_date').datepicker('destroy');
            
            // Initialize datepicker with specific settings
        $('#api_effective_date').datepicker({
            format: 'yyyy-mm-dd',
            autoclose: true,
            todayHighlight: true,
            orientation: 'bottom auto',
            todayBtn: 'linked',
            clearBtn: true,
            startDate: '1900-01-01',
                endDate: '2100-12-31',
                weekStart: 1,
                todayHighlight: true
            });
            
            // Set the date after initialization
            $('#api_effective_date').datepicker('setDate', today);
            
            // Initialize expiry date picker
            $('#api_expiry_date').datepicker('destroy');
            $('#api_expiry_date').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayHighlight: true,
                orientation: 'bottom auto',
                todayBtn: 'linked',
                clearBtn: true,
                startDate: '1900-01-01',
                endDate: '2100-12-31',
                weekStart: 1
            });
        });
    }

    function check_internet_connection() {
        $.ajax({
            url: base_url + 'exchange_rates/check_internet_connection',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.connected) {
                    $('#internet_status').html('<span class="text-success"><i class="fa fa-check"></i> Internet connection available</span>');
                    $('#fetch_api_btn').prop('disabled', false);
                } else {
                    $('#internet_status').html('<span class="text-danger"><i class="fa fa-times"></i> No internet connection. Please check your connection and try again.</span>');
                    $('#fetch_api_btn').prop('disabled', true);
                    toastr.warning('Internet connection required to fetch rates via API. Please check your internet connection and try again.', 'No Internet Connection', {
                        timeOut: 8000,
                        extendedTimeOut: 2000,
                        closeButton: true
                    });
                }
            },
            error: function() {
                $('#internet_status').html('<span class="text-danger"><i class="fa fa-times"></i> Unable to check internet connection</span>');
                $('#fetch_api_btn').prop('disabled', true);
            }
        });
    }

    function preview_api_rate() {
        var from_currency_id = $('#api_from_currency').val();
        var to_currency_id = $('#api_to_currency').val();
        var date = $('#api_effective_date').val();
        
        if (!from_currency_id) {
            toastr.error('Please select a from currency');
            return;
        }
        
        if (!to_currency_id) {
            toastr.error('Please select a to currency');
            return;
        }
        
        if (from_currency_id == to_currency_id) {
            toastr.error('From and To currencies cannot be the same');
            return;
        }
        
        if (!date) {
            toastr.error('Please select an effective date');
            return;
        }
        
        $('#fetch_api_btn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Fetching...');
        
        $.ajax({
            url: base_url + 'exchange_rates/fetch_single_api_rate',
            type: 'POST',
            data: {
                from_currency_id: from_currency_id,
                to_currency_id: to_currency_id,
                date: date,
                preview_only: true
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    display_api_rate_preview(response);
                    $('#api_rate_preview').show();
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error fetching rate from API');
            },
            complete: function() {
                $('#fetch_api_btn').prop('disabled', false).html('<i class="fa fa-cloud-download"></i> Fetch & Save Rate');
            }
        });
    }

    function display_api_rate_preview(response) {
        var html = '<div class="row">';
        html += '<div class="col-md-6"><strong>From:</strong> ' + response.from_currency_name + ' (' + response.from_currency_code + ')</div>';
        html += '<div class="col-md-6"><strong>To:</strong> ' + response.to_currency_name + ' (' + response.to_currency_code + ')</div>';
        html += '</div>';
        html += '<div class="row" style="margin-top: 10px;">';
        html += '<div class="col-md-6"><strong>Exchange Rate:</strong> <span class="text-primary" style="font-size: 18px;">' + parseFloat(response.rate).toFixed(6) + '</span></div>';
        html += '<div class="col-md-6"><strong>Source:</strong> <span class="label label-info">API</span></div>';
        html += '</div>';
        html += '<div class="row" style="margin-top: 10px;">';
        html += '<div class="col-md-12"><strong>Effective Date:</strong> ' + response.date + '</div>';
        html += '</div>';
        
        $('#api_rate_details').html(html);
    }

    // Handle API rates form submission
    $('#api_rates_form').on('submit', function(e) {
        e.preventDefault();
        
        var from_currency_id = $('#api_from_currency').val();
        var to_currency_id = $('#api_to_currency').val();
        var date = $('#api_effective_date').val();
        var expiry_date = $('#api_expiry_date').val();
        
        if (!from_currency_id) {
            toastr.error('Please select a from currency');
            return;
        }
        
        if (!to_currency_id) {
            toastr.error('Please select a to currency');
            return;
        }
        
        if (from_currency_id == to_currency_id) {
            toastr.error('From and To currencies cannot be the same');
            return;
        }
        
        if (!date) {
            toastr.error('Please select an effective date');
            return;
        }
        
        $('#fetch_api_btn').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Fetching & Saving...');
        
        // Check if bidirectional creation is enabled
        var createBidirectional = $('#api_create_bidirectional').is(':checked');
        
        $.ajax({
            url: base_url + 'exchange_rates/fetch_single_api_rate',
            type: 'POST',
            data: {
                from_currency_id: from_currency_id,
                to_currency_id: to_currency_id,
                date: date,
                expiry_date: expiry_date,
                create_bidirectional: createBidirectional
            },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    toastr.success(response.message);
                    $('#api_rates_modal').modal('hide');
                    $('#exchange_rates_table').DataTable().ajax.reload();
                } else {
                    toastr.error(response.message);
                }
            },
            error: function() {
                toastr.error('Error fetching rate from API');
            },
            complete: function() {
                $('#fetch_api_btn').prop('disabled', false).html('<i class="fa fa-cloud-download"></i> Fetch & Save Rate');
            }
        });
    });
    
    // Clean unused exchange rates
    function clean_unused_rates() {
        $('#clean_unused_modal').modal('show');
    }

    function proceedCleanUnused() {
        var confirmText = $('#confirmCleanText').val();
        if (confirmText === 'CLEAN') {
            $('#clean_unused_modal').modal('hide');
            
            // Show loading state
            toastr.info('Cleaning unused exchange rates...');
            
            $.ajax({
                url: base_url + 'exchange_rates/clean_unused_rates',
                type: 'POST',
                data: {
                    '<?php echo $this->security->get_csrf_token_name(); ?>': '<?php echo $this->security->get_csrf_hash(); ?>'
                },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        toastr.success(response.message, 'Success', {
                            timeOut: 5000,
                            closeButton: true
                        });
                        // Reload the table to show updated data
                        $('#exchange_rates_table').DataTable().ajax.reload();
                    } else {
                        toastr.error(response.message, 'Error', {
                            timeOut: 5000,
                            closeButton: true
                        });
                    }
                },
                error: function() {
                    toastr.error('Error cleaning unused exchange rates. Please try again.', 'Error', {
                        timeOut: 5000,
                        closeButton: true
                    });
                }
            });
        } else {
            toastr.warning('You must type "CLEAN" to confirm the action.', 'Invalid Confirmation');
        }
    }

    // Initialize on page load
    $(document).ready(function() {
        // Enable/disable clean confirm button based on text input
        $('#confirmCleanText').on('input', function() {
            if ($(this).val() === 'CLEAN') {
                $('#confirmCleanBtn').prop('disabled', false);
            } else {
                $('#confirmCleanBtn').prop('disabled', true);
            }
        });
        
        // Reset form when clean modal is closed
        $('#clean_unused_modal').on('hidden.bs.modal', function() {
            $('#confirmCleanText').val('');
            $('#confirmCleanBtn').prop('disabled', true);
        });
    });
    </script>
</body>
</html>
