<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<link href="<?php echo base_url('assets/css/chosen.css') ?>" rel="stylesheet">
<link href="<?php echo base_url('assets/css/datatables/dataTables.bootstrap.css') ?>" rel="stylesheet">
<link href="<?php echo base_url('assets/css/jquery.datetimepicker.css') ?>" rel="stylesheet">
<style>
.summary-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:0; }
.summary-item { padding:12px 16px; border-bottom:1px solid #f0f2f5; border-right:1px solid #f0f2f5; }
.summary-item:last-child { border-right:none; }
.summary-item .dl { font-size:10px; font-weight:700; color:#aaa; text-transform:uppercase; letter-spacing:.5px; display:block; margin-bottom:3px; }
.summary-item .dv { font-size:15px; font-weight:700; color:#1e3a5f; }
.tax-row { display:flex; gap:10px; align-items:center; margin-bottom:8px; }
@media(max-width:767px){ .summary-grid{grid-template-columns:1fr 1fr} }
</style>
<script>
function areyousure() { return confirm('<?php echo lang('are_you_sure') ?>'); }
</script>

<section class="content-header">
    <h1><i class="fa fa-money"></i> <?php echo lang('fees') ?></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo site_url('admin') ?>"><i class="fa fa-dashboard"></i> Dashboard</a></li>
        <li><a href="<?php echo site_url('admin/cases') ?>"><?php echo lang('cases') ?></a></li>
        <li class="active"><?php echo lang('fees') ?></li>
    </ol>
</section>

<section class="content">

<?php if(validation_errors()): ?>
<div class="alert alert-danger alert-dismissible">
    <button class="close" data-dismiss="alert">&times;</button>
    <i class="fa fa-ban"></i> <?php echo validation_errors() ?>
</div>
<?php endif; ?>

<?php
$total_rec = $this->db->query("SELECT SUM(amount) AS tot_rec FROM receipt WHERE case_id = '".$id."'")->row();
$tot = $total_rec->tot_rec ?? 0;
$due = ($case->fees ?? 0) - $tot;
?>

<!-- Resumo -->
<div class="box box-primary">
    <div class="box-body no-padding">
        <div class="summary-grid">
            <div class="summary-item">
                <span class="dl"><?php echo lang('case') ?> <?php echo lang('number') ?></span>
                <span class="dv" style="font-family:monospace;font-size:13px"><?php echo $case->case_no ?? '—' ?></span>
            </div>
            <div class="summary-item">
                <span class="dl"><?php echo lang('fees_agreed') ?></span>
                <span class="dv">R$ <?php echo number_format($case->fees ?? 0, 2, ',', '.') ?></span>
            </div>
            <div class="summary-item">
                <span class="dl"><?php echo lang('paid') ?></span>
                <span class="dv" style="color:#2e7d32">R$ <?php echo number_format($tot, 2, ',', '.') ?></span>
            </div>
            <div class="summary-item">
                <span class="dl">Saldo</span>
                <span class="dv" style="color:<?php echo $due>0?'#c0392b':'#2e7d32' ?>">R$ <?php echo number_format($due, 2, ',', '.') ?></span>
            </div>
        </div>
    </div>
</div>

<div class="nav-tabs-custom" style="border-radius:10px;box-shadow:0 1px 6px rgba(0,0,0,.07)">
    <ul class="nav nav-tabs">
        <li class="active"><a href="#tab-invoice" data-toggle="tab"><i class="fa fa-file-text-o"></i> <?php echo lang('invoice') ?></a></li>
        <li><a href="#tab-receipt" data-toggle="tab"><i class="fa fa-receipt"></i> <?php echo lang('receipt') ?></a></li>
    </ul>
    <div class="tab-content" style="padding:16px">

        <!-- TAB INVOICE -->
        <div class="tab-pane active" id="tab-invoice">

            <form method="post" action="<?php echo site_url('admin/cases/fees/'.$id) ?>" enctype="multipart/form-data" id="form-invoice">
                <input type="hidden" name="inr" id="inr" value="<?php echo $case->fees ?? 0 ?>">
                <input type="hidden" name="bal" id="bal" value="<?php echo @$fees_all[0]->bal ?>">

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase">Nº <?php echo lang('invoice') ?></label>
                            <input type="text" name="invoice_no" value="<?php echo $invoice_no ?? '' ?>" class="form-control" readonly>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('payment_mode') ?></label>
                            <select name="payment_mode_id" class="form-control chzn">
                                <option value="">-- <?php echo lang('select') ?> --</option>
                                <?php foreach($payment_modes as $new): ?>
                                <option value="<?php echo $new->id ?>"><?php echo htmlspecialchars($new->name) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('date') ?></label>
                            <input type="text" name="date" value="" class="form-control datepicker" placeholder="AAAA-MM-DD">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('amount') ?></label>
                            <input type="text" name="amount" value="" id="amount" class="form-control">
                        </div>
                    </div>
                </div>

                <div class="input_fields_wrap">
                    <div class="row tax-row">
                        <div class="col-md-3">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('tax') ?></label>
                        </div>
                        <div class="col-md-3">
                            <select name="tax_id[]" class="form-control tax" required id="tax1">
                                <option value="">-- <?php echo lang('select') ?> <?php echo lang('tax') ?> --</option>
                                <?php foreach($tax as $new): ?>
                                <option value="<?php echo $new->id ?>"><?php echo $new->name ?> — <?php echo $new->percent ?>%</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="row" style="margin-bottom:14px">
                    <div class="col-md-3 col-md-offset-3">
                        <button type="button" class="add_field_button btn btn-default btn-sm"><i class="fa fa-plus"></i> Adicionar Imposto</button>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('total') ?></label>
                            <input type="text" name="total" value="" class="form-control" id="total" readonly>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('save') ?></button>
            </form>

            <hr>

            <div class="table-responsive">
                <table id="example2" class="table table-hover">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?php echo lang('invoice') ?></th>
                            <th><?php echo lang('date') ?></th>
                            <th><?php echo lang('amount') ?></th>
                            <th><?php echo lang('payment_mode') ?></th>
                            <th style="width:160px"></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if(isset($fees_all)): $i=1; foreach($fees_all as $new): ?>
                    <tr>
                        <td><?php echo $i++ ?></td>
                        <td><strong><?php echo $new->invoice ?></strong></td>
                        <td><?php echo date_convert($new->date) ?></td>
                        <td>R$ <?php echo number_format($new->amount, 2, ',', '.') ?></td>
                        <td><?php echo htmlspecialchars($new->mode ?? '—') ?></td>
                        <td style="white-space:nowrap">
                            <?php if(check_user_role(108)==1): ?>
                            <a href="<?php echo site_url('admin/invoice/index/'.$new->id) ?>" class="btn btn-xs btn-default" title="<?php echo lang('invoice') ?>"><i class="fa fa-file-text-o"></i></a>
                            <?php endif; ?>
                            <?php if(check_user_role(166)==1): ?>
                            <a href="<?php echo site_url('admin/cases/delete_fees/'.$new->id) ?>" class="btn btn-xs btn-danger" onclick="return areyousure()" title="<?php echo lang('delete') ?>"><i class="fa fa-trash"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- TAB RECEIPT -->
        <div class="tab-pane" id="tab-receipt">

            <?php if($due > 0): ?>
            <form method="post" action="<?php echo site_url('admin/cases/receipt/'.$id) ?>" enctype="multipart/form-data">
                <input type="hidden" name="case_id" value="<?php echo $id ?>">

                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('invoice') ?></label>
                            <select name="fees_id" class="form-control" required>
                                <option value="">-- <?php echo lang('select') ?> <?php echo lang('invoice') ?> --</option>
                                <?php foreach($fees_all as $new): ?>
                                <option value="<?php echo $new->id ?>"><?php echo $new->invoice ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('date') ?></label>
                            <input type="text" name="r_date" value="" class="form-control datepicker" required placeholder="AAAA-MM-DD">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang('amount') ?></label>
                            <input type="text" name="r_amount" value="" id="r_amount" class="form-control" required>
                        </div>
                    </div>
                </div>

                <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('save') ?></button>
            </form>
            <hr>
            <?php endif; ?>

            <div class="table-responsive">
                <table id="example1" class="table table-hover">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?php echo lang('date') ?></th>
                            <th><?php echo lang('amount') ?></th>
                            <th style="width:160px"></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php if(isset($receipts)): $i=1; foreach($receipts as $new): ?>
                    <tr>
                        <td><?php echo $i++ ?></td>
                        <td><?php echo date_convert($new->date) ?></td>
                        <td>R$ <?php echo number_format($new->amount, 2, ',', '.') ?></td>
                        <td style="white-space:nowrap">
                            <?php if(check_user_role(167)==1): ?>
                            <a href="<?php echo site_url('admin/cases/view_receipt/'.$new->id) ?>" class="btn btn-xs btn-default" title="<?php echo lang('receipt') ?>"><i class="fa fa-receipt"></i></a>
                            <?php endif; ?>
                            <?php if(check_user_role(169)==1): ?>
                            <a href="<?php echo site_url('admin/cases/delete_deceipt/'.$new->id.'/'.$id) ?>" class="btn btn-xs btn-danger" onclick="return areyousure()" title="<?php echo lang('delete') ?>"><i class="fa fa-trash"></i></a>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

</section>

<script src="<?php echo base_url('assets/js/jquery.datetimepicker.js') ?>"></script>
<script src="<?php echo base_url('assets/js/chosen.jquery.min.js') ?>"></script>
<script src="<?php echo base_url('assets/js/plugins/datatables/jquery.dataTables.js') ?>"></script>
<script src="<?php echo base_url('assets/js/plugins/datatables/dataTables.bootstrap.js') ?>"></script>
<script>
$(function() {
    $('.chzn').chosen({ width: '100%' });
    $('#example1, #example2').dataTable({ language: { url: '//cdn.datatables.net/plug-ins/1.10.21/i18n/Portuguese-Brasil.json' } });

    jQuery('.datepicker').datetimepicker({ timepicker:false, format:'Y-m-d' });

    var wrapper = $('.input_fields_wrap');
    var x = 1, t = 1;
    var taxOptions = `<?php foreach($tax as $new): ?><option value="<?php echo $new->id ?>"><?php echo $new->name ?> — <?php echo $new->percent ?>%</option><?php endforeach; ?>`;

    $('.add_field_button').click(function(e) {
        e.preventDefault();
        if (x < 20) {
            x++; t++;
            wrapper.append(
                '<div class="row tax-row">' +
                '<div class="col-md-3"><label style="font-size:11px;font-weight:700;color:#888;text-transform:uppercase"><?php echo lang("tax") ?></label></div>' +
                '<div class="col-md-3"><select name="tax_id[]" class="form-control tax" required id="tax'+t+'"><option value="">-- <?php echo lang("select") ?> <?php echo lang("tax") ?> --</option>'+taxOptions+'</select></div>' +
                '<div class="col-md-2"><a href="#" class="remove_field btn btn-danger btn-sm"><i class="fa fa-trash"></i></a></div>' +
                '</div>'
            );
        }
    });
    wrapper.on('click', '.remove_field', function(e) {
        e.preventDefault();
        $(this).closest('.tax-row').remove();
        x--;
    });

    $(document).on('change', '.tax', function() {
        var amt = parseFloat($('#amount').val()) || 0;
        var totalPct = 0;
        $('.tax :selected').each(function() {
            var txt = $(this).text().split('—');
            if (txt[1]) totalPct += parseFloat(txt[1].replace('%','').trim()) || 0;
        });
        var taxValue = (totalPct/100) * amt;
        $('#total').val((amt + taxValue).toFixed(2));
    });

    $(document).on('focusout', '#amount', function() {
        var amt = parseFloat($(this).val()) || 0;
        if (!$(this).val()) { alert('<?php echo lang("amount") ?>'); $(this).focus(); }
        $('#total').val(amt.toFixed(2));
    });
});
</script>
