<?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/jquery.datetimepicker.css') ?>" rel="stylesheet">
<style>
.form-group label { font-size:11px; font-weight:700; color:#888; text-transform:uppercase; letter-spacing:.5px; margin-bottom:5px; display:block; }
.gender-opt { display:inline-flex; align-items:center; gap:5px; margin-right:18px; font-weight:400; font-size:13px; }
.section-title { font-size:13px; font-weight:700; color:#1e3a5f; margin:20px 0 14px; padding-bottom:6px; border-bottom:2px solid #e8f0fb; }
.section-title .fa { margin-right:6px; }
</style>

<section class="content-header">
    <h1><i class="fa fa-folder-open"></i> <?php echo lang('case') ?> <small><?php echo lang('edit') ?></small></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('edit') ?></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; ?>

<div class="box box-primary">
    <div class="box-header with-border" style="background:linear-gradient(135deg,#1e3a5f,#2e75b6);border-radius:10px 10px 0 0">
        <h3 class="box-title" style="color:#fff"><i class="fa fa-pencil"></i> Editar Processo</h3>
    </div>
    <?php echo form_open_multipart('admin/cases/edit/'.$id) ?>
    <div class="box-body">

        <!-- BLOCO 1: Identificação -->
        <div class="section-title"><i class="fa fa-info-circle"></i> Identificação</div>
        <div class="row">
            <div class="col-md-8">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('title') ?></label>
                    <input type="text" name="title" value="<?php echo htmlspecialchars($case->title ?? '') ?>" class="form-control" required>
                </div>
            </div>
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('number') ?></label>
                    <input type="text" name="case_no" value="<?php echo htmlspecialchars($case->case_no ?? '') ?>" class="form-control">
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('client') ?> <?php echo lang('name') ?></label>
                    <select name="client_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('client') ?> --</option>
                        <?php foreach($clients as $new):
                            $sel = ($new->id == ($case->client_id ?? 0)) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('stage') ?></label>
                    <select name="case_stage_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> <?php echo lang('stage') ?> --</option>
                        <?php foreach($stages as $new):
                            $sel = ($new->id == ($case->case_stage_id ?? 0)) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 2: Tribunal -->
        <div class="section-title"><i class="fa fa-university"></i> Tribunal</div>
        <div class="row">
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo lang('location') ?></label>
                    <select name="location_id" id="location_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> --</option>
                        <?php foreach($locations as $new):
                            $sel = ($new->id == ($case->location_id ?? 0)) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4" id="court_category_result">
                <div class="form-group">
                    <label><?php echo lang('court') ?> <?php echo lang('category') ?></label>
                    <select name="court_category_id" id="court_category_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> --</option>
                        <?php foreach($court_categories as $new):
                            $sel = ($new->id == ($case->court_category_id ?? 0)) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-4" id="court_result">
                <div class="form-group">
                    <label><?php echo lang('court') ?></label>
                    <select name="court_id" id="court_id" class="form-control chzn">
                        <option value="">-- <?php echo lang('select') ?> --</option>
                        <?php foreach($courts as $new):
                            $sel = ($new->id == ($case->court_id ?? 0)) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 3: Classificação -->
        <div class="section-title"><i class="fa fa-tags"></i> Classificação</div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('case') ?> <?php echo lang('category') ?></label>
                    <select name="case_category_id[]" class="form-control chzn" multiple="multiple" data-placeholder="Selecione categorias...">
                        <?php
                        $cats_sel = @json_decode($case->case_category_id ?? '[]', true) ?: [];
                        foreach($case_categories as $new):
                            $sel = in_array($new->id, $cats_sel) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->name) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label><?php echo lang('act') ?></label>
                    <select name="act_id[]" class="form-control chzn" multiple="multiple" data-placeholder="Selecione legislações...">
                        <?php
                        $acts_sel = @json_decode($case->act_id ?? '[]', true) ?: [];
                        foreach($acts as $new):
                            $sel = in_array($new->id, $acts_sel) ? 'selected' : '';
                        ?>
                        <option value="<?php echo $new->id ?>" <?php echo $sel ?>><?php echo htmlspecialchars($new->title) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>

        <!-- BLOCO 4: Datas e Valores -->
        <div class="section-title"><i class="fa fa-calendar"></i> Datas e Valores</div>
        <div class="row">
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('filling_date') ?></label>
                    <input type="text" name="start_date" value="<?php echo $case->start_date ?? '' ?>" class="form-control datepicker" placeholder="AAAA-MM-DD">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('hearing_date') ?></label>
                    <input type="text" name="hearing_date" value="<?php echo $case->hearing_date ?? '' ?>" class="form-control datepicker" placeholder="AAAA-MM-DD">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('opposite_lawyer') ?></label>
                    <input type="text" name="o_lawyer" value="<?php echo htmlspecialchars($case->o_lawyer ?? '') ?>" class="form-control">
                </div>
            </div>
            <div class="col-md-3">
                <div class="form-group">
                    <label><?php echo lang('total_fees') ?></label>
                    <input type="text" name="fees" value="<?php echo htmlspecialchars($case->fees ?? '') ?>" class="form-control">
                </div>
            </div>
        </div>

        <!-- Descrição -->
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label><?php echo lang('description') ?></label>
                    <textarea name="description" class="form-control" rows="4"><?php echo htmlspecialchars($case->description ?? '') ?></textarea>
                </div>
            </div>
        </div>

        <!-- BLOCO 5: Campos personalizados -->
        <?php
        $CI = get_instance();
        if(!empty($fields)):
        ?>
        <div class="section-title"><i class="fa fa-list-alt"></i> Informações Adicionais</div>
        <div class="row">
        <?php foreach($fields as $doc):
            $result = $CI->db->query("SELECT * FROM rel_form_custom_fields WHERE custom_field_id='".$doc->id."' AND table_id='".$case->id."' AND form='".$doc->form."'")->row();
            $reply  = $result->reply ?? '';
            $values = explode(',', $doc->values ?? '');
        ?>
            <div class="col-md-4">
                <div class="form-group">
                    <label><?php echo htmlspecialchars($doc->name) ?></label>
                    <?php if($doc->field_type==1): ?>
                    <input type="text" class="form-control" name="reply[<?php echo $doc->id ?>]" value="<?php echo htmlspecialchars($reply) ?>">
                    <?php elseif($doc->field_type==2): ?>
                    <select name="reply[<?php echo $doc->id ?>]" class="form-control">
                        <?php foreach($values as $val): ?>
                        <option value="<?php echo trim($val) ?>" <?php echo trim($val)==$reply?'selected':'' ?>><?php echo trim($val) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <?php elseif($doc->field_type==3): ?>
                    <div style="padding-top:6px">
                        <?php foreach($values as $val): ?>
                        <label class="gender-opt"><input type="radio" name="reply[<?php echo $doc->id ?>]" value="<?php echo trim($val) ?>" <?php echo trim($val)==$reply?'checked':'' ?>> <?php echo trim($val) ?></label>
                        <?php endforeach; ?>
                    </div>
                    <?php elseif($doc->field_type==4): ?>
                    <div style="padding-top:6px">
                        <?php foreach($values as $val): ?>
                        <label class="gender-opt"><input type="checkbox" name="reply[<?php echo $doc->id ?>][]" value="<?php echo trim($val) ?>" <?php echo trim($val)==$reply?'checked':'' ?>> <?php echo trim($val) ?></label>
                        <?php endforeach; ?>
                    </div>
                    <?php elseif($doc->field_type==5): ?>
                    <textarea class="form-control" name="reply[<?php echo $doc->id ?>]" rows="2"><?php echo htmlspecialchars($reply) ?></textarea>
                    <?php elseif($doc->field_type==6): ?>
                    <input type="url" class="form-control" name="reply[<?php echo $doc->id ?>]" value="<?php echo htmlspecialchars($reply) ?>">
                    <?php elseif($doc->field_type==7): ?>
                    <input type="email" class="form-control" name="reply[<?php echo $doc->id ?>]" value="<?php echo htmlspecialchars($reply) ?>">
                    <?php elseif($doc->field_type==8): ?>
                    <input type="number" class="form-control" name="reply[<?php echo $doc->id ?>]" value="<?php echo htmlspecialchars($reply) ?>">
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
        </div>
        <?php endif; ?>

    </div>
    <div class="box-footer">
        <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> <?php echo lang('update') ?></button>
        <a href="<?php echo site_url('admin/cases/view_case/'.($case->id ?? '')) ?>" class="btn btn-default"><i class="fa fa-arrow-left"></i> Cancelar</a>
    </div>
    <?php echo form_close() ?>
</div>

</section>

<script src="<?php echo base_url('assets/js/chosen.jquery.min.js') ?>"></script>
<script src="<?php echo base_url('assets/js/jquery.datetimepicker.js') ?>"></script>
<script>
$(function() {
    $('.chzn').chosen({ width:'100%' });
    $('.datepicker').datetimepicker({ timepicker:false, format:'Y-m-d' });

    $(document).on('change', '#location_id', function() {
        var vch = $(this).val();
        $('#court_category_result').html('<img src="<?php echo base_url('assets/img/ajax-loader.gif') ?>" style="margin:8px 0">');
        $.ajax({
            url: '<?php echo site_url('admin/cases/get_court_categories') ?>',
            type: 'POST', data: { id: vch },
            success: function(result) {
                $('#court_category_result').html(result);
                $('.chzn').chosen({ width:'100%' });
            }
        });
    });

    $(document).on('change', '#court_category_id', function() {
        var l_id = $('#location_id').val();
        var c_id = $(this).val();
        $('#court_result').html('<img src="<?php echo base_url('assets/img/ajax-loader.gif') ?>" style="margin:8px 0">');
        $.ajax({
            url: '<?php echo site_url('admin/cases/get_courts') ?>',
            type: 'POST', data: { l_id: l_id, c_id: c_id },
            success: function(result) {
                $('#court_result').html(result);
                $('.chzn').chosen({ width:'100%' });
            }
        });
    });
});
</script>
