<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php
$money = function ($value) use ($currency_symbol) {
    return $currency_symbol . number_format((float) $value, 2);
};
$date_text = function ($value) {
    return !empty($value) ? date('M d, Y', strtotime($value)) : '--';
};

$invoiceMap = !empty($finance['invoice_status_map']) ? $finance['invoice_status_map'] : array();
$overdueTasks = !empty($overdue['tasks']) ? $overdue['tasks'] : array();
$overdueProjects = !empty($overdue['projects']) ? $overdue['projects'] : array();
$overdueInvoices = !empty($overdue['invoices']) ? $overdue['invoices'] : array();
$overdueTickets = !empty($overdue['tickets']) ? $overdue['tickets'] : array();
$recentActivities = array_slice(!empty($activity['recent_activities']) ? $activity['recent_activities'] : array(), 0, 5);
$recentProjects = array_slice(!empty($delivery['recent_projects']) ? $delivery['recent_projects'] : array(), 0, 4);
$recentTasks = array_slice(!empty($delivery['recent_tasks']) ? $delivery['recent_tasks'] : array(), 0, 4);
$recentOpportunities = array_slice(!empty($crm['recent_opportunities']) ? $crm['recent_opportunities'] : array(), 0, 3);
$recentTickets = array_slice(!empty($crm['recent_tickets']) ? $crm['recent_tickets'] : array(), 0, 4);
$recentInvoices = array_slice(!empty($finance['recent_invoices']) ? $finance['recent_invoices'] : array(), 0, 4);
$recentTransactions = array_slice(!empty($finance['recent_transactions']) ? $finance['recent_transactions'] : array(), 0, 4);

$financeSeries = !empty($finance['finance_series']) ? $finance['finance_series'] : array();
$incomeExpenseRows = array();
if (!empty($financeSeries) && !empty($financeSeries[0]['data']) && is_array($financeSeries[0]['data'])) {
    $labels = !empty($financeSeries[0]['categories']) && is_array($financeSeries[0]['categories']) ? $financeSeries[0]['categories'] : array();
    $incomeData = $financeSeries[0]['data'];
    $expenseData = !empty($financeSeries[1]['data']) && is_array($financeSeries[1]['data']) ? $financeSeries[1]['data'] : array();
    $rowCount = max(count($labels), count($incomeData), count($expenseData));
    for ($i = 0; $i < $rowCount; $i++) {
        $incomeValue = isset($incomeData[$i]) ? (float) $incomeData[$i] : 0;
        $expenseValue = isset($expenseData[$i]) ? (float) $expenseData[$i] : 0;
        $incomeExpenseRows[] = array(
            'label' => isset($labels[$i]) ? $labels[$i] : 'Month ' . ($i + 1),
            'income' => $incomeValue,
            'expense' => $expenseValue,
            'net' => $incomeValue - $expenseValue,
        );
    }
}

$activeProjectCount = isset($delivery['active_project_count']) ? (int) $delivery['active_project_count'] : count($recentProjects);
$openTaskCount = isset($delivery['open_task_count']) ? (int) $delivery['open_task_count'] : count($recentTasks);
$openTicketCount = isset($crm['open_ticket_count']) ? (int) $crm['open_ticket_count'] : count($overdueTickets);

$kpis = array(
    array('label' => 'Sales', 'value_html' => $money($finance['invoice_total']), 'hint' => 'Invoice book', 'icon' => 'badge-dollar-sign', 'tone' => 'primary'),
    array('label' => 'Collections', 'value_html' => $money($finance['paid_total']), 'hint' => 'Payments posted', 'icon' => 'wallet', 'tone' => 'success'),
    array('label' => 'Outstanding', 'value_html' => $money($finance['outstanding_total']), 'hint' => 'Receivables open', 'icon' => 'hourglass', 'tone' => 'warning'),
    array('label' => 'Open Pipeline', 'value_html' => $money($crm['pipeline_total']), 'hint' => (int) $crm['opportunity_count'] . ' opportunities', 'icon' => 'funnel', 'tone' => 'primary'),
    array('label' => 'Overdue Tasks', 'value_html' => number_format(count($overdueTasks)), 'hint' => 'Needs execution', 'icon' => 'alarm-clock', 'tone' => 'danger'),
    array('label' => 'Active Projects', 'value_html' => number_format($activeProjectCount), 'hint' => 'Not completed', 'icon' => 'briefcase', 'tone' => 'neutral'),
    array('label' => 'Open Tickets', 'value_html' => number_format($openTicketCount), 'hint' => 'Support queue', 'icon' => 'headset', 'tone' => 'warning'),
    array('label' => 'Net Cash', 'value_html' => $money($finance['net_cash']), 'hint' => 'Income minus expense', 'icon' => 'scale', 'tone' => $finance['net_cash'] >= 0 ? 'success' : 'danger'),
);

$invoice_summary = array(
    array('label' => 'Paid', 'count' => (int) ($invoiceMap['paid'] ?? 0), 'tone' => 'success'),
    array('label' => 'Pending', 'count' => (int) ($invoiceMap['pending'] ?? 0), 'tone' => 'warning'),
    array('label' => 'Partial', 'count' => (int) ($invoiceMap['partially_paid'] ?? 0), 'tone' => 'primary'),
    array('label' => 'Overdue', 'count' => (int) ($invoiceMap['overdue'] ?? 0), 'tone' => 'danger'),
);

$priorities = array(
    array(
        'label' => 'Overdue tasks',
        'count' => count($overdueTasks),
        'tone' => 'danger',
        'detail' => 'Execution backlog blocking delivery plans.',
        'href' => base_url('admin/tasks/all_task'),
        'action' => 'Open tasks',
    ),
    array(
        'label' => 'Overdue projects',
        'count' => count($overdueProjects),
        'tone' => 'warning',
        'detail' => 'Projects beyond target end date.',
        'href' => base_url('admin/projects'),
        'action' => 'Open projects',
    ),
    array(
        'label' => 'Outstanding invoices',
        'count' => count($overdueInvoices),
        'tone' => 'primary',
        'detail' => 'Commercial follow-up required.',
        'href' => base_url('admin/invoice/manage_invoice'),
        'action' => 'Open invoices',
    ),
    array(
        'label' => 'Open tickets',
        'count' => $openTicketCount,
        'tone' => 'warning',
        'detail' => 'Active support load across the queue.',
        'href' => base_url('admin/tickets'),
        'action' => 'Open tickets',
    ),
    array(
        'label' => 'Pipeline review',
        'count' => (int) $crm['opportunity_count'],
        'tone' => 'primary',
        'detail' => 'Revenue forecast waiting on sales movement.',
        'href' => base_url('admin/opportunities'),
        'action' => 'Open pipeline',
    ),
);
?>

<div class="space-y-4">
    <div class="grid grid-cols-2 gap-3 xl:grid-cols-4 2xl:grid-cols-8">
        <?php foreach ($kpis as $kpi): ?>
            <?= $this->load->view('admin/common/erp/stat_card', array(
                'label' => $kpi['label'],
                'value_html' => $kpi['value_html'],
                'hint' => $kpi['hint'],
                'icon' => $kpi['icon'],
                'tone' => $kpi['tone'],
                // 'class' => 'h-full',
            ), true); ?>
        <?php endforeach; ?>
    </div>

    <div class="grid grid-cols-1 gap-4 xl:grid-cols-[minmax(0,1.45fr)_minmax(330px,0.95fr)]">
        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Income vs Expense',
                'subtitle' => 'Six-month cash movement with current net position.',
                'actions' => $this->load->view('admin/common/erp/badge', array(
                    'label' => 'Net ' . $money($finance['net_cash']),
                    'tone' => $finance['net_cash'] >= 0 ? 'success' : 'danger',
                    'icon' => $finance['net_cash'] >= 0 ? 'trending-up' : 'trending-down',
                ), true),
            ), true); ?>
            <div class="erp-panel-body space-y-3">
                <div data-chart="area" data-height="240" data-height-sm="220" data-series='<?= json_encode($finance['finance_series'], JSON_UNESCAPED_SLASHES) ?>'></div>
                <div class="grid grid-cols-3 gap-3">
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Income</p>
                        <p class="mt-1 text-sm font-semibold text-emerald-400"><?= $money($finance['income_total']) ?></p>
                    </div>
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Expense</p>
                        <p class="mt-1 text-sm font-semibold text-rose-400"><?= $money($finance['expense_total']) ?></p>
                    </div>
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Collections</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= $money($finance['paid_total']) ?></p>
                    </div>
                </div>
                <div class="space-y-2">
                    <?php if (!empty($incomeExpenseRows)): ?>
                        <?php foreach ($incomeExpenseRows as $row): ?>
                            <div class="grid grid-cols-[minmax(0,1fr)_auto_auto_auto] items-center gap-3 rounded-lg border border-border bg-background/40 px-3 py-2.5 text-sm">
                                <span class="truncate font-semibold text-foreground"><?= html_escape($row['label']) ?></span>
                                <span class="text-emerald-400"><?= $money($row['income']) ?></span>
                                <span class="text-rose-400"><?= $money($row['expense']) ?></span>
                                <span class="font-semibold <?= $row['net'] >= 0 ? 'text-emerald-400' : 'text-rose-400' ?>"><?= $money($row['net']) ?></span>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <?= $this->load->view('admin/common/erp/empty_state', array(
                            'title' => 'No monthly movement available',
                            'message' => 'Income and expense rows will appear here once monthly transaction data is available.',
                            'icon' => 'chart-column',
                        ), true); ?>
                    <?php endif; ?>
                </div>
            </div>
        </article>

        <div class="grid gap-4">
            <article class="erp-panel">
                <?= $this->load->view('admin/common/erp/section_header', array(
                    'title' => 'Invoice / Payment Summary',
                    'subtitle' => 'Billing pressure and collection progress in one block.',
                ), true); ?>
                <div class="erp-panel-body space-y-3">
                    <div class="grid grid-cols-2 gap-3">
                        <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                            <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Collected</p>
                            <p class="mt-1 text-sm font-semibold text-emerald-400"><?= $money($finance['paid_total']) ?></p>
                        </div>
                        <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                            <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Outstanding</p>
                            <p class="mt-1 text-sm font-semibold text-amber-300"><?= $money($finance['outstanding_total']) ?></p>
                        </div>
                    </div>
                    <div class="space-y-2">
                        <?php foreach ($invoice_summary as $row): ?>
                            <div class="flex items-center justify-between gap-3 rounded-lg border border-border bg-background/40 px-3 py-2">
                                <div class="flex items-center gap-2">
                                    <?= $this->load->view('admin/common/erp/badge', array(
                                        'label' => $row['label'],
                                        'tone' => $row['tone'],
                                        'dot' => true,
                                    ), true); ?>
                                </div>
                                <span class="text-sm font-semibold text-foreground"><?= number_format($row['count']) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="space-y-2">
                        <?php if (!empty($recentTransactions)): ?>
                            <?php foreach ($recentTransactions as $transaction): ?>
                                <?php
                                $transactionType = strtolower((string) ($transaction->type ?? ''));
                                $isIncome = $transactionType === 'income';
                                $transactionLabel = !empty($transaction->transaction_prefix) ? $transaction->transaction_prefix : (!empty($transaction->name) ? $transaction->name : 'Transaction');
                                ?>
                                <div class="flex items-center justify-between gap-3 rounded-lg border border-border bg-background/40 px-3 py-2.5">
                                    <div class="min-w-0 flex-1">
                                        <p class="truncate text-sm font-semibold text-foreground"><?= html_escape($transactionLabel) ?></p>
                                        <p class="mt-1 text-xs text-muted-foreground">
                                            <?= html_escape($transaction->name ?: ucfirst($transactionType ?: 'entry')) ?>
                                            <?php if (!empty($transaction->date)): ?>
                                                • <?= $date_text($transaction->date) ?>
                                            <?php endif; ?>
                                        </p>
                                    </div>
                                    <span class="shrink-0 text-sm font-semibold <?= $isIncome ? 'text-emerald-400' : 'text-rose-400' ?>">
                                        <?= $isIncome ? '+' : '-' ?><?= $money(abs((float) ($transaction->amount ?? 0))) ?>
                                    </span>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <?= $this->load->view('admin/common/erp/empty_state', array(
                                'title' => 'No recent payment entries',
                                'message' => 'Posted transactions will appear here once finance activity is available.',
                                'icon' => 'wallet',
                            ), true); ?>
                        <?php endif; ?>
                    </div>
                    <div class="flex flex-wrap gap-2">
                        <a href="<?= base_url('admin/invoice/manage_invoice') ?>" class="erp-btn"><i data-lucide="receipt-text" class="h-4 w-4"></i><span>Invoices</span></a>
                        <a href="<?= base_url('admin/report/payment_reports') ?>" class="erp-btn"><i data-lucide="file-bar-chart-2" class="h-4 w-4"></i><span>Payments</span></a>
                    </div>
                </div>
            </article>

            <article class="erp-panel">
                <?= $this->load->view('admin/common/erp/section_header', array(
                    'title' => 'Current Priorities',
                    'subtitle' => 'Compact watchlist for immediate operational follow-up.',
                ), true); ?>
                <div class="erp-panel-body space-y-2">
                    <?php foreach ($priorities as $item): ?>
                        <div class="flex items-start justify-between gap-3 rounded-lg border border-border bg-background/40 px-3 py-2.5">
                            <div class="min-w-0 flex-1">
                                <div class="flex items-center gap-2">
                                    <p class="text-sm font-semibold text-foreground"><?= html_escape($item['label']) ?></p>
                                    <?= $this->load->view('admin/common/erp/badge', array(
                                        'label' => number_format($item['count']),
                                        'tone' => $item['tone'],
                                    ), true); ?>
                                </div>
                                <p class="mt-1 text-xs text-muted-foreground"><?= html_escape($item['detail']) ?></p>
                            </div>
                            <a href="<?= $item['href'] ?>" class="text-xs font-semibold text-primary hover:underline"><?= html_escape($item['action']) ?></a>
                        </div>
                    <?php endforeach; ?>
                </div>
            </article>
        </div>
    </div>

    <div class="grid grid-cols-1 gap-4 xl:grid-cols-3">
        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Recent Activity',
                'subtitle' => 'Latest movement across the ERP workspace.',
                'actions' => '<a href="' . base_url('admin/settings/activities') . '" class="text-xs font-semibold text-primary hover:underline">View log</a>',
            ), true); ?>
            <div class="erp-panel-body space-y-2">
                <?php foreach ($recentActivities as $row): ?>
                    <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-semibold text-foreground"><?= html_escape($row->fullname ?: 'System') ?></p>
                                <p class="mt-1 text-xs leading-5 text-muted-foreground"><?= html_escape(strip_tags($row->activity . ' ' . $row->value1)) ?></p>
                            </div>
                            <span class="shrink-0 text-[11px] text-muted-foreground"><?= $date_text($row->activity_date) ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Project / Workload Snapshot',
                'subtitle' => 'Active delivery pressure and near-term work items.',
            ), true); ?>
            <div class="erp-panel-body space-y-3">
                <div class="grid grid-cols-2 gap-3">
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Projects</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= number_format($activeProjectCount) ?></p>
                    </div>
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Open Tasks</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= number_format($openTaskCount) ?></p>
                    </div>
                </div>
                <div class="space-y-2">
                    <?php foreach ($recentTasks as $task): ?>
                        <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-semibold text-foreground"><?= html_escape($task->task_name) ?></p>
                                    <p class="mt-1 text-xs text-muted-foreground"><?= html_escape($task->project_name ?: 'No project') ?> • Due <?= $date_text($task->due_date) ?></p>
                                </div>
                                <span class="text-xs font-semibold text-primary"><?= (int) $task->task_progress ?>%</span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php foreach ($recentProjects as $project): ?>
                        <?php $progress = (int) ($project->total_tasks > 0 ? round(($project->completed_tasks / $project->total_tasks) * 100) : 0); ?>
                        <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0 flex-1">
                                    <p class="text-sm font-semibold text-foreground"><?= html_escape($project->project_name) ?></p>
                                    <p class="mt-1 text-xs text-muted-foreground"><?= html_escape(ucfirst($project->project_status)) ?> • Due <?= $date_text($project->end_date) ?></p>
                                </div>
                                <span class="text-xs font-semibold text-foreground"><?= $progress ?>%</span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </article>

        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Leads / Tickets Summary',
                'subtitle' => 'Commercial pressure and support queue at a glance.',
            ), true); ?>
            <div class="erp-panel-body space-y-3">
                <div class="grid grid-cols-3 gap-3">
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Leads</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= number_format((int) $crm['lead_count']) ?></p>
                    </div>
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Tickets</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= number_format($openTicketCount) ?></p>
                    </div>
                    <div class="rounded-lg border border-border bg-background/50 px-3 py-2">
                        <p class="text-[11px] font-semibold uppercase tracking-wide text-muted-foreground">Pipeline</p>
                        <p class="mt-1 text-sm font-semibold text-foreground"><?= $money($crm['pipeline_total']) ?></p>
                    </div>
                </div>
                <?php foreach ($recentOpportunities as $opp): ?>
                    <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-semibold text-foreground"><?= html_escape($opp->opportunity_name) ?></p>
                                <p class="mt-1 text-xs text-muted-foreground"><?= html_escape(ucfirst($opp->stages ?: 'open')) ?> • Close <?= $date_text($opp->close_date) ?></p>
                            </div>
                            <span class="text-xs font-semibold text-primary"><?= $money($opp->expected_revenue) ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
                <?php foreach ($recentTickets as $ticket): ?>
                    <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-semibold text-foreground"><?= html_escape($ticket->ticket_code ?: 'Ticket') ?></p>
                                <p class="mt-1 text-xs text-muted-foreground"><?= html_escape($ticket->subject) ?></p>
                            </div>
                            <?= $this->load->view('admin/common/erp/badge', array(
                                'label' => ucfirst($ticket->priority ?: 'medium'),
                                'tone' => strtolower((string) $ticket->priority) === 'high' ? 'danger' : (strtolower((string) $ticket->priority) === 'medium' ? 'warning' : 'neutral'),
                            ), true); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>
    </div>

    <div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Recent Invoices',
                'subtitle' => 'Latest receivables and invoice status.',
                'actions' => '<a href="' . base_url('admin/invoice/manage_invoice') . '" class="text-xs font-semibold text-primary hover:underline">Open invoices</a>',
            ), true); ?>
            <div class="erp-panel-body space-y-2">
                <?php foreach ($recentInvoices as $invoice): ?>
                    <div class="rounded-lg border border-border bg-background/40 px-3 py-2.5">
                        <div class="flex items-start justify-between gap-3">
                            <div class="min-w-0 flex-1">
                                <p class="text-sm font-semibold text-foreground"><?= html_escape($invoice->reference_no) ?></p>
                                <p class="mt-1 text-xs text-muted-foreground"><?= html_escape($invoice->client_name ?: 'Unassigned client') ?> • Due <?= $date_text($invoice->due_date) ?></p>
                            </div>
                            <?= $this->load->view('admin/common/erp/badge', array(
                                'label' => ucfirst($invoice->status),
                                'tone' => strtolower((string) $invoice->status) === 'paid' ? 'success' : (strtolower((string) $invoice->status) === 'overdue' ? 'danger' : 'warning'),
                            ), true); ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </article>

        <article class="erp-panel">
            <?= $this->load->view('admin/common/erp/section_header', array(
                'title' => 'Commercial Mix',
                'subtitle' => 'Billing status distribution across current invoices.',
            ), true); ?>
            <div class="erp-panel-body">
                <div data-chart="bar" data-height="220" data-height-sm="200" data-series='<?= json_encode($finance['invoice_status_series'], JSON_UNESCAPED_SLASHES) ?>'></div>
            </div>
        </article>
    </div>
</div>
