<?php
/**
 * Service_Report_Render — رندر HTML گزارش فنی SRD
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Service_Report_Render {

    public static function decode_report( array $row ): array {
        foreach ( [
            'technical_readings', 'service_lines', 'part_lines', 'material_lines',
            'extra_costs', 'recommendations', 'pm_offer', 'complaint_tags', 'device_snapshot',
            'photos_before', 'photos_after',
        ] as $f ) {
            if ( isset( $row[ $f ] ) && is_string( $row[ $f ] ) ) {
                $row[ $f ] = json_decode( $row[ $f ], true ) ?: [];
            }
        }
        return $row;
    }

    public static function public_url( string $token ): string {
        if ( defined( 'ACC_URL' ) ) {
            return rtrim( ACC_URL, '/' ) . '/service-report.php?token=' . rawurlencode( $token );
        }
        if ( function_exists( 'home_url' ) ) {
            return home_url( '/service-report.php?token=' . rawurlencode( $token ) );
        }
        return '/service-report.php?token=' . rawurlencode( $token );
    }

    public static function render_html( array $report, bool $print_mode = false ): string {
        $r   = self::decode_report( $report );
        $url = self::public_url( $r['public_token'] ?? '' );
        $snap = $r['device_snapshot'] ?? [];
        $types = class_exists( 'SR_Controller' ) ? SR_Controller::$SERVICE_TYPES : [];

        $fmt = fn( $n ) => number_format( (float) $n, 0, '.', ',' ) . ' ریال';

        ob_start();
        ?>
<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>گزارش فنی <?= esc_html( $r['report_no'] ?? '' ) ?></title>
<style>
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:Tahoma,'Vazir',sans-serif;background:#f1f5f9;color:#1e293b;font-size:13px;line-height:1.6}
.wrap{max-width:800px;margin:0 auto;background:#fff;min-height:100vh}
.hdr{background:linear-gradient(135deg,#1e3a8a,#2563eb);color:#fff;padding:20px 24px}
.hdr h1{font-size:20px;margin-bottom:4px}
.hdr .sub{opacity:.9;font-size:12px}
.body{padding:20px 24px}
.sec{margin-bottom:20px}
.sec h2{font-size:14px;color:#1e40af;border-bottom:2px solid #dbeafe;padding-bottom:6px;margin-bottom:10px}
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:8px 16px}
.grid2 div{font-size:12px}
.grid2 b{color:#64748b;font-weight:600;display:block;font-size:10px}
table{width:100%;border-collapse:collapse;font-size:11px;margin-top:8px}
th,td{border:1px solid #e2e8f0;padding:6px 8px;text-align:right}
th{background:#f8fafc;color:#475569}
.totals{background:#f0f9ff;border:1px solid #bfdbfe;border-radius:10px;padding:14px;margin-top:12px}
.totals .final{font-size:18px;font-weight:800;color:#1d4ed8;margin-top:8px}
.qr-box{text-align:center;padding:16px;background:#f8fafc;border-radius:12px;margin-top:16px}
.qr-box canvas,.qr-box img{max-width:140px}
.actions{padding:16px 24px;border-top:1px solid #e2e8f0;display:flex;gap:10px;justify-content:center}
.btn{background:#2563eb;color:#fff;border:none;padding:10px 20px;border-radius:8px;font-family:inherit;cursor:pointer;font-size:13px}
.btn--sec{background:#e2e8f0;color:#334155}
.tag{display:inline-block;background:#eff6ff;color:#1d4ed8;padding:2px 8px;border-radius:12px;font-size:10px;margin:2px}
.rec li{margin:4px 0 4px 16px;font-size:12px}
.stamp{display:flex;gap:24px;margin-top:20px;flex-wrap:wrap}
.stamp div{flex:1;min-width:140px;border-top:1px solid #94a3b8;padding-top:8px;font-size:11px;color:#64748b}
@media print{
    body{background:#fff}
    .actions{display:none!important}
    .wrap{box-shadow:none}
}
@media (max-width:640px){
    .grid2{grid-template-columns:1fr}
    .body{padding:14px 16px}
}
</style>
</head>
<body>
<div class="wrap">
    <div class="hdr">
        <h1>📄 گزارش فنی خدمات</h1>
        <div class="sub"><?= esc_html( $r['report_no'] ?? '' ) ?> · <?= esc_html( $r['report_date'] ?? substr( $r['created_at'] ?? '', 0, 10 ) ) ?></div>
    </div>
    <div class="body">
        <div class="sec">
            <h2>مشتری و پرونده</h2>
            <div class="grid2">
                <div><b>نام</b><?= esc_html( $r['customer_name'] ?? '' ) ?></div>
                <div><b>شرکت</b><?= esc_html( $r['company'] ?? '—' ) ?></div>
                <div><b>تلفن</b><span dir="ltr"><?= esc_html( $r['phone'] ?? '' ) ?></span></div>
                <div><b>موضع</b><?= esc_html( $r['site_label'] ?? '—' ) ?></div>
                <div><b>شناسه پرونده</b><?= esc_html( $r['case_no'] ?? '—' ) ?></div>
                <div><b>نوع خدمت</b><?= esc_html( $types[ $r['service_type'] ?? '' ] ?? ( $r['service_type'] ?? '' ) ) ?></div>
            </div>
        </div>

        <?php if ( ! empty( $snap ) ) : ?>
        <div class="sec">
            <h2>دستگاه</h2>
            <div class="grid2">
                <div><b>نوع</b><?= esc_html( $snap['device_type'] ?? '' ) ?></div>
                <div><b>برند/مدل</b><?= esc_html( ( $snap['brand'] ?? '' ) . ' ' . ( $snap['model'] ?? '' ) ) ?></div>
                <div><b>سریال</b><span dir="ltr"><?= esc_html( $snap['serial_no'] ?? '' ) ?></span></div>
                <div><b>ظرفیت</b><?= esc_html( $snap['capacity'] ?? '' ) ?></div>
                <div><b>مبرد</b><?= esc_html( $snap['refrigerant'] ?? '' ) ?></div>
                <div><b>محل نصب</b><?= esc_html( $snap['install_location'] ?? '' ) ?></div>
                <?php if ( ! empty( $snap['operating_hours'] ) ) : ?>
                <div><b>ساعت کارکرد</b><?= esc_html( (string) $snap['operating_hours'] ) ?></div>
                <?php endif; ?>
                <?php if ( ! empty( $snap['last_service_date'] ) ) : ?>
                <div><b>آخرین سرویس</b><?= esc_html( $snap['last_service_date'] ) ?></div>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>

        <?php
        $photos_b = $r['photos_before'] ?? [];
        $photos_a = $r['photos_after'] ?? [];
        if ( $photos_b || $photos_a ) :
        ?>
        <div class="sec">
            <h2>تصاویر قبل و بعد</h2>
            <?php if ( $photos_b ) : ?>
            <p style="font-size:11px;color:#64748b;margin-bottom:6px;">قبل از کار</p>
            <div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:12px;">
                <?php foreach ( (array) $photos_b as $src ) : if ( ! $src ) continue; ?>
                <img src="<?= esc_attr( $src ) ?>" alt="before" style="width:100px;height:100px;object-fit:cover;border-radius:8px;border:1px solid #e2e8f0;">
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
            <?php if ( $photos_a ) : ?>
            <p style="font-size:11px;color:#64748b;margin-bottom:6px;">بعد از کار</p>
            <div style="display:flex;flex-wrap:wrap;gap:8px;">
                <?php foreach ( (array) $photos_a as $src ) : if ( ! $src ) continue; ?>
                <img src="<?= esc_attr( $src ) ?>" alt="after" style="width:100px;height:100px;object-fit:cover;border-radius:8px;border:1px solid #e2e8f0;">
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php if ( ! empty( $r['complaint_text'] ) || ! empty( $r['complaint_tags'] ) ) : ?>
        <div class="sec">
            <h2>شرح درخواست</h2>
            <?php foreach ( (array) ( $r['complaint_tags'] ?? [] ) as $t ) : ?>
                <span class="tag"><?= esc_html( $t ) ?></span>
            <?php endforeach; ?>
            <p style="margin-top:8px;font-size:12px;"><?= nl2br( esc_html( $r['complaint_text'] ?? '' ) ) ?></p>
        </div>
        <?php endif; ?>

        <?php $tr = $r['technical_readings'] ?? []; if ( array_filter( $tr ) || ! empty( $r['diagnosis_result'] ) ) : ?>
        <div class="sec">
            <h2>گزارش کارشناسی</h2>
            <div class="grid2">
                <?php
                $labels = [
                    'suction_pressure' => 'فشار مکش', 'discharge_pressure' => 'فشار دهش',
                    'superheat' => 'سوپرهیت', 'subcool' => 'سابکول',
                    'compressor_amps' => 'آمپر', 'voltage' => 'ولتاژ',
                    'ambient_temp' => 'دمای محیط', 'inlet_temp' => 'دمای ورود',
                    'outlet_temp' => 'دمای خروج', 'oil_status' => 'روغن', 'filter_status' => 'فیلتر',
                ];
                foreach ( $labels as $k => $lbl ) :
                    if ( empty( $tr[ $k ] ) ) continue;
                ?>
                <div><b><?= esc_html( $lbl ) ?></b><?= esc_html( $tr[ $k ] ) ?></div>
                <?php endforeach; ?>
            </div>
            <?php if ( ! empty( $r['diagnosis_result'] ) ) : ?>
            <p style="margin-top:10px;font-size:12px;"><b>نتیجه عیب‌یابی:</b> <?= nl2br( esc_html( $r['diagnosis_result'] ) ) ?></p>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <?php self::_table_section( 'خدمات انجام‌شده', $r['service_lines'] ?? [], [ 'desc' => 'شرح', 'qty' => 'تعداد', 'unit' => 'واحد', 'unit_price' => 'قیمت واحد', 'total' => 'جمع' ] ); ?>
        <?php self::_table_section( 'قطعات مصرفی', $r['part_lines'] ?? [], [ 'name' => 'قطعه', 'part_no' => 'شماره فنی', 'qty' => 'تعداد', 'unit_price' => 'قیمت', 'total' => 'جمع' ] ); ?>
        <?php self::_table_section( 'مواد مصرفی', $r['material_lines'] ?? [], [ 'desc' => 'شرح', 'qty' => 'مقدار', 'unit' => 'واحد', 'unit_price' => 'قیمت', 'total' => 'جمع' ] ); ?>
        <?php self::_table_section( 'هزینه‌های جانبی', $r['extra_costs'] ?? [], [ 'desc' => 'شرح', 'amount' => 'مبلغ' ] ); ?>

        <?php if ( ! empty( $r['recommendations'] ) ) : ?>
        <div class="sec">
            <h2>پیشنهادهای فنی</h2>
            <ul class="rec">
                <?php foreach ( $r['recommendations'] as $rec ) : ?>
                <li><?= esc_html( $rec ) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>

        <div class="sec totals">
            <div>جمع خدمات: <?= $fmt( $r['subtotal_services'] ?? 0 ) ?></div>
            <div>جمع قطعات: <?= $fmt( $r['subtotal_parts'] ?? 0 ) ?></div>
            <div>جمع مواد: <?= $fmt( $r['subtotal_materials'] ?? 0 ) ?></div>
            <div>جمع جانبی: <?= $fmt( $r['subtotal_extra'] ?? 0 ) ?></div>
            <?php if ( (float) ( $r['discount'] ?? 0 ) > 0 ) : ?><div>تخفیف: −<?= $fmt( $r['discount'] ) ?></div><?php endif; ?>
            <?php if ( (float) ( $r['tax'] ?? 0 ) > 0 ) : ?><div>مالیات: +<?= $fmt( $r['tax'] ) ?></div><?php endif; ?>
            <div class="final">مبلغ نهایی: <?= $fmt( $r['total'] ?? 0 ) ?></div>
            <div>پرداخت‌شده: <?= $fmt( $r['paid'] ?? 0 ) ?> · مانده: <?= $fmt( $r['balance'] ?? 0 ) ?></div>
        </div>

        <div class="stamp">
            <div>امضای کارشناس<br><strong><?= esc_html( $r['tech_signature'] ?? '' ) ?></strong></div>
            <div>امضای مشتری<br><strong><?= esc_html( $r['customer_signature'] ?? '' ) ?></strong></div>
            <?php if ( ! empty( $r['company_stamp'] ) ) : ?>
            <div>مهر شرکت<br><strong><?= esc_html( $r['company_stamp'] ) ?></strong></div>
            <?php endif; ?>
        </div>

        <?php if ( ! empty( $r['public_token'] ) ) : ?>
        <div class="qr-box">
            <div style="font-size:11px;color:#64748b;margin-bottom:8px;">اسکن QR برای مشاهده آنلاین</div>
            <div id="qrcode"></div>
            <div style="font-size:10px;margin-top:8px;word-break:break-all;color:#94a3b8;"><?= esc_html( $url ) ?></div>
        </div>
        <?php endif; ?>
    </div>

    <?php if ( ! $print_mode ) : ?>
    <div class="actions">
        <button class="btn" onclick="window.print()">🖨️ چاپ / PDF</button>
        <button class="btn btn--sec" onclick="navigator.clipboard?.writeText(location.href)">📋 کپی لینک</button>
    </div>
    <?php endif; ?>
</div>
<script src="/acc-engine/assets/vendor/qrcode/qrcode.min.js"></script>
<script>
(function(){
    var url = <?= json_encode( $url, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) ?>;
    var el = document.getElementById('qrcode');
    if (!el || !url) return;
    // QR آفلاین — کتابخانه محلی assets/vendor/qrcode
    if (typeof QRCode === 'undefined') {
        el.innerHTML = '<div style="font-size:11px;padding:20px;">QR</div>';
        return;
    }
    new QRCode(el, { text: url, width: 140, height: 140, correctLevel: QRCode.CorrectLevel.M });
})();
</script>
</body>
</html>
        <?php
        return (string) ob_get_clean();
    }

    private static function _table_section( string $title, array $rows, array $cols ): void {
        if ( empty( $rows ) ) return;
        echo '<div class="sec"><h2>' . esc_html( $title ) . '</h2><table><thead><tr>';
        foreach ( $cols as $lbl ) echo '<th>' . esc_html( $lbl ) . '</th>';
        echo '</tr></thead><tbody>';
        foreach ( $rows as $row ) {
            echo '<tr>';
            foreach ( array_keys( $cols ) as $k ) {
                $v = $row[ $k ] ?? '';
                if ( in_array( $k, [ 'unit_price', 'total', 'amount' ], true ) && is_numeric( $v ) ) {
                    $v = number_format( (float) $v, 0, '.', ',' );
                }
                echo '<td>' . esc_html( (string) $v ) . '</td>';
            }
            echo '</tr>';
        }
        echo '</tbody></table></div>';
    }
}
