<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<style>
.fin-card { border-radius:8px; padding:18px 20px; color:#fff; margin-bottom:12px; position:relative; overflow:hidden; }
.fin-card .val { font-size:24px; font-weight:700; margin:6px 0 2px; }
.fin-card .lbl { font-size:12px; opacity:.85; text-transform:uppercase; letter-spacing:.5px; }
.fin-card .ico { position:absolute; right:16px; top:50%; transform:translateY(-50%); font-size:42px; opacity:.2; }
.fin-card.verde  { background:linear-gradient(135deg,#1D6B3B,#28a745); }
.fin-card.azul   { background:linear-gradient(135deg,#1F4E79,#2E75B6); }
.fin-card.laranja { background:linear-gradient(135deg,#C55A11,#e67e22); }
.fin-card.vermelho{ background:linear-gradient(135deg,#C00000,#e74c3c); }
.appt-item { padding:10px 14px; border-left:4px solid #2E75B6; margin-bottom:8px; background:#f8f9fa; border-radius:0 6px 6px 0; }
.appt-item.hoje  { border-color:#28a745; background:#f0fff4; }
.appt-item.passado { border-color:#e74c3c; background:#fff5f5; opacity:.8; }
.appt-item .appt-time { font-size:12px; color:#888; }
.appt-item .appt-title { font-weight:600; color:#333; font-size:14px; }
.appt-item .appt-client { font-size:12px; color:#666; }
.box-fin { box-shadow:0 2px 12px rgba(0,0,0,.08); }
</style>

<section class="content-header">
    <h1><i class="fa fa-dashboard"></i> <?php echo lang('dashboard')?> <small><?php echo date('d/m/Y')?></small></h1>
    <ol class="breadcrumb"><li class="active"><i class="fa fa-dashboard"></i> Dashboard</li></ol>
</section>

<section class="content">
<?php
$admin  = $this->session->userdata('admin');
$access = $admin['user_role'];
$fin    = $financeiro_mes ?? null;
?>

<?php if($access == 1): ?>
<!-- ── CONTADORES ─────────────────────────────────── -->
<?php if($access == 2): ?>
<div class="row">
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-aqua">
            <div class="inner"><h3><?php echo is_array($my_cases)?count($my_cases):0?></h3><p><?php echo lang('my_cases')?></p></div>
            <div class="icon"><i class="fa fa-list"></i></div>
            <a href="<?php echo site_url('admin/my_cases')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
</div>
<?php else: ?>
<div class="row">
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-aqua">
            <div class="inner"><h3><?php echo (is_array($clients)?count($clients):0)?></h3><p><?php echo lang('clients')?></p></div>
            <div class="icon"><i class="fa fa-users"></i></div>
            <a href="<?php echo site_url('admin/clients')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-green">
            <div class="inner"><h3><?php echo (is_array($case_all)?count($case_all):0)?></h3><p><?php echo lang('cases')?></p></div>
            <div class="icon"><i class="fa fa-list"></i></div>
            <a href="<?php echo site_url('admin/cases')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-yellow">
            <div class="inner"><h3><?php echo (is_array($starred)?count($starred):0)?></h3><p><?php echo lang('starred_cases')?></p></div>
            <div class="icon"><i class="fa fa-star"></i></div>
            <a href="<?php echo site_url('admin/cases/starred_cases')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-red">
            <div class="inner"><h3><?php echo (is_array($archived)?count($archived):0)?></h3><p><?php echo lang('archived_cases')?></p></div>
            <div class="icon"><i class="fa fa-archive"></i></div>
            <a href="<?php echo site_url('admin/cases/archived_cases')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-blue">
            <div class="inner"><h3><?php echo (is_array($employees)?count($employees):0)?></h3><p><?php echo lang('employees')?></p></div>
            <div class="icon"><i class="fa fa-users"></i></div>
            <a href="<?php echo site_url('admin/employees')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-red">
            <div class="inner"><h3><?php echo (is_array($tasks)?count($tasks):0)?></h3><p><?php echo lang('tasks')?></p></div>
            <div class="icon"><i class="fa fa-tasks"></i></div>
            <a href="<?php echo site_url('admin/tasks')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-light-blue-gradient">
            <div class="inner"><h3><?php echo (is_array($to_do_list)?count($to_do_list):0)?></h3><p><?php echo lang('to_do_list')?></p></div>
            <div class="icon"><i class="fa fa-book"></i></div>
            <a href="<?php echo site_url('admin/to_do_list')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
    <div class="col-lg-3 col-xs-6">
        <div class="small-box bg-aqua">
            <div class="inner"><h3><?php echo (is_array($my_tasks)?count($my_tasks):0)?></h3><p><?php echo lang('my_tasks')?></p></div>
            <div class="icon"><i class="fa fa-inbox"></i></div>
            <a href="<?php echo site_url('admin/tasks/my_tasks')?>" class="small-box-footer"><?php echo lang('more_info')?> <i class="fa fa-arrow-circle-right"></i></a>
        </div>
    </div>
</div>
<?php endif; ?>

<!-- ── QUADROS: TODAY CASES + TO DO + NOTICE ─────── -->
<div class="row">
<?php if(check_user_role(105)==1): ?>
<section class="col-lg-6 connectedSortable">
    <div class="box box-primary">
        <div class="box-header with-border"><i class="ion ion-clipboard"></i><h3 class="box-title"><?php echo lang('todays_cases')?></h3></div>
        <div class="box-body">
            <ul class="todo-list">
            <?php if(isset($cases)) foreach($cases as $new): ?>
            <li>
                <span class="handle"><i class="fa fa-ellipsis-v"></i><i class="fa fa-ellipsis-v"></i></span>
                <span class="text"><a href="<?php echo site_url('admin/cases/dates/'.$new->case_id)?>"><?php echo $new->case_no." - ".$new->title?></a></span>
            </li>
            <?php endforeach; ?>
            </ul>
        </div>
        <div class="box-footer clearfix no-border">
            <a href="<?php echo site_url('admin/cases/view_all')?>" class="btn btn-default pull-right btn-sm"><i class="fa fa-plus"></i> <?php echo lang('view_all')?></a>
        </div>
    </div>
</section>
<?php endif; ?>

<?php if(check_user_role(107)==1): ?>
<section class="col-lg-6 connectedSortable">
    <div class="box box-primary">
        <div class="box-header with-border"><i class="fa fa-tasks"></i><h3 class="box-title"><?php echo lang('todays_to_do')?></h3></div>
        <div class="box-body">
            <ul class="todo-list">
            <?php if(isset($to_do)) foreach($to_do as $new): ?>
            <li>
                <span class="handle"><i class="fa fa-ellipsis-v"></i><i class="fa fa-ellipsis-v"></i></span>
                <span class="text"><a href="<?php echo site_url('admin/to_do_list')?>"><?php echo $new->title?></a></span>
            </li>
            <?php endforeach; ?>
            </ul>
        </div>
        <div class="box-footer clearfix no-border">
            <a href="<?php echo site_url('admin/to_do_list/view_all')?>" class="btn btn-default pull-right btn-sm"><i class="fa fa-plus"></i> <?php echo lang('view_all')?></a>
        </div>
    </div>
</section>
<?php endif; ?>

<section class="col-lg-6 connectedSortable">
    <div class="box box-primary">
        <div class="box-header with-border"><i class="ion ion-clipboard"></i><h3 class="box-title"><?php echo lang('notice_board')?></h3></div>
        <div class="box-body">
            <ul class="todo-list">
            <?php if(isset($notice)) foreach($notice as $new): ?>
            <li>
                <span class="label label-info"><i class="fa fa-clock-o"></i> <?php echo date_time_convert($new->date_time)?></span>
                <span class="text"><?php echo $new->title?></span>
                <div class="tools"><a href="<?php echo site_url('admin/notice/view/'.$new->id)?>"><i class="fa fa-eye"></i></a></div>
            </li>
            <?php endforeach; ?>
            </ul>
        </div>
        <div class="box-footer clearfix no-border">
            <a href="<?php echo site_url('admin/notice/')?>" class="btn btn-default pull-right btn-sm"><i class="fa fa-plus"></i> <?php echo lang('view_all')?></a>
        </div>
    </div>
</section>
</div>


<section class="col-lg-6 connectedSortable">
    <div class="box box-primary">
        <div class="box-header"><h3 class="box-title"><?php echo lang('today_employees_on_leave')?></h3></div>
        <div class="box-body">
            <ul class="todo-list">
            <?php foreach((array)$todays_leaves as $new): ?>
            <li>
                <span class="text"><?php echo $new->user?></span>
                <span class="label label-success"><?php echo $new->leave_type?></span>
            </li>
            <?php endforeach; ?>
            </ul>
        </div>
    </div>
</section>
</div>

<div class="row">
<section class="col-lg-6">
    <div class="box box-primary">
        <div class="box-header">
            <h3 class="box-title"><?php echo lang('attendance')?></h3>
            <div class="box-tools pull-right">
                <a href="#apply_leave" class="btn bg-purple btn-flat btn-sm" data-toggle="modal"><i class="fa fa-arrow-circle-up"></i> <?php echo lang('apply_leave')?></a>
            </div>
        </div>
        <div class="box-body">
            <?php if(empty($check_today)): ?>
                <?php if(!empty($att_status)): ?>
                    <?php if($att_status->current_status == NULL || $att_status->current_status == 0): ?>
                    <a href="#mark_in" class="btn bg-olive btn-flat" data-toggle="modal"><i class="fa fa-sign-in"></i> <?php echo lang('mark_in')?></a>
                    <?php else: ?>
                    <a href="#mark_out" class="btn bg-orange btn-flat" data-toggle="modal"><i class="fa fa-sign-out"></i> <?php echo lang('mark_out')?></a>
                    <?php endif; ?>
                <?php else: ?>
                <a href="#mark_in" class="btn bg-olive btn-flat" data-toggle="modal"><i class="fa fa-sign-in"></i> <?php echo lang('mark_in')?></a>
                <?php endif; ?>
            <?php else: ?>
            <button class="btn bg-maroon btn-flat">Today is <?php echo $check_today->leave_type?></button>
            <?php endif; ?>
        </div>
        <div class="box-footer clearfix no-border">
								 <?php //if(check_user_role(135)==1){?>	
                                    <a href="<?php echo site_url('admin/attendance/my_attendance');?>" style="padding-right:7px" class="btn btn-default"><i class="fa fa-user"></i> <?php echo lang('my_attendance')?></a>
								<?php //} ?>	
									<?php //if(check_user_role(136)==1){?>	
									<a href="<?php echo site_url('admin/attendance/my_leaves');?>"  class="btn btn-default pull-right"><i class="fa fa-plus"></i> <?php echo lang('my_leaves')?></a>	
									<?php //} ?>	
                                </div>
    </div>
</section>
</div>




<!-- ── CARDS FINANCEIROS ───────────────────────────── -->
<div class="row">
    <div class="col-md-3 col-sm-6">
        <div class="fin-card verde">
            <div class="lbl">Recebido no Mês</div>
            <div class="val">R$ <?php echo number_format($fin->recebido??0,2,',','.')?></div>
            <i class="fa fa-arrow-down ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?status=pago')?>" style="color:rgba(255,255,255,.8);font-size:11px">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="fin-card azul">
            <div class="lbl">A Receber no Mês</div>
            <div class="val">R$ <?php echo number_format($fin->a_receber??0,2,',','.')?></div>
            <i class="fa fa-clock-o ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/receber?status=pendente')?>" style="color:rgba(255,255,255,.8);font-size:11px">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="fin-card laranja">
            <div class="lbl">Pago no Mês</div>
            <div class="val">R$ <?php echo number_format($fin->pago??0,2,',','.')?></div>
            <i class="fa fa-arrow-up ico"></i>
            <a href="<?php echo site_url('admin/financeiro/lancamentos/pagar?status=pago')?>" style="color:rgba(255,255,255,.8);font-size:11px">Ver detalhes →</a>
        </div>
    </div>
    <div class="col-md-3 col-sm-6">
        <div class="fin-card vermelho">
            <div class="lbl">Vencido sem Baixa</div>
            <div class="val">R$ <?php echo number_format($fin->vencido??0,2,',','.')?></div>
            <i class="fa fa-exclamation-triangle ico"></i>
            <a href="<?php echo site_url('admin/financeiro')?>" style="color:rgba(255,255,255,.8);font-size:11px">Ver todos →</a>
        </div>
    </div>
</div>

<!-- ── GRÁFICO FINANCEIRO + AGENDA ────────────────── -->
<div class="row">
    <!-- Gráfico -->
    <div class="col-md-8">
        <div class="box box-fin">
            <div class="box-header with-border">
                <h3 class="box-title"><i class="fa fa-bar-chart text-blue"></i> Financeiro — Últimos 6 Meses</h3>
                <div class="box-tools pull-right">
                    <a href="<?php echo site_url('admin/financeiro/relatorio')?>" class="btn btn-xs btn-default">
                        <i class="fa fa-external-link"></i> Relatório completo
                    </a>
                </div>
            </div>
            <div class="box-body">
                <canvas id="chart-financeiro" height="280"></canvas>
            </div>
        </div>
    </div>

    <!-- Agenda -->
    <div class="col-md-4">
        <div class="box box-fin">
            <div class="box-header with-border" style="background:#1F4E79;color:#fff">
                <h3 class="box-title" style="color:#fff"><i class="fa fa-calendar"></i> Próximos Agendamentos</h3>
                <div class="box-tools pull-right">
                    <a href="<?php echo site_url('admin/appointments')?>" class="btn btn-xs" style="background:rgba(255,255,255,.2);color:#fff">Ver todos</a>
                </div>
            </div>
            <div class="box-body" style="padding:12px;max-height:320px;overflow-y:auto">
                <?php if(empty($upcoming_appointments)): ?>
                <div class="text-center text-muted" style="padding:20px">
                    <i class="fa fa-calendar-o" style="font-size:32px;opacity:.3"></i>
                    <p>Nenhum agendamento próximo</p>
                    <a href="<?php echo site_url('admin/appointments/add')?>" class="btn btn-xs btn-primary">
                        <i class="fa fa-plus"></i> Novo agendamento
                    </a>
                </div>
                <?php else: ?>
                <?php foreach($upcoming_appointments as $a):
                    $dt = strtotime($a->date_time);
                    $hoje = date('Y-m-d') === date('Y-m-d', $dt);
                    $passado = $dt < time();
                    $cls = $hoje ? 'hoje' : ($passado ? 'passado' : '');
                ?>
                <div class="appt-item <?php echo $cls?>">
                    <div class="appt-time">
                        <i class="fa fa-clock-o"></i>
                        <?php echo date('d/m', $dt)?> às <?php echo date('H:i', $dt)?>
                        <?php if($hoje): ?><span class="label label-success" style="font-size:10px">Hoje</span><?php endif; ?>
                    </div>
                    <div class="appt-title"><?php echo htmlspecialchars($a->title)?></div>
                    <?php if(!empty($a->client_nome)): ?>
                    <div class="appt-client"><i class="fa fa-user"></i> <?php echo htmlspecialchars($a->client_nome)?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <div style="text-align:center;margin-top:10px">
                    <a href="<?php echo site_url('admin/appointments/add')?>" class="btn btn-xs btn-success">
                        <i class="fa fa-plus"></i> Novo agendamento
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; // access == 1 ?>


    <!-- Diligências -->
    <div class="col-md-4">
        <div class="box box-fin">
            <div class="box-header with-border" style="background:#7F6000;color:#fff">
                <h3 class="box-title" style="color:#fff"><i class="fa fa-gavel"></i> Próximas Diligências</h3>
                <div class="box-tools pull-right">
                    <a href="<?php echo site_url('admin/diligencias')?>" class="btn btn-xs" style="background:rgba(255,255,255,.2);color:#fff">Ver todas</a>
                </div>
            </div>
            <div class="box-body" style="padding:12px;max-height:320px;overflow-y:auto">
                <?php if(empty($proximas_diligencias)): ?>
                <div class="text-center text-muted" style="padding:20px">
                    <i class="fa fa-gavel" style="font-size:32px;opacity:.3"></i>
                    <p>Nenhuma diligência próxima</p>
                    <a href="<?php echo site_url('admin/diligencias/add')?>" class="btn btn-xs btn-warning">
                        <i class="fa fa-plus"></i> Nova diligência
                    </a>
                </div>
                <?php else: ?>
                <?php foreach($proximas_diligencias as $d):
                    $dt = strtotime($d->data_hora);
                    $hoje = date('Y-m-d') === date('Y-m-d', $dt);
                ?>
                <div class="appt-item <?php echo $hoje?'hoje':''?>" style="border-left-color:#C55A11">
                    <div class="appt-time">
                        <i class="fa fa-clock-o"></i>
                        <?php echo date('d/m', $dt)?> às <?php echo date('H:i', $dt)?>
                        <?php if($hoje): ?><span class="label label-warning" style="font-size:10px">Hoje</span><?php endif; ?>
                        <span class="label label-info" style="font-size:10px"><?php echo ucfirst($d->tipo??'')?></span>
                    </div>
                    <div class="appt-title"><?php echo htmlspecialchars($d->titulo)?></div>
                    <?php if(!empty($d->case_no)): ?>
                    <div class="appt-client"><i class="fa fa-folder"></i> <?php echo htmlspecialchars($d->case_no)?></div>
                    <?php endif; ?>
                    <?php if(!empty($d->local)): ?>
                    <div class="appt-client"><i class="fa fa-map-marker"></i> <?php echo htmlspecialchars($d->local)?></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
                <div style="text-align:center;margin-top:10px">
                    <a href="<?php echo site_url('admin/diligencias/add')?>" class="btn btn-xs btn-warning">
                        <i class="fa fa-plus"></i> Nova diligência
                    </a>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<!-- ── GOOGLE CALENDAR ────────────────────────────── -->
<div class="row">
    <div class="col-md-9">
        <div class="box box-primary">
            <div class="box-body no-padding">
                <iframe src="https://calendar.google.com/calendar/embed?src=agendaadvbp%40gmail.com&ctz=America%2FRecife" style="border:0" width="100%" height="500" frameborder="0" scrolling="no"></iframe>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="box box-primary">
            <div class="box-body">
                <h2><?php echo lang('events')?></h2>
                <div class="external-event bg-red ui-draggable-handle"><?php echo lang('cases')?></div>
                
                <div class="external-event ui-draggable-handle" style="background:#0073b7;color:#fff"><?php echo lang('appointments')?></div>
                
                
                
                
                
            </div>
        </div>
    </div>
</div>

</section>

<!-- ── CHART.JS ───────────────────────────────────── -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js"></script>
<script>
<?php
$labels   = [];
$recebido = [];
$a_receber= [];
$pago     = [];
foreach((array)$financeiro_chart as $row) {
    $labels[]    = $row->mes_label;
    $recebido[]  = (float)$row->recebido;
    $a_receber[] = (float)$row->a_receber;
    $pago[]      = (float)$row->pago;
}
?>
var ctx = document.getElementById('chart-financeiro');
if(ctx) {
    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: <?php echo json_encode($labels)?>,
            datasets: [
                {
                    label: 'Recebido',
                    data: <?php echo json_encode($recebido)?>,
                    backgroundColor: 'rgba(29,107,59,0.8)',
                    borderColor: '#1D6B3B',
                    borderWidth: 1,
                    borderRadius: 4,
                },
                {
                    label: 'A Receber',
                    data: <?php echo json_encode($a_receber)?>,
                    backgroundColor: 'rgba(46,117,182,0.6)',
                    borderColor: '#2E75B6',
                    borderWidth: 1,
                    borderRadius: 4,
                },
                {
                    label: 'Pago (Despesas)',
                    data: <?php echo json_encode($pago)?>,
                    backgroundColor: 'rgba(197,90,17,0.7)',
                    borderColor: '#C55A11',
                    borderWidth: 1,
                    borderRadius: 4,
                },
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'top' },
                tooltip: {
                    callbacks: {
                        label: function(ctx) {
                            return ctx.dataset.label + ': R$ ' +
                                ctx.parsed.y.toLocaleString('pt-BR',{minimumFractionDigits:2});
                        }
                    }
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        callback: function(val) {
                            return 'R$ ' + val.toLocaleString('pt-BR',{minimumFractionDigits:0});
                        }
                    }
                }
            }
        }
    });
}
</script>

<?php
// Attendance modals (mantidos do original)
$modal_ids = ['mark_in','mark_out','apply_leave','myModal'];
foreach($modal_ids as $mid):
?>
<?php endforeach; ?>
