<?php $this->load->view('theme/header'); ?>

<div class="content-wrapper">
    <section class="content-header">
        <h1>
            <i class="fa fa-cogs"></i> <?php echo $page_title; ?>
        </h1>
        <ol class="breadcrumb">
            <li><a href="<?php echo base_url(); ?>"><i class="fa fa-dashboard"></i> Home</a></li>
            <li><a href="<?php echo base_url(); ?>accounts">Accounts</a></li>
            <li class="active">System Maintenance</li>
        </ol>
    </section>

    <section class="content">
        <div class="row">
            <!-- Exchange Rate Management -->
            <div class="col-md-6">
                <div class="box box-primary">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-exchange"></i> Exchange Rate Management</h3>
                    </div>
                    <div class="box-body">
                        <form id="exchange_rate_form">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>From Currency</label>
                                        <select class="form-control" id="from_currency_id" name="from_currency_id" required>
                                            <option value="">Select Currency</option>
                                            <?php foreach($currencies as $currency): ?>
                                                <option value="<?php echo $currency->id; ?>">
                                                    <?php echo $currency->currency_name . ' (' . $currency->currency_code . ')'; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>To Currency</label>
                                        <select class="form-control" id="to_currency_id" name="to_currency_id" required>
                                            <option value="">Select Currency</option>
                                            <?php foreach($currencies as $currency): ?>
                                                <option value="<?php echo $currency->id; ?>">
                                                    <?php echo $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>Exchange Rate</label>
                                        <input type="number" class="form-control" id="exchange_rate" name="exchange_rate" 
                                               step="0.000001" placeholder="e.g., 0.000285" required>
                                        <small class="help-block">Enter the rate (1 from_currency = ? to_currency)</small>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Effective Date</label>
                                        <input type="date" class="form-control" id="effective_date" name="effective_date" 
                                               value="<?php echo date('Y-m-d'); ?>">
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fa fa-save"></i> Update Exchange Rate
                                </button>
                                <button type="button" class="btn btn-info" id="load_rates_btn">
                                    <i class="fa fa-refresh"></i> Load Current Rates
                                </button>
                            </div>
                        </form>
                        
                        <div id="exchange_rate_result" style="margin-top: 15px;"></div>
                    </div>
                </div>
            </div>

            <!-- Account Balance Management -->
            <div class="col-md-6">
                <div class="box box-success">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-calculator"></i> Account Balance Management</h3>
                    </div>
                    <div class="box-body">
                        <p>Recalculate all account balances using the corrected expense transaction logic.</p>
                        <p><strong>Note:</strong> This will update all account balances in the database.</p>
                        
                        <div class="form-group">
                            <button type="button" class="btn btn-success" id="recalculate_balances_btn">
                                <i class="fa fa-calculator"></i> Recalculate All Balances
                            </button>
                        </div>
                        
                        <div id="balance_result" style="margin-top: 15px;"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Current Exchange Rates Display -->
        <div class="row">
            <div class="col-md-12">
                <div class="box box-info">
                    <div class="box-header with-border">
                        <h3 class="box-title"><i class="fa fa-list"></i> Current Exchange Rates</h3>
                    </div>
                    <div class="box-body">
                        <div id="rates_table_container">
                            <p>Click "Load Current Rates" to view existing exchange rates.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script type="text/javascript">
$(document).ready(function() {
    // Exchange rate form submission
    $('#exchange_rate_form').on('submit', function(e) {
        e.preventDefault();
        
        var formData = {
            from_currency_id: $('#from_currency_id').val(),
            to_currency_id: $('#to_currency_id').val(),
            exchange_rate: $('#exchange_rate').val(),
            effective_date: $('#effective_date').val()
        };
        
        if (!formData.from_currency_id || !formData.to_currency_id || !formData.exchange_rate) {
            $('#exchange_rate_result').html('<div class="alert alert-danger">Please fill in all required fields.</div>');
            return;
        }
        
        if (formData.from_currency_id == formData.to_currency_id) {
            $('#exchange_rate_result').html('<div class="alert alert-warning">From and To currencies cannot be the same.</div>');
            return;
        }
        
        $.ajax({
            url: '<?php echo base_url(); ?>accounts/update_exchange_rate',
            type: 'POST',
            data: formData,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#exchange_rate_result').html('<div class="alert alert-success">' + response.message + 
                        '<br>Rate: 1 ' + response.from_currency + ' = ' + response.exchange_rate + ' ' + response.to_currency + '</div>');
                    $('#exchange_rate_form')[0].reset();
                    $('#effective_date').val('<?php echo date('Y-m-d'); ?>');
                } else {
                    $('#exchange_rate_result').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#exchange_rate_result').html('<div class="alert alert-danger">Error updating exchange rate.</div>');
            }
        });
    });
    
    // Load current rates
    $('#load_rates_btn').on('click', function() {
        $.ajax({
            url: '<?php echo base_url(); ?>accounts/get_exchange_rates',
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    var html = '<table class="table table-striped table-bordered">';
                    html += '<thead><tr><th>From Currency</th><th>To Currency</th><th>Rate</th><th>Effective Date</th><th>Type</th></tr></thead>';
                    html += '<tbody>';
                    
                    if (response.rates.length > 0) {
                        $.each(response.rates, function(index, rate) {
                            html += '<tr>';
                            html += '<td>' + rate.from_name + ' (' + rate.from_code + ')</td>';
                            html += '<td>' + rate.to_name + ' (' + rate.to_code + ')</td>';
                            html += '<td>' + parseFloat(rate.exchange_rate).toFixed(6) + '</td>';
                            html += '<td>' + rate.effective_date + '</td>';
                            html += '<td>' + rate.rate_type + '</td>';
                            html += '</tr>';
                        });
                    } else {
                        html += '<tr><td colspan="5" class="text-center">No exchange rates found.</td></tr>';
                    }
                    
                    html += '</tbody></table>';
                    $('#rates_table_container').html(html);
                } else {
                    $('#rates_table_container').html('<div class="alert alert-danger">Error loading exchange rates.</div>');
                }
            },
            error: function() {
                $('#rates_table_container').html('<div class="alert alert-danger">Error loading exchange rates.</div>');
            }
        });
    });
    
    // Recalculate balances
    $('#recalculate_balances_btn').on('click', function() {
        if (!confirm('Are you sure you want to recalculate all account balances? This may take a moment.')) {
            return;
        }
        
        var $btn = $(this);
        $btn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Recalculating...');
        
        $.ajax({
            url: '<?php echo base_url(); ?>accounts/recalculate_balances',
            type: 'POST',
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('#balance_result').html('<div class="alert alert-success">' + response.message + 
                        '<br>Updated: ' + response.updated + ' accounts<br>Errors: ' + response.errors + ' accounts<br>Total: ' + response.total + ' accounts</div>');
                } else {
                    $('#balance_result').html('<div class="alert alert-danger">' + response.message + '</div>');
                }
            },
            error: function() {
                $('#balance_result').html('<div class="alert alert-danger">Error recalculating balances.</div>');
            },
            complete: function() {
                $btn.prop('disabled', false).html('<i class="fa fa-calculator"></i> Recalculate All Balances');
            }
        });
    });
});
</script>

<?php $this->load->view('theme/footer'); ?>
