<?php
/**
 * payment_reports.php
 * صفحة بحث وفلترة وتقارير لعمليات السداد
 *
 * بتقرأ الإعدادات الأساسية تلقائيا من bot.php لو موجود في نفس المجلد
 * وبتعرض
 * - بحث وفلترة متقدمة
 * - إحصائيات سريعة
 * - عرض الصور
 * - تصدير CSV
 * - صفحة طباعة مناسبة للحفظ PDF من المتصفح
 * - PDF مباشر لو مكتبة Dompdf متثبتة
 * - حذف عملية بكلمة سر من ملف خارجي
 */

error_reporting(E_ALL);
ini_set('display_errors', '1');
date_default_timezone_set('Africa/Cairo');

/* =========================
   1) تحميل الإعدادات من bot.php
========================= */
$botConfig = loadBotConfig(__DIR__ . '/bot.php');

$dbHost = $botConfig['DB_HOST'] ?: '127.0.0.1';
$dbName = $botConfig['DB_NAME'] ?: 'PUT_DB_NAME_HERE';
$dbUser = $botConfig['DB_USER'] ?: 'PUT_DB_USER_HERE';
$dbPass = $botConfig['DB_PASS'] ?: 'PUT_DB_PASS_HERE';
$baseUrl = rtrim($botConfig['BASE_URL'] ?: 'https://your-domain.com', '/');
$uploadUrl = $baseUrl . '/uploads/payments';
$uploadDir = __DIR__ . '/uploads/payments';

$pdo = db($dbHost, $dbName, $dbUser, $dbPass);

$deleteConfig = loadDeleteConfig(__DIR__ . '/delete_config.php');
$deleteMessage = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_payment_id'])) {
    $deleteId = (int)$_POST['delete_payment_id'];
    $deletePassword = trim((string)($_POST['delete_password'] ?? ''));

    if ($deleteId > 0) {
        $deleteResult = deletePaymentById($pdo, $deleteId, $deletePassword, $deleteConfig, $uploadDir);
        $deleteMessage = $deleteResult['message'];

        $redirectParams = $_GET;
        $redirectParams['delete_msg'] = $deleteMessage;
        header('Location: ?' . http_build_query($redirectParams));
        exit;
    }
}

if (isset($_GET['delete_msg'])) {
    $deleteMessage = trim((string)$_GET['delete_msg']);
}

/* =========================
   2) الفلاتر
========================= */
$filters = [
    'id' => trim((string)($_GET['id'] ?? '')),
    'route_number' => trim((string)($_GET['route_number'] ?? '')),
    'invoice_number' => trim((string)($_GET['invoice_number'] ?? '')),
    'reference_number' => trim((string)($_GET['reference_number'] ?? '')),
    'accountant_telegram_id' => trim((string)($_GET['accountant_telegram_id'] ?? '')),
    'payment_method' => trim((string)($_GET['payment_method'] ?? '')),
    'status' => trim((string)($_GET['status'] ?? '')),
    'date_from' => trim((string)($_GET['date_from'] ?? '')),
    'date_to' => trim((string)($_GET['date_to'] ?? '')),
    'amount_min' => trim((string)($_GET['amount_min'] ?? '')),
    'amount_max' => trim((string)($_GET['amount_max'] ?? '')),
    'duplicate_only' => trim((string)($_GET['duplicate_only'] ?? '')),
    'q' => trim((string)($_GET['q'] ?? '')),
];

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = min(200, max(10, (int)($_GET['per_page'] ?? 25)));
$offset = ($page - 1) * $perPage;
$action = trim((string)($_GET['action'] ?? ''));

$queryParts = buildPaymentsQuery($filters);
$stats = fetchStats($pdo, $queryParts['where'], $queryParts['params']);
$totalRows = fetchTotal($pdo, $queryParts['where'], $queryParts['params']);
$rows = fetchRows($pdo, $queryParts['where'], $queryParts['params'], $offset, $perPage);

if ($action === 'csv') {
    exportCsv($rows);
}

if ($action === 'print') {
    renderPrintPage($rows, $filters, $stats, $uploadUrl);
    exit;
}

if ($action === 'pdf') {
    $html = buildPrintableHtml($rows, $filters, $stats, $uploadUrl, true);
    if (streamPdfIfPossible($html)) {
        exit;
    }
    renderPrintPage($rows, $filters, $stats, $uploadUrl);
    exit;
}

$totalPages = max(1, (int)ceil($totalRows / $perPage));

/* =========================
   3) الواجهة
========================= */
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>تقارير السداد</title>
    <style>
        body{font-family:Tahoma,Arial,sans-serif;background:#f5f7fb;margin:0;color:#222}
        .wrap{max-width:1400px;margin:20px auto;padding:0 16px}
        .card{background:#fff;border-radius:14px;padding:16px;margin-bottom:16px;box-shadow:0 4px 20px rgba(0,0,0,.06)}
        h1,h2,h3{margin:0 0 12px}
        .grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px}
        .grid-2{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
        .stat{padding:14px;border-radius:12px;background:#fafafa;border:1px solid #eee}
        label{display:block;font-size:13px;margin-bottom:6px;color:#555}
        input,select{width:100%;box-sizing:border-box;padding:10px;border:1px solid #d8dde6;border-radius:10px;background:#fff}
        .actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:10px}
        .btn{display:inline-block;text-decoration:none;border:none;background:#0b5ed7;color:#fff;padding:10px 14px;border-radius:10px;cursor:pointer}
        .btn.secondary{background:#6c757d}
        .btn.success{background:#198754}
        .btn.dark{background:#212529}
        .btn.warn{background:#fd7e14}
        .btn.danger{background:#dc3545}
        table{width:100%;border-collapse:collapse;font-size:14px}
        th,td{padding:10px;border-bottom:1px solid #eee;vertical-align:top;text-align:right}
        th{background:#fafafa;position:sticky;top:0}
        .status{padding:4px 8px;border-radius:999px;font-size:12px;display:inline-block}
        .approved{background:#d1e7dd;color:#0f5132}
        .duplicate{background:#f8d7da;color:#842029}
        .rejected{background:#f8d7da;color:#842029}
        .under_review{background:#fff3cd;color:#664d03}
        .thumb{width:90px;height:90px;object-fit:cover;border-radius:10px;border:1px solid #eee}
        .pager{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
        .muted{color:#6b7280;font-size:12px}
        .small{font-size:12px}
        .alert{
            padding:12px;
            border-radius:10px;
            margin-bottom:12px;
            background:#fff3cd;
            border:1px solid #ffe69c;
            color:#664d03;
        }
        .delete-form{
            display:flex;
            flex-direction:column;
            gap:6px;
            min-width:150px;
        }
        .delete-form input{
            padding:8px;
            font-size:12px;
        }
        @media (max-width:1100px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
        @media (max-width:700px){.grid,.grid-2{grid-template-columns:1fr} table{font-size:12px}.thumb{width:70px;height:70px}}
    </style>
</head>
<body>
<div class="wrap">
    <div class="card">
        <h1>تقارير السداد</h1>
        <div class="muted">البيانات مقروءة من جدول payments والصور من مجلد uploads/payments</div>
    </div>

    <?php if ($deleteMessage !== ''): ?>
    <div class="card">
        <div class="alert"><?php echo h($deleteMessage); ?></div>
    </div>
    <?php endif; ?>

    <div class="card">
        <h2>إحصائيات سريعة</h2>
        <div class="grid">
            <div class="stat"><strong>إجمالي النتائج</strong><br><?php echo h((string)$totalRows); ?></div>
            <div class="stat"><strong>إجمالي المبالغ</strong><br><?php echo h(number_format((float)$stats['total_amount'], 2)); ?></div>
            <div class="stat"><strong>عمليات معتمدة</strong><br><?php echo h((string)$stats['approved_count']); ?></div>
            <div class="stat"><strong>عمليات مكررة</strong><br><?php echo h((string)$stats['duplicate_count']); ?></div>
        </div>
    </div>

    <div class="card">
        <h2>البحث والفلترة</h2>
        <form method="get">
            <div class="grid">
                <div>
                    <label>بحث عام</label>
                    <input type="text" name="q" value="<?php echo h($filters['q']); ?>" placeholder="رقم خط السير أو الفاتورة أو المرجع أو مبلغ أو محاسب">
                </div>
                <div>
                    <label>رقم العملية</label>
                    <input type="text" name="id" value="<?php echo h($filters['id']); ?>">
                </div>
                <div>
                    <label>رقم خط السير</label>
                    <input type="text" name="route_number" value="<?php echo h($filters['route_number']); ?>">
                </div>
                <div>
                    <label>رقم الفاتورة</label>
                    <input type="text" name="invoice_number" value="<?php echo h($filters['invoice_number']); ?>">
                </div>
                <div>
                    <label>الرقم المرجعي</label>
                    <input type="text" name="reference_number" value="<?php echo h($filters['reference_number']); ?>">
                </div>
                <div>
                    <label>المحاسب Telegram ID</label>
                    <input type="text" name="accountant_telegram_id" value="<?php echo h($filters['accountant_telegram_id']); ?>">
                </div>
                <div>
                    <label>نوع الدفع</label>
                    <select name="payment_method">
                        <?php echo selectOptions([
                            '' => 'الكل',
                            'instapay' => 'انستا باي',
                            'phone_cash' => 'فون كاش',
                            'bank_transfer' => 'تحويل بنكي',
                        ], $filters['payment_method']); ?>
                    </select>
                </div>
                <div>
                    <label>الحالة</label>
                    <select name="status">
                        <?php echo selectOptions([
                            '' => 'الكل',
                            'approved' => 'approved',
                            'duplicate' => 'duplicate',
                            'rejected' => 'rejected',
                            'under_review' => 'under_review',
                        ], $filters['status']); ?>
                    </select>
                </div>
                <div>
                    <label>عمليات مكررة فقط</label>
                    <select name="duplicate_only">
                        <?php echo selectOptions(['' => 'الكل', '1' => 'نعم'], $filters['duplicate_only']); ?>
                    </select>
                </div>
                <div>
                    <label>من تاريخ</label>
                    <input type="date" name="date_from" value="<?php echo h($filters['date_from']); ?>">
                </div>
                <div>
                    <label>إلى تاريخ</label>
                    <input type="date" name="date_to" value="<?php echo h($filters['date_to']); ?>">
                </div>
                <div>
                    <label>أقل مبلغ</label>
                    <input type="number" step="0.01" name="amount_min" value="<?php echo h($filters['amount_min']); ?>">
                </div>
                <div>
                    <label>أعلى مبلغ</label>
                    <input type="number" step="0.01" name="amount_max" value="<?php echo h($filters['amount_max']); ?>">
                </div>
            </div>
            <div class="actions">
                <button class="btn" type="submit">بحث</button>
                <a class="btn secondary" href="payment_reports.php">مسح الفلاتر</a>
                <a class="btn success" href="?<?php echo h(buildQueryString(array_merge($_GET, ['action' => 'csv', 'page' => 1]))); ?>">تصدير CSV</a>
                <a class="btn dark" target="_blank" href="?<?php echo h(buildQueryString(array_merge($_GET, ['action' => 'print', 'page' => 1]))); ?>">نسخة طباعة</a>
                <a class="btn warn" target="_blank" href="?<?php echo h(buildQueryString(array_merge($_GET, ['action' => 'pdf', 'page' => 1]))); ?>">تصدير PDF</a>
            </div>
        </form>
    </div>

    <div class="card">
        <h2>النتائج</h2>
        <div class="muted">عدد النتائج في الصفحة الحالية <?php echo h((string)count($rows)); ?> من أصل <?php echo h((string)$totalRows); ?></div>
        <div style="overflow:auto;margin-top:12px">
            <table>
                <thead>
                <tr>
                    <th>رقم خط السير</th>
                    <th>رقم العملية</th>
                    <th>رقم الفاتورة</th>
                    <th>المبلغ</th>
                    <th>التاريخ</th>
                    <th>الوقت</th>
                    <th>المرجع</th>
                    <th>نوع الدفع</th>
                    <th>الحالة</th>
                    <th>المحاسب</th>
                    <th>سبب التكرار</th>
                    <th>الصورة</th>
                    <th>وقت التسجيل</th>
                    <th>حذف</th>
                </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr><td colspan="14">لا توجد نتائج</td></tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <tr>
                            <td><?php echo h($row['route_number']); ?></td>
                            <td><?php echo h($row['id']); ?></td>
                            <td><?php echo h($row['invoice_number']); ?></td>
                            <td><?php echo h(number_format((float)$row['amount'], 2)); ?></td>
                            <td><?php echo h($row['payment_date']); ?></td>
                            <td><?php echo h($row['payment_time']); ?></td>
                            <td><?php echo h($row['reference_number']); ?></td>
                            <td><?php echo h(arPaymentMethod($row['payment_method'])); ?></td>
                            <td><span class="status <?php echo h($row['status']); ?>"><?php echo h($row['status']); ?></span></td>
                            <td><?php echo h($row['accountant_telegram_id']); ?></td>
                            <td class="small"><?php echo h($row['duplicate_reason'] ?: '-'); ?></td>
                            <td>
                                <?php if (!empty($row['screenshot_file'])): ?>
                                    <a target="_blank" href="<?php echo h($uploadUrl . '/' . rawurlencode($row['screenshot_file'])); ?>">
                                        <img class="thumb" src="<?php echo h($uploadUrl . '/' . rawurlencode($row['screenshot_file'])); ?>" alt="img">
                                    </a>
                                <?php else: ?>-
                                <?php endif; ?>
                            </td>
                            <td><?php echo h($row['created_at']); ?></td>
                            <td>
                                <form method="post" class="delete-form" onsubmit="return confirm('متأكد إنك عايز تحذف العملية دي');">
                                    <input type="hidden" name="delete_payment_id" value="<?php echo h($row['id']); ?>">
                                    <input type="password" name="delete_password" placeholder="كلمة سر الحذف" required>
                                    <button type="submit" class="btn danger">حذف</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card">
        <div class="pager">
            <span>الصفحة <?php echo h((string)$page); ?> من <?php echo h((string)$totalPages); ?></span>
            <?php if ($page > 1): ?>
                <a class="btn secondary" href="?<?php echo h(buildQueryString(array_merge($_GET, ['page' => $page - 1]))); ?>">السابق</a>
            <?php endif; ?>
            <?php if ($page < $totalPages): ?>
                <a class="btn secondary" href="?<?php echo h(buildQueryString(array_merge($_GET, ['page' => $page + 1]))); ?>">التالي</a>
            <?php endif; ?>
        </div>
    </div>
</div>
</body>
</html>
<?php

/* =========================
   4) دوال قاعدة البيانات والاستعلام
========================= */
function db($host, $db, $user, $pass)
{
    static $pdo = null;
    if ($pdo instanceof PDO) {
        return $pdo;
    }

    $dsn = 'mysql:host=' . $host . ';dbname=' . $db . ';charset=utf8mb4';
    $pdo = new PDO($dsn, $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);
    return $pdo;
}

function buildPaymentsQuery(array $filters)
{
    $where = ['1=1'];
    $params = [];

    if ($filters['id'] !== '') {
        $where[] = 'id = :id';
        $params[':id'] = (int)$filters['id'];
    }

    if ($filters['route_number'] !== '') {
        $where[] = 'route_number LIKE :route_number';
        $params[':route_number'] = '%' . $filters['route_number'] . '%';
    }

    if ($filters['invoice_number'] !== '') {
        $where[] = 'invoice_number LIKE :invoice_number';
        $params[':invoice_number'] = '%' . $filters['invoice_number'] . '%';
    }

    if ($filters['reference_number'] !== '') {
        $where[] = 'reference_number LIKE :reference_number';
        $params[':reference_number'] = '%' . $filters['reference_number'] . '%';
    }

    if ($filters['accountant_telegram_id'] !== '') {
        $where[] = 'accountant_telegram_id = :accountant_telegram_id';
        $params[':accountant_telegram_id'] = $filters['accountant_telegram_id'];
    }

    if ($filters['payment_method'] !== '') {
        $where[] = 'payment_method = :payment_method';
        $params[':payment_method'] = $filters['payment_method'];
    }

    if ($filters['status'] !== '') {
        $where[] = 'status = :status';
        $params[':status'] = $filters['status'];
    }

    if ($filters['date_from'] !== '') {
        $where[] = 'payment_date >= :date_from';
        $params[':date_from'] = $filters['date_from'];
    }

    if ($filters['date_to'] !== '') {
        $where[] = 'payment_date <= :date_to';
        $params[':date_to'] = $filters['date_to'];
    }

    if ($filters['amount_min'] !== '') {
        $where[] = 'amount >= :amount_min';
        $params[':amount_min'] = (float)$filters['amount_min'];
    }

    if ($filters['amount_max'] !== '') {
        $where[] = 'amount <= :amount_max';
        $params[':amount_max'] = (float)$filters['amount_max'];
    }

    if ($filters['duplicate_only'] === '1') {
        $where[] = 'status = :duplicate_only_status';
        $params[':duplicate_only_status'] = 'duplicate';
    }

    if ($filters['q'] !== '') {
        $where[] = '(route_number LIKE :q OR invoice_number LIKE :q OR reference_number LIKE :q OR accountant_telegram_id LIKE :q OR CAST(id AS CHAR) LIKE :q OR CAST(amount AS CHAR) LIKE :q)';
        $params[':q'] = '%' . $filters['q'] . '%';
    }

    return [
        'where' => implode(' AND ', $where),
        'params' => $params,
    ];
}

function fetchTotal(PDO $pdo, $where, array $params)
{
    $stmt = $pdo->prepare("SELECT COUNT(*) AS cnt FROM payments WHERE {$where}");
    $stmt->execute($params);
    $row = $stmt->fetch();
    return $row ? (int)$row['cnt'] : 0;
}

function fetchStats(PDO $pdo, $where, array $params)
{
    $stmt = $pdo->prepare("SELECT
        COUNT(*) AS total_count,
        COALESCE(SUM(amount),0) AS total_amount,
        SUM(CASE WHEN status='approved' THEN 1 ELSE 0 END) AS approved_count,
        SUM(CASE WHEN status='duplicate' THEN 1 ELSE 0 END) AS duplicate_count
        FROM payments WHERE {$where}");
    $stmt->execute($params);
    $row = $stmt->fetch();
    return $row ?: ['total_count' => 0, 'total_amount' => 0, 'approved_count' => 0, 'duplicate_count' => 0];
}

function fetchRows(PDO $pdo, $where, array $params, $offset, $limit)
{
    $sql = "SELECT * FROM payments WHERE {$where} ORDER BY id DESC LIMIT :offset, :limit";
    $stmt = $pdo->prepare($sql);
    foreach ($params as $k => $v) {
        $stmt->bindValue($k, $v);
    }
    $stmt->bindValue(':offset', (int)$offset, PDO::PARAM_INT);
    $stmt->bindValue(':limit', (int)$limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

/* =========================
   5) التصدير والطباعة
========================= */
function exportCsv(array $rows)
{
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=payments_report_' . date('Ymd_His') . '.csv');

    $fp = fopen('php://output', 'w');
    fputcsv($fp, ['route_number','id','invoice_number','amount','payment_date','payment_time','reference_number','payment_method','status','accountant_telegram_id','duplicate_reason','screenshot_file','created_at']);
    foreach ($rows as $row) {
        fputcsv($fp, [
            $row['route_number'],
            $row['id'],
            $row['invoice_number'],
            $row['amount'],
            $row['payment_date'],
            $row['payment_time'],
            $row['reference_number'],
            $row['payment_method'],
            $row['status'],
            $row['accountant_telegram_id'],
            $row['duplicate_reason'],
            $row['screenshot_file'],
            $row['created_at'],
        ]);
    }
    fclose($fp);
    exit;
}

function renderPrintPage(array $rows, array $filters, array $stats, $uploadUrl)
{
    echo buildPrintableHtml($rows, $filters, $stats, $uploadUrl, false);
}

function buildPrintableHtml(array $rows, array $filters, array $stats, $uploadUrl, $forPdf = false)
{
    ob_start();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
<meta charset="utf-8">
<title>تقرير السداد</title>

<style>
@page{
    size:A4;
    margin:8mm;
}

html, body{
    margin:0;
    padding:0;
    background:#fff;
    direction:rtl;
    font-family:DejaVu Sans, Tahoma, Arial, sans-serif;
    color:#111;
}

.print-btn{
    display:inline-block;
    margin:12px;
    padding:10px 14px;
    background:#111;
    color:#fff;
    text-decoration:none;
    border-radius:8px;
    font-size:14px;
}

.page{
    width:194mm;
    height:281mm;
    box-sizing:border-box;
    page-break-after:always;
    page-break-inside:avoid;
    break-inside:avoid;
    overflow:hidden;
    display:flex;
    flex-direction:column;
    justify-content:flex-start;
    padding:4mm;
}

.title{
    text-align:center;
    font-size:18px;
    font-weight:bold;
    margin-bottom:4mm;
    flex:0 0 auto;
}

.img-box{
    width:100%;
    height:175mm;
    border:1px solid #ccc;
    border-radius:8px;
    box-sizing:border-box;
    overflow:hidden;
    display:flex;
    align-items:center;
    justify-content:center;
    background:#fff;
    flex:0 0 auto;
}

.img-box img{
    max-width:100%;
    max-height:100%;
    width:auto;
    height:auto;
    object-fit:contain;
    display:block;
}

.no-image{
    font-size:16px;
    color:#666;
}

.details{
    margin-top:4mm;
    flex:1 1 auto;
    overflow:hidden;
}

.details table{
    width:100%;
    border-collapse:collapse;
    table-layout:fixed;
}

.details td{
    border:1px solid #ddd;
    padding:6px 8px;
    vertical-align:top;
    font-size:13px;
    word-wrap:break-word;
    overflow-wrap:break-word;
}

.details td.label{
    width:32%;
    font-weight:bold;
    background:#f7f7f7;
}

@media print{
    .print-btn{
        display:none !important;
    }

    html, body{
        width:210mm;
        height:297mm;
    }

    .page{
        margin:0;
    }
}
</style>
</head>
<body>

<?php if (!$forPdf): ?>
<a href="#" class="print-btn" onclick="window.print();return false;">طباعة / حفظ PDF</a>
<?php endif; ?>

<?php foreach ($rows as $index => $row): ?>
<div class="page">
    <div class="title">
        عملية رقم <?php echo h($row['id']); ?>
    </div>

    <div class="img-box">
        <?php if (!empty($row['screenshot_file'])): ?>
            <img src="<?php echo h($uploadUrl . '/' . rawurlencode($row['screenshot_file'])); ?>" alt="payment image">
        <?php else: ?>
            <div class="no-image">لا توجد صورة</div>
        <?php endif; ?>
    </div>

    <div class="details">
        <table>
            <tr>
                <td class="label">رقم خط السير</td>
                <td><?php echo h($row['route_number']); ?></td>
            </tr>
            <tr>
                <td class="label">رقم العملية</td>
                <td><?php echo h($row['id']); ?></td>
            </tr>
            <tr>
                <td class="label">رقم الفاتورة</td>
                <td><?php echo h($row['invoice_number']); ?></td>
            </tr>
            <tr>
                <td class="label">المبلغ</td>
                <td><?php echo h(number_format((float)$row['amount'], 2)); ?></td>
            </tr>
            <tr>
                <td class="label">التاريخ</td>
                <td><?php echo h($row['payment_date']); ?></td>
            </tr>
            <tr>
                <td class="label">الوقت</td>
                <td><?php echo h($row['payment_time']); ?></td>
            </tr>
            <tr>
                <td class="label">الرقم المرجعي</td>
                <td><?php echo h($row['reference_number']); ?></td>
            </tr>
            <tr>
                <td class="label">نوع الدفع</td>
                <td><?php echo h(arPaymentMethod($row['payment_method'])); ?></td>
            </tr>
            <tr>
                <td class="label">الحالة</td>
                <td><?php echo h($row['status']); ?></td>
            </tr>
            <tr>
                <td class="label">المحاسب</td>
                <td><?php echo h($row['accountant_telegram_id']); ?></td>
            </tr>
            <tr>
                <td class="label">سبب التكرار</td>
                <td><?php echo h($row['duplicate_reason'] ?: '-'); ?></td>
            </tr>
            <tr>
                <td class="label">وقت التسجيل</td>
                <td><?php echo h($row['created_at']); ?></td>
            </tr>
        </table>
    </div>
</div>
<?php endforeach; ?>

</body>
</html>
<?php
    return ob_get_clean();
}

function streamPdfIfPossible($html)
{
    if (class_exists('Dompdf\\Dompdf')) {
        $dompdf = new Dompdf\Dompdf(['isRemoteEnabled' => true]);
        $dompdf->loadHtml($html, 'UTF-8');
        $dompdf->setPaper('A4', 'portrait');
        $dompdf->render();
        $dompdf->stream('payments_report_' . date('Ymd_His') . '.pdf', ['Attachment' => true]);
        return true;
    }

    if (file_exists(__DIR__ . '/vendor/autoload.php')) {
        require_once __DIR__ . '/vendor/autoload.php';
        if (class_exists('Dompdf\\Dompdf')) {
            $dompdf = new Dompdf\Dompdf(['isRemoteEnabled' => true]);
            $dompdf->loadHtml($html, 'UTF-8');
            $dompdf->setPaper('A4', 'portrait');
            $dompdf->render();
            $dompdf->stream('payments_report_' . date('Ymd_His') . '.pdf', ['Attachment' => true]);
            return true;
        }
    }

    return false;
}

/* =========================
   6) حذف بكلمة سر
========================= */
function loadDeleteConfig($file)
{
    if (!file_exists($file)) {
        return [
            'delete_password' => ''
        ];
    }

    $config = require $file;

    if (!is_array($config)) {
        return [
            'delete_password' => ''
        ];
    }

    return $config;
}

function deletePaymentById(PDO $pdo, $paymentId, $password, array $deleteConfig, $uploadDir)
{
    $savedPassword = trim((string)($deleteConfig['delete_password'] ?? ''));

    if ($savedPassword === '') {
        return [
            'ok' => false,
            'message' => 'ملف كلمة سر الحذف غير مضبوط'
        ];
    }

    if ($password === '' || $password !== $savedPassword) {
        return [
            'ok' => false,
            'message' => 'كلمة السر غير صحيحة'
        ];
    }

    $stmt = $pdo->prepare("SELECT * FROM payments WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $paymentId]);
    $row = $stmt->fetch();

    if (!$row) {
        return [
            'ok' => false,
            'message' => 'العملية غير موجودة'
        ];
    }

    $pdo->beginTransaction();

    try {
        $stmt = $pdo->prepare("DELETE FROM payments WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $paymentId]);
        $pdo->commit();
    } catch (Exception $e) {
        $pdo->rollBack();
        return [
            'ok' => false,
            'message' => 'حصل خطأ أثناء الحذف'
        ];
    }

    if (!empty($row['screenshot_file'])) {
        $photoPath = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . $row['screenshot_file'];
        if (is_file($photoPath)) {
            @unlink($photoPath);
        }
    }

    return [
        'ok' => true,
        'message' => 'تم حذف العملية بنجاح'
    ];
}
/* =========================
   7) مساعدات
========================= */
function loadBotConfig($botFile)
{
    $result = [
        'DB_HOST' => '',
        'DB_NAME' => '',
        'DB_USER' => '',
        'DB_PASS' => '',
        'BASE_URL' => '',
    ];

    if (!file_exists($botFile)) {
        return $result;
    }

    $content = file_get_contents($botFile);
    foreach ($result as $key => $v) {
        if (preg_match("/const\\s+" . preg_quote($key, '/') . "\\s*=\\s*'([^']*)'\\s*;/", $content, $m)) {
            $result[$key] = $m[1];
        }
    }

    return $result;
}

function h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function buildQueryString(array $params)
{
    return http_build_query($params);
}

function selectOptions(array $options, $selected)
{
    $html = '';
    foreach ($options as $value => $label) {
        $sel = ((string)$value === (string)$selected) ? ' selected' : '';
        $html .= '<option value="' . h($value) . '"' . $sel . '>' . h($label) . '</option>';
    }
    return $html;
}

function arPaymentMethod($method)
{
    if ($method === 'instapay') return 'انستا باي';
    if ($method === 'phone_cash') return 'فون كاش';
    if ($method === 'bank_transfer') return 'تحويل بنكي';
    return $method;
}