<?php
$currency = $this->report_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
$today = date('Y-m-d');
$first_day_month = date('Y-m-01');
$this_week_start = date('Y-m-d', safe_strtotime('previous sunday'));
$before_30_days = date('Y-m-d', safe_strtotime('today - 30 days'));

$total_summary = $this->db
    ->select('COALESCE(SUM(credit), 0) AS total_credit, COALESCE(SUM(debit), 0) AS total_debit', false)
    ->get('tbl_transactions')
    ->row();
$period_rows = $this->db
    ->select("
        SUM(CASE WHEN date >= '{$first_day_month}' AND date <= '{$today}' THEN credit ELSE 0 END) AS income_this_month,
        SUM(CASE WHEN date >= '{$this_week_start}' AND date <= '{$today}' THEN credit ELSE 0 END) AS income_this_week,
        SUM(CASE WHEN date >= '{$before_30_days}' AND date <= '{$today}' THEN credit ELSE 0 END) AS income_this_30_days,
        SUM(CASE WHEN date >= '{$first_day_month}' AND date <= '{$today}' THEN debit ELSE 0 END) AS expense_this_month,
        SUM(CASE WHEN date >= '{$this_week_start}' AND date <= '{$today}' THEN debit ELSE 0 END) AS expense_this_week,
        SUM(CASE WHEN date >= '{$before_30_days}' AND date <= '{$today}' THEN debit ELSE 0 END) AS expense_this_30_days
    ", false)
    ->get('tbl_transactions')
    ->row();
$total_income = !empty($total_summary->total_credit) ? (float) $total_summary->total_credit : 0;
$total_expense = !empty($total_summary->total_debit) ? (float) $total_summary->total_debit : 0;
$income_this_month = !empty($period_rows->income_this_month) ? (float) $period_rows->income_this_month : 0;
$income_this_week = !empty($period_rows->income_this_week) ? (float) $period_rows->income_this_week : 0;
$income_this_30_days = !empty($period_rows->income_this_30_days) ? (float) $period_rows->income_this_30_days : 0;
$expense_this_month = !empty($period_rows->expense_this_month) ? (float) $period_rows->expense_this_month : 0;
$expense_this_week = !empty($period_rows->expense_this_week) ? (float) $period_rows->expense_this_week : 0;
$expense_this_30_days = !empty($period_rows->expense_this_30_days) ? (float) $period_rows->expense_this_30_days : 0;

$monthly_buckets = array();
for ($i = 11; $i >= 0; $i--) {
    $month_key = date('Y-m', safe_strtotime('-' . $i . ' months'));
    $monthly_buckets[$month_key] = array(
        'label' => date('M Y', safe_strtotime($month_key . '-01')),
        'income' => 0,
        'expense' => 0,
        'net' => 0,
    );
}
$monthly_rows = $this->db
    ->select("DATE_FORMAT(date, '%Y-%m') AS bucket, COALESCE(SUM(credit), 0) AS income_total, COALESCE(SUM(debit), 0) AS expense_total", false)
    ->where('date >=', key($monthly_buckets) . '-01')
    ->where('date <=', $today)
    ->group_by("DATE_FORMAT(date, '%Y-%m')")
    ->order_by('bucket', 'ASC')
    ->get('tbl_transactions')
    ->result();
foreach ($monthly_rows as $row) {
    if (isset($monthly_buckets[$row->bucket])) {
        $monthly_buckets[$row->bucket]['income'] = (float) $row->income_total;
        $monthly_buckets[$row->bucket]['expense'] = (float) $row->expense_total;
        $monthly_buckets[$row->bucket]['net'] = (float) $row->income_total - (float) $row->expense_total;
    }
}

$current_month_days = (int) date('t');
$daily_buckets = array();
for ($day = 1; $day <= $current_month_days; $day++) {
    $date_key = date('Y-m-') . str_pad((string) $day, 2, '0', STR_PAD_LEFT);
    $daily_buckets[$date_key] = array(
        'label' => str_pad((string) $day, 2, '0', STR_PAD_LEFT),
        'income' => 0,
        'expense' => 0,
        'net' => 0,
    );
}
$daily_rows = $this->db
    ->select("date AS bucket, COALESCE(SUM(credit), 0) AS income_total, COALESCE(SUM(debit), 0) AS expense_total", false)
    ->where('date >=', $first_day_month)
    ->where('date <=', date('Y-m-t'))
    ->group_by('date')
    ->order_by('date', 'ASC')
    ->get('tbl_transactions')
    ->result();
foreach ($daily_rows as $row) {
    if (isset($daily_buckets[$row->bucket])) {
        $daily_buckets[$row->bucket]['income'] = (float) $row->income_total;
        $daily_buckets[$row->bucket]['expense'] = (float) $row->expense_total;
        $daily_buckets[$row->bucket]['net'] = (float) $row->income_total - (float) $row->expense_total;
    }
}

$periods = array(
    array(
        'title' => lang('this_month'),
        'caption' => date('F Y'),
        'income' => $income_this_month,
        'expense' => $expense_this_month,
        'color' => 'emerald'
    ),
    array(
        'title' => lang('this_week'),
        'caption' => 'Rolling 7 days',
        'income' => $income_this_week,
        'expense' => $expense_this_week,
        'color' => 'sky'
    ),
    array(
        'title' => lang('last') . ' 30 ' . lang('days'),
        'caption' => 'Rolling 30 days',
        'income' => $income_this_30_days,
        'expense' => $expense_this_30_days,
        'color' => 'violet'
    ),
);

$gross_flow = $total_income + $total_expense;
$net_position = $total_income - $total_expense;
$profit_margin = $gross_flow > 0 ? round(($net_position / $gross_flow) * 100, 1) : 0;
$expense_ratio = $gross_flow > 0 ? round(($total_expense / $gross_flow) * 100, 1) : 0;

$monthly_categories = array();
$monthly_income = array();
$monthly_expense = array();
$monthly_net = array();
foreach ($monthly_buckets as $bucket) {
    $monthly_categories[] = $bucket['label'];
    $monthly_income[] = round($bucket['income'], 2);
    $monthly_expense[] = round($bucket['expense'], 2);
    $monthly_net[] = round($bucket['net'], 2);
}
$monthly_trend_series = array(
    array('name' => lang('Income'), 'data' => $monthly_income, 'categories' => $monthly_categories),
    array('name' => lang('expense'), 'data' => $monthly_expense),
    array('name' => 'Net', 'data' => $monthly_net),
);

$daily_categories = array();
$daily_income = array();
$daily_expense = array();
$daily_net = array();
foreach ($daily_buckets as $bucket) {
    $daily_categories[] = $bucket['label'];
    $daily_income[] = round($bucket['income'], 2);
    $daily_expense[] = round($bucket['expense'], 2);
    $daily_net[] = round($bucket['net'], 2);
}
$daily_flow_series = array(
    array('name' => lang('Income'), 'data' => $daily_income, 'categories' => $daily_categories),
    array('name' => lang('expense'), 'data' => $daily_expense),
    array('name' => 'Net', 'data' => $daily_net),
);

$period_categories = array();
$period_income_series = array();
$period_expense_series = array();
$period_net_series = array();
foreach ($periods as $period) {
    $period_categories[] = $period['title'];
    $period_income_series[] = round($period['income'], 2);
    $period_expense_series[] = round($period['expense'], 2);
    $period_net_series[] = round($period['income'] - $period['expense'], 2);
}
$period_comparison_series = array(
    array('name' => lang('Income'), 'data' => $period_income_series, 'categories' => $period_categories),
    array('name' => lang('expense'), 'data' => $period_expense_series),
    array('name' => 'Net', 'data' => $period_net_series),
);

$account_rows = $this->db
    ->select('COALESCE(tbl_accounts.account_name, "Unassigned") AS account_name, COALESCE(SUM(tbl_transactions.credit), 0) AS income_total, COALESCE(SUM(tbl_transactions.debit), 0) AS expense_total, (COALESCE(SUM(tbl_transactions.credit), 0) + COALESCE(SUM(tbl_transactions.debit), 0)) AS cash_volume', false)
    ->from('tbl_transactions')
    ->join('tbl_accounts', 'tbl_accounts.account_id = tbl_transactions.account_id', 'left')
    ->group_by('tbl_transactions.account_id')
    ->order_by('cash_volume', 'DESC')
    ->limit(8)
    ->get()
    ->result();
$account_categories = array();
$account_income = array();
$account_expense = array();
foreach ($account_rows as $row) {
    $account_categories[] = $row->account_name;
    $account_income[] = round((float) $row->income_total, 2);
    $account_expense[] = round((float) $row->expense_total, 2);
}
$account_series = array(
    array('name' => lang('Income'), 'data' => $account_income, 'categories' => $account_categories),
    array('name' => lang('expense'), 'data' => $account_expense),
);

$summary_cards = array(
    array(
        'label' => lang('total_income'),
        'value' => display_money($total_income, $currency->symbol),
        'meta' => 'All recorded inflow across finance accounts',
        'icon' => 'arrow-down-left',
        'tone' => 'text-emerald-600 dark:text-emerald-300 bg-emerald-500/10',
    ),
    array(
        'label' => lang('total_expense'),
        'value' => display_money($total_expense, $currency->symbol),
        'meta' => 'All posted outflow across finance accounts',
        'icon' => 'arrow-up-right',
        'tone' => 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
    array(
        'label' => 'Net Position',
        'value' => display_money($net_position, $currency->symbol),
        'meta' => 'Current spread between income and expense',
        'icon' => 'scale',
        'tone' => ($net_position >= 0)
            ? 'text-sky-600 dark:text-sky-300 bg-sky-500/10'
            : 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
    array(
        'label' => 'Profit Margin',
        'value' => $profit_margin . '%',
        'meta' => 'Net performance against total cash flow',
        'icon' => 'badge-percent',
        'tone' => ($profit_margin >= 0)
            ? 'text-violet-600 dark:text-violet-300 bg-violet-500/10'
            : 'text-rose-600 dark:text-rose-300 bg-rose-500/10',
    ),
);
?>
<div class="space-y-6 sales-report-page">
    <div class="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-4 sales-report-cardgrid">
        <?php foreach ($summary_cards as $card): ?>
            <div class="rounded-xl border border-border bg-card p-4 shadow-sm sales-report-card">
                <div class="flex items-start justify-between gap-3">
                    <div>
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= $card['label'] ?></p>
                        <p class="mt-2 text-xl font-bold text-foreground"><?= $card['value'] ?></p>
                        <p class="mt-1 text-xs text-muted-foreground"><?= $card['meta'] ?></p>
                    </div>
                    <span class="inline-flex h-10 w-10 items-center justify-center rounded-xl <?= $card['tone'] ?>">
                        <i data-lucide="<?= $card['icon'] ?>" class="h-5 w-5"></i>
                    </span>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div id="printReport" class="rounded-2xl border border-border bg-card shadow-sm sales-report-content p-4">
        <div class="">
        <div class="show_print hidden">
                <div class="report-print-brand">
                    <div class="report-print-brand-row">
                        <img class="report-print-brand-logo" src="<?= base_url() . config_item('company_logo') ?>" alt="<?= html_escape(config_item('company_name')) ?>" />
                        <p class="report-print-brand-name"><?= config_item('company_name') ?></p>
                    </div>
                </div>
        </div>

        <section class="grid grid-cols-1 gap-6 p-6 xl:grid-cols-12">
            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-8">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">12 Month Performance Trend</h3>
                    <p class="text-sm text-muted-foreground">Income, expense, and net position across the rolling financial year.</p>
                </div>
                <div class="p-6">
                    <div data-chart="line" data-height="340" data-height-sm="260" data-series='<?= json_encode($monthly_trend_series, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>

            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-4">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">Window Comparison</h3>
                    <p class="text-sm text-muted-foreground">This month, this week, and last 30 days side by side.</p>
                </div>
                <div class="p-6">
                    <div data-chart="bar" data-height="340" data-height-sm="260" data-series='<?= json_encode($period_comparison_series, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 px-6 pb-6 xl:grid-cols-12">
            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-7">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground"><?= date('F Y') ?> Daily Flow</h3>
                    <p class="text-sm text-muted-foreground">Daily income, expense, and net movement for the current reporting month.</p>
                </div>
                <div class="p-6">
                    <div data-chart="area" data-height="320" data-height-sm="250" data-series='<?= json_encode($daily_flow_series, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>

            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-5">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">Top Account Contribution</h3>
                    <p class="text-sm text-muted-foreground">Largest finance accounts by posted income and expense volume.</p>
                </div>
                <div class="p-6">
                    <div data-chart="bar" data-height="320" data-height-sm="250" data-series='<?= json_encode($account_series, JSON_UNESCAPED_SLASHES | JSON_HEX_APOS) ?>'></div>
                </div>
            </div>
        </section>

        <section class="grid grid-cols-1 gap-6 xl:grid-cols-12">
            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-8">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">Period Comparison</h3>
                    <p class="text-sm text-muted-foreground">Compare revenue and spending by reporting window with net position and flow mix.</p>
                </div>
                <div class="space-y-4 p-6">
                    <?php foreach ($periods as $period):
                        $period_total = $period['income'] + $period['expense'];
                        $income_share = $period_total > 0 ? round(($period['income'] / $period_total) * 100) : 0;
                        $expense_share = $period_total > 0 ? round(($period['expense'] / $period_total) * 100) : 0;
                        $net_total = $period['income'] - $period['expense'];
                        ?>
                        <div class="rounded-2xl border border-border bg-background/70 p-5">
                            <div class="flex flex-col gap-3 md:flex-row md:items-start md:justify-between">
                                <div>
                                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= $period['title'] ?></p>
                                    <h4 class="mt-1 text-lg font-semibold text-foreground"><?= $period['caption'] ?></h4>
                                </div>
                                <span class="inline-flex rounded-full border border-border bg-card px-3 py-1 text-xs font-semibold <?= $net_total >= 0 ? 'text-emerald-600 dark:text-emerald-300' : 'text-rose-600 dark:text-rose-300' ?>">
                                    Net Position: <?= display_money($net_total, $currency->symbol) ?>
                                </span>
                            </div>
                            <div class="mt-4 grid grid-cols-1 gap-4 md:grid-cols-2">
                                <div>
                                    <div class="mb-2 flex items-center justify-between text-sm">
                                        <span class="font-medium text-foreground"><?= lang('Income') ?></span>
                                        <span class="text-muted-foreground"><?= display_money($period['income'], $currency->symbol) ?></span>
                                    </div>
                                    <progress class="report-meter report-meter-income" max="100" value="<?= $income_share ?>"></progress>
                                </div>
                                <div>
                                    <div class="mb-2 flex items-center justify-between text-sm">
                                        <span class="font-medium text-foreground"><?= lang('expense') ?></span>
                                        <span class="text-muted-foreground"><?= display_money($period['expense'], $currency->symbol) ?></span>
                                    </div>
                                    <progress class="report-meter report-meter-expense" max="100" value="<?= $expense_share ?>"></progress>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <div class="rounded-2xl border border-border bg-background/60 sales-report-module p-4 xl:col-span-4">
                <div class="border-b border-border px-6 py-4">
                    <h3 class="text-lg font-semibold text-foreground">Executive Snapshot</h3>
                    <p class="text-sm text-muted-foreground">Quick profitability indicators for management review.</p>
                </div>
                <div class="space-y-4 p-6">
                    <div class="rounded-2xl border border-border bg-background/70 p-5">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Gross Flow</p>
                        <p class="mt-2 text-2xl font-bold text-foreground"><?= display_money($gross_flow, $currency->symbol) ?></p>
                    </div>
                    <div class="rounded-2xl border border-border bg-background/70 p-5">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">Profit Margin</p>
                        <p class="mt-2 text-2xl font-bold <?= $profit_margin >= 0 ? 'text-emerald-600 dark:text-emerald-300' : 'text-rose-600 dark:text-rose-300' ?>"><?= $profit_margin ?>%</p>
                    </div>
                    <div class="rounded-2xl border border-border bg-background/70 p-5">
                        <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('expense_ratio') ?></p>
                        <p class="mt-2 text-2xl font-bold text-foreground"><?= $expense_ratio ?>%</p>
                        <p class="mt-2 text-sm text-muted-foreground">Share of total flow consumed by expenses.</p>
                    </div>
                </div>
            </div>
        </section>
        </div>
    </div>
</div>

<textarea class="hidden" style="display:none" data-income-expense-print-html><?= html_escape(isset($income_expense_print_html) ? $income_expense_print_html : '') ?></textarea>
<script type="text/javascript">
    function print_sales_report(printReport) {
        var textarea = document.querySelector('[data-income-expense-print-html]');
        var fallback = document.getElementById(printReport);
        var printHtml = (textarea ? textarea.value : '') || (fallback ? fallback.outerHTML : '');
        if (!printHtml) return false;

        var printWindow = window.open('', 'PRINT', 'height=900,width=1200');
        if (!printWindow) {
            window.print();
            return false;
        }

        printWindow.document.open();
        printWindow.document.write(printHtml);
        printWindow.document.close();

        var printed = false;
        var doPrint = function() {
            if (printed || printWindow.closed) return;
            printed = true;
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        };
        printWindow.onload = function() {
            printWindow.setTimeout(doPrint, 350);
        };
        printWindow.setTimeout(doPrint, 900);
        return false;
    }
</script>
