<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/layout.php';

require_permission($conn, 'void_report');

ensure_order_branch_column($conn);
ensure_order_bill_number_column($conn);
ensure_order_cancellation_columns($conn);

function void_report_month(string $value, string $default): string
{
    if (!preg_match('/^\d{4}-\d{2}$/', $value)) {
        return $default;
    }

    $timestamp = strtotime($value . '-01');

    return $timestamp === false ? $default : date('Y-m', $timestamp);
}

function void_report_date_value(string $value, string $default): string
{
    $timestamp = strtotime($value);

    return $timestamp === false ? $default : date('Y-m-d', $timestamp);
}

function void_report_year(string $value, string $default): string
{
    if (!preg_match('/^\d{4}$/', $value)) {
        return $default;
    }

    $year = (int) $value;

    if ($year < 2000 || $year > 2100) {
        return $default;
    }

    return (string) $year;
}

$period = (string) ($_GET['period'] ?? 'monthly');
$allowedPeriods = array('daily', 'monthly', 'yearly');
if (!in_array($period, $allowedPeriods, true)) {
    $period = 'monthly';
}

$today = date('Y-m-d');
$currentMonth = date('Y-m');
$currentYear = date('Y');
$shouldLoadReport = isset($_GET['load']) && (string) $_GET['load'] === '1';
$dateValue = void_report_date_value((string) ($_GET['date'] ?? $today), $today);
$monthValue = void_report_month((string) ($_GET['month'] ?? $currentMonth), $currentMonth);
$yearValue = void_report_year((string) ($_GET['year'] ?? $currentYear), $currentYear);

if ($period === 'daily') {
    $startAt = $dateValue . ' 00:00:00';
    $endAt = date('Y-m-d 00:00:00', strtotime($startAt . ' +1 day'));
    $periodLabel = date('d/m/Y', strtotime($startAt));
} elseif ($period === 'yearly') {
    $startAt = $yearValue . '-01-01 00:00:00';
    $endAt = ((int) $yearValue + 1) . '-01-01 00:00:00';
    $periodLabel = $yearValue;
} else {
    $startAt = date('Y-m-01 00:00:00', strtotime($monthValue . '-01'));
    $endAt = date('Y-m-d 00:00:00', strtotime($startAt . ' +1 month'));
    $periodLabel = localized_year_month_label($startAt);
}

$branchNames = authorized_order_branch_options($conn);

$branchFilter = trim((string) ($_GET['branch_name'] ?? ''));
if ($branchFilter !== '' && !in_array($branchFilter, $branchNames, true)) {
    $branchFilter = '';
}

$voidDateExpression = 'o.cancelled_at';
$where = array(
    "o.status = 'cancelled'",
    'o.cancelled_at IS NOT NULL',
    "{$voidDateExpression} >= ?",
    "{$voidDateExpression} < ?",
);
$types = 'ss';
$params = array($startAt, $endAt);

$branchAccessCondition = auth_branch_condition($conn, 'o', $types, $params);
if ($branchAccessCondition !== '') {
    $where[] = $branchAccessCondition;
}

if ($branchFilter !== '') {
    $where[] = 'o.branch_name = ?';
    $types .= 's';
    $params[] = $branchFilter;
}

$whereSql = implode(' AND ', $where);
$rows = array();
if ($shouldLoadReport) {
    $stmt = db_prepare($conn, "
        SELECT
            o.order_id,
            o.bill_number,
            o.order_date,
            {$voidDateExpression} AS voided_at,
            o.branch_name,
            o.total_price,
            o.cancellation_reason,
            c.name AS customer_name,
            car.plate_number,
            car.brand,
            car.model,
            cancelled_by.name AS cancelled_by_name
        FROM orders o FORCE INDEX (idx_orders_void_report)
        STRAIGHT_JOIN customers c ON c.customer_id = o.customer_id
        STRAIGHT_JOIN cars car ON car.car_id = o.car_id
        LEFT JOIN employees cancelled_by ON cancelled_by.employee_id = o.cancelled_by_employee_id
        WHERE {$whereSql}
        ORDER BY voided_at DESC, o.order_id DESC
    ");
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }

    $stmt->close();

    $orderIds = array_column($rows, 'order_id');
    $serviceSummaryMap = order_service_summary_map($conn, $orderIds);
    $paymentSummaryMap = order_payment_summary_map($conn, $orderIds);

    foreach ($rows as &$row) {
        $orderId = (int) ($row['order_id'] ?? 0);
        $serviceSummary = $serviceSummaryMap[$orderId] ?? array();
        $paymentSummary = $paymentSummaryMap[$orderId] ?? order_payment_summary_defaults();
        $row['service_names'] = (string) ($serviceSummary['service_names'] ?? '');
        $row['paid_amount'] = (float) ($paymentSummary['total_amount'] ?? 0);
    }
    unset($row);
}

$pageTitle = ui_text('รายงานบิลยกเลิก', 'Void Report');
$pageDescription = ui_text('ติดตามบิลที่ยกเลิกพร้อมเหตุผลการยกเลิกและผู้ดำเนินการ', 'Cancelled bills with void reason and employee audit trail.');
$printReportLabel = ui_text('พิมพ์รายงาน', 'Print report');
$viewByLabel = ui_text('ดูตาม', 'View by');
$dailyLabel = ui_text('รายวัน', 'Daily');
$monthlyLabel = ui_text('รายเดือน', 'Monthly');
$yearlyLabel = ui_text('รายปี', 'Yearly');
$dailyDateLabel = ui_text('วันที่', 'Daily date');
$monthlyPeriodLabel = ui_text('ช่วงเดือน', 'Monthly period');
$yearlyPeriodLabel = ui_text('ช่วงปี', 'Yearly period');
$branchLabel = ui_text('สาขา', 'Branch');
$allBranchesLabel = ui_text('ทุกสาขา', 'All branches');
$currentPeriodLabel = ui_text('ช่วงที่ดู', 'Current period');
$viewReportLabel = ui_text('ดูรายงาน', 'View report');
$resetLabel = ui_text('รีเซ็ต', 'Reset');
$loadPromptLabel = ui_text('กดดูรายงานเพื่อโหลดข้อมูลบิลยกเลิก', 'Click View report to load voided bill data.');
$reportCountLabel = ui_text(count($rows) . ' บิลยกเลิก', count($rows) . ' void bill(s)');
$emptyRowsLabel = ui_text('ไม่พบบิลยกเลิกในช่วงเวลาที่เลือก', 'No void bills found for this period.');
$voidDateLabel = ui_text('วันที่ยกเลิก', 'Void date');
$billNumberLabel = ui_text('เลขที่บิล', 'Bill no.');
$customerLabel = ui_text('ลูกค้า', 'Customer');
$plateLabel = ui_text('ทะเบียน', 'Plate');
$vehicleLabel = ui_text('รถ', 'Vehicle');
$servicesLabel = ui_text('บริการ', 'Services');
$totalLabel = ui_text('ยอดรวม', 'Total');
$paidLabel = ui_text('ชำระแล้ว', 'Paid');
$cancelledByLabel = ui_text('ยกเลิกโดย', 'Cancelled by');
$reasonLabel = ui_text('เหตุผล', 'Reason');
$selectedBranchLabel = $branchFilter !== '' ? $branchFilter : $allBranchesLabel;

render_page_start($pageTitle, 'void_report', array('translation_buffer' => false));
?>

<section class="page-hero">
    <div>
        <h1><?= e($pageTitle) ?></h1>
        <p><?= e($pageDescription) ?></p>
    </div>
    <div class="hero-actions">
        <button class="button button-secondary" type="button" onclick="window.print()"><?= e($printReportLabel) ?></button>
    </div>
</section>

<section class="form-card sale-report-filters sale-report-toolbar-card">
    <form method="GET" action="void_report.php" class="sale-report-toolbar-form">
        <input type="hidden" name="load" value="1">

        <div class="sale-report-toolbar-head">
            <div>
                <h2 class="section-title"><?= e($pageTitle) ?></h2>
                <p class="helper"><?= e($pageDescription) ?></p>
            </div>
        </div>

        <div class="sale-report-filter-strip">
            <label class="sale-report-filter-pill" for="period">
                <span><?= e($viewByLabel) ?></span>
                <select id="period" name="period">
                    <option value="daily" <?= $period === 'daily' ? 'selected' : '' ?>><?= e($dailyLabel) ?></option>
                    <option value="monthly" <?= $period === 'monthly' ? 'selected' : '' ?>><?= e($monthlyLabel) ?></option>
                    <option value="yearly" <?= $period === 'yearly' ? 'selected' : '' ?>><?= e($yearlyLabel) ?></option>
                </select>
            </label>

            <label class="sale-report-filter-pill <?= $period === 'daily' ? 'is-active' : '' ?>" for="date">
                <span><?= e($dailyDateLabel) ?></span>
                <input id="date" name="date" type="date" value="<?= e($dateValue) ?>">
            </label>

            <label class="sale-report-filter-pill <?= $period === 'monthly' ? 'is-active' : '' ?>" for="month">
                <span><?= e($monthlyPeriodLabel) ?></span>
                <?= render_month_picker('month', 'month', $monthValue, $monthlyPeriodLabel) ?>
            </label>

            <label class="sale-report-filter-pill <?= $period === 'yearly' ? 'is-active' : '' ?>" for="year">
                <span><?= e($yearlyPeriodLabel) ?></span>
                <input id="year" name="year" type="number" min="2000" max="2100" value="<?= e($yearValue) ?>">
            </label>

            <label class="sale-report-filter-pill" for="branch_name">
                <span><?= e($branchLabel) ?></span>
                <select id="branch_name" name="branch_name">
                    <option value=""><?= e($allBranchesLabel) ?></option>
                    <?php foreach ($branchNames as $branchName): ?>
                        <option value="<?= e($branchName) ?>" <?= $branchFilter === $branchName ? 'selected' : '' ?>>
                            <?= e($branchName) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </label>
        </div>

        <div class="sale-report-current-scope">
            <span><strong><?= e($currentPeriodLabel) ?>:</strong> <?= e($periodLabel) ?></span>
            <span><strong><?= e($branchLabel) ?>:</strong> <?= e($selectedBranchLabel) ?></span>
        </div>

        <div class="sale-report-toolbar-actions">
            <button class="button button-secondary app-action-button" type="button" onclick="window.print()"><?= app_button_content('printer', $printReportLabel) ?></button>
            <button class="button button-accent app-action-button" type="submit"><?= app_button_content('chart', $viewReportLabel) ?></button>
            <a class="button button-ghost app-action-button" href="void_report.php"><?= app_button_content('rotate-ccw', $resetLabel) ?></a>
        </div>
    </form>
</section>

<?php if (!$shouldLoadReport): ?>
    <section class="empty-state" style="margin-top: 18px;"><?= e($loadPromptLabel) ?></section>
<?php else: ?>
    <section class="table-card" style="margin-top: 18px;">
        <div class="section-head" style="padding: 18px 18px 0;">
            <div>
                <h2 class="section-title"><?= e($pageTitle) ?> <?= e($periodLabel) ?></h2>
                <p class="helper"><?= e($selectedBranchLabel) ?> / <?= e($reportCountLabel) ?></p>
            </div>
        </div>

        <?php if (empty($rows)): ?>
            <div class="empty-state" style="margin: 18px;"><?= e($emptyRowsLabel) ?></div>
        <?php else: ?>
            <table style="min-width: 1120px;">
                <thead>
                <tr>
                    <th><?= e($voidDateLabel) ?></th>
                    <th><?= e($billNumberLabel) ?></th>
                    <th><?= e($branchLabel) ?></th>
                    <th><?= e($customerLabel) ?></th>
                    <th><?= e($plateLabel) ?></th>
                    <th><?= e($vehicleLabel) ?></th>
                    <th><?= e($servicesLabel) ?></th>
                    <th><?= e($totalLabel) ?></th>
                    <th><?= e($paidLabel) ?></th>
                    <th><?= e($cancelledByLabel) ?></th>
                    <th><?= e($reasonLabel) ?></th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($rows as $row): ?>
                    <?php $brandModel = trim((string) (($row['brand'] ?? '') . ' ' . ($row['model'] ?? ''))); ?>
                    <tr class="sale-report-void-row">
                        <td><?= e(format_datetime((string) $row['voided_at'])) ?></td>
                        <td>
                            <a class="bill-link" href="job_details.php?id=<?= (int) $row['order_id'] ?>">
                                <?= e((string) ($row['bill_number'] ?: '#' . (int) $row['order_id'])) ?>
                            </a>
                        </td>
                        <td><?= e((string) ($row['branch_name'] ?? '-')) ?></td>
                        <td><?= e((string) $row['customer_name']) ?></td>
                        <td><?= e((string) $row['plate_number']) ?></td>
                        <td><?= e($brandModel !== '' ? $brandModel : '-') ?></td>
                        <td><?= e((string) ($row['service_names'] ?? '-')) ?></td>
                        <td class="number"><?= format_money($row['total_price']) ?></td>
                        <td class="number"><?= format_money($row['paid_amount']) ?></td>
                        <td><?= e((string) ($row['cancelled_by_name'] ?? '-')) ?></td>
                        <td><?= nl2br(e((string) ($row['cancellation_reason'] ?? '-'))) ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </section>
<?php endif; ?>

<?php render_page_end(); ?>
