<?php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) session_start();

require_once __DIR__ . '/helpers.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db_bootstrap.php';
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/app_assets.php';
require_once __DIR__ . '/output_devices_lib.php';
require_once __DIR__ . '/subscriber_router_setup_lib.php';
require_once __DIR__ . '/company_profile_lib.php';
require_once __DIR__ . '/subscribers_lib.php';

$agentId = max(0, (int)($_GET['agent'] ?? 0));
$editToken = strtolower(trim((string)($_GET['agent_edit_token'] ?? '')));
$agentMode = $agentId > 0;

if ($agentMode) {
    require_once __DIR__ . '/agent_portal_lib.php';
    require_once __DIR__ . '/agent_edit_request_lib.php';
    $conn = ensure_db(true);
    $agentContext = agent_portal_boot($conn);
    $agent = $agentContext['agent'] ?? null;
    if (!$agent || empty($agentContext['logged']) || (int)($agentContext['agent_id'] ?? 0) !== $agentId) {
        header('Location: agent_portal.php?agent=' . $agentId);
        exit;
    }
} else {
    require_login('index.php?login=1');
    if (function_exists('require_perm')) require_perm('can_view_subscribers');
    $conn = ensure_db(true);
}

if (!($conn instanceof mysqli)) {
    http_response_code(500);
    exit('Database connection error');
}
subs_ensure_pppoe_cols($conn);

$subscriberId = max(0, (int)($_GET['subscriber_id'] ?? 0));
if ($subscriberId <= 0) {
    http_response_code(422);
    exit('رقم المشترك غير صالح.');
}

$stmt = $conn->prepare("SELECT * FROM subscribers WHERE id=? AND COALESCE(is_deleted,0)=0 LIMIT 1");
$stmt->bind_param('i', $subscriberId);
$stmt->execute();
$subscriber = $stmt->get_result()->fetch_assoc() ?: null;
$stmt->close();
if (!$subscriber) {
    http_response_code(404);
    exit('المشترك غير موجود.');
}

if ($agentMode) {
    $ownsSubscriber = strtolower(trim((string)($subscriber['created_by_type'] ?? ''))) === 'agent'
        && (int)($subscriber['created_by_id'] ?? 0) === $agentId;
    $hasEditGrant = $editToken !== ''
        && ua_agent_edit_request_is_granted($conn, $editToken, $agentId, $subscriberId);
    if (!$ownsSubscriber && !$hasEditGrant) {
        http_response_code(403);
        exit('لا توجد موافقة صالحة لطباعة معلومات هذا المشترك.');
    }
}

function sip_first_value(array $row, array $keys, string $fallback = ''): string
{
    foreach ($keys as $key) {
        $value = trim((string)($row[$key] ?? ''));
        if ($value !== '') return $value;
    }
    return $fallback;
}

function sip_company_logo(string $logoPath): string
{
    $logoPath = trim($logoPath);
    if ($logoPath === '') return '';
    if (preg_match('~^https?://~i', $logoPath)) return $logoPath;
    $clean = ltrim(str_replace('\\', '/', $logoPath), '/');
    return is_file(__DIR__ . '/' . $clean)
        ? $clean . '?v=' . (int)(@filemtime(__DIR__ . '/' . $clean) ?: time())
        : '';
}

$company = company_profile_fetch($conn);
$companyContacts = company_profile_contact_lines($company);
$programName = company_profile_program_name();
$companyLogo = sip_company_logo($company['logo_path']);

$fullName = sip_first_value($subscriber, ['full_name', 'name'], 'المشترك #' . $subscriberId);
$phone = sip_first_value($subscriber, ['phone', 'mobile']);
$address = sip_first_value($subscriber, ['address_area', 'address']);
$nationalId = sip_first_value($subscriber, ['national_id']);
$documentType = sip_first_value($subscriber, ['document_type']);
$documentNumber = sip_first_value($subscriber, ['document_number']);
$credentialMode = strtolower(trim((string)($_GET['credentials'] ?? 'current')));
$encryptedRequested = $credentialMode === 'encrypted';
$stagedAccountStatus = $encryptedRequested
    ? subs_policy_staged_account_status($conn, $subscriber)
    : ['ready'=>false,'stale'=>false,'message'=>''];
$useEncryptedCredentials = $encryptedRequested && !empty($stagedAccountStatus['ready']);
$credentialPolicyError = $encryptedRequested && !$useEncryptedCredentials
    ? (string)($stagedAccountStatus['message'] ?? 'لا توجد بيانات تشفير مجهزة وفق إعداد البرنامج الحالي.')
    : '';
$pppUsername = $useEncryptedCredentials
    ? trim((string)$subscriber['pending_ppp_username'])
    : ($encryptedRequested ? '' : sip_first_value($subscriber, ['ppp_username', 'username']));
$pppPassword = $useEncryptedCredentials
    ? (string)($subscriber['pending_ppp_password'] ?? '')
    : ($encryptedRequested ? '' : sip_first_value($subscriber, ['ppp_password', 'password_plain']));
$packageName = sip_first_value($subscriber, ['package_name'], '—');
$rateLimit = $useEncryptedCredentials
    ? trim((string)($subscriber['pending_ppp_rate_limit'] ?? ''))
    : ($encryptedRequested ? '—' : sip_first_value($subscriber, ['ppp_rate_limit', 'mt_rate_limit'], '—'));
$rateLimit = subs_rate_limit_display($rateLimit);
$profile = $useEncryptedCredentials
    ? trim((string)($subscriber['pending_ppp_profile'] ?? ''))
    : ($encryptedRequested ? '—' : sip_first_value($subscriber, ['ppp_profile', 'pppoe_profile', 'mt_profile'], '—'));
$speedName = subs_speed_display($subscriber, $profile) ?: '—';
$ipAddress = sip_first_value($subscriber, ['ip_address']);
$ipType = $ipAddress !== '' ? 'IP ثابت' : 'IP ديناميكي';
$reservation = $ipAddress !== '' ? $ipAddress : 'من الـ Pool / غير محدد';
$quota = sip_first_value($subscriber, ['quota_gb']);
$quotaLabel = $quota !== '' ? $quota . ' GB' : 'مفتوح / غير محدد';

$includeWifi = (string)($_GET['include_wifi'] ?? '') === '1';
$setupId = max(0, (int)($_GET['setup_id'] ?? 0));
$wifiRows = [];
if ($includeWifi) {
    srs_ensure_schema($conn);
    $setupSql = 'SELECT id,encrypted_payload FROM subscriber_router_setups WHERE subscriber_id=?';
    if ($setupId > 0) $setupSql .= ' AND id=' . $setupId;
    $setupSql .= ' ORDER BY id DESC LIMIT 1';
    $setupStmt = $conn->prepare($setupSql);
    $setupStmt->bind_param('i', $subscriberId);
    $setupStmt->execute();
    $setup = $setupStmt->get_result()->fetch_assoc() ?: null;
    $setupStmt->close();
    if ($setup) {
        $payload = srs_decrypt((string)$setup['encrypted_payload']);
        $candidateWifi = $payload['wifi'] ?? [];
        if (is_array($candidateWifi)) {
            foreach ($candidateWifi as $wifi) {
                if (!is_array($wifi)) continue;
                $ssid = trim((string)($wifi['ssid'] ?? ''));
                $password = (string)($wifi['password'] ?? '');
                if ($ssid === '') continue;
                $wifiRows[] = [
                    'label' => trim((string)($wifi['label'] ?? 'Wi-Fi')) ?: 'Wi-Fi',
                    'ssid' => $ssid,
                    'password' => $password,
                    'qr' => trim((string)($wifi['qr'] ?? ''))
                        ?: srs_wifi_qr_payload($ssid, $password, !empty($wifi['hidden'])),
                ];
            }
        }
    }
}

$accountQr = "PPPoE\nUsername: {$pppUsername}\nPassword: {$pppPassword}";
$autoPrint = (string)($_GET['auto'] ?? '') === '1' && $credentialPolicyError === '';
$backUrl = $agentMode
    ? ('agent_portal.php?agent=' . $agentId)
    : ('subscribers_edit.php?id=' . $subscriberId);

?><!doctype html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>بطاقة معلومات <?= h($fullName) ?></title>
    <link rel="stylesheet" href="assets/css/subscriber_info_print.css?v=<?= (int)(@filemtime(__DIR__ . '/assets/css/subscriber_info_print.css') ?: 1) ?>">
</head>
<body>
<div class="sip-toolbar" aria-label="إجراءات الطباعة">
    <a href="<?= h($backUrl) ?>">رجوع</a>
    <button type="button" id="sipPrintButton" <?= $credentialPolicyError !== '' ? 'disabled' : '' ?>>طباعة البطاقة</button>
</div>

<main class="sip-sheet">
    <header class="sip-header">
        <div class="sip-company-copy">
            <h1><?= h($company['company_name']) ?></h1>
            <?php if($company['address'] !== '' || $companyContacts): ?>
                <p class="sip-company-contacts">
                  <?php if($company['address'] !== ''): ?><span><?= h($company['address']) ?></span><?php endif; ?>
                  <?php foreach($companyContacts as $contact): ?><span><b><?= h((string)$contact['label']) ?>:</b> <span dir="ltr"><?= h((string)$contact['value']) ?></span></span><?php endforeach; ?>
                </p>
            <?php endif; ?>
        </div>
        <div class="sip-company-mark">
            <?php if($companyLogo !== ''): ?>
                <img src="<?= h($companyLogo) ?>" alt="<?= h($company['company_name']) ?>">
            <?php else: ?>
                <span><?= h(mb_substr($company['company_name'], 0, 1, 'UTF-8')) ?></span>
            <?php endif; ?>
        </div>
    </header>

    <section class="sip-title">
        <div>
            <span>بطاقة معلومات المشترك</span>
            <h2><?= h($fullName) ?></h2>
        </div>
        <strong>#<?= (int)$subscriberId ?></strong>
    </section>
    <?php if($credentialPolicyError !== ''): ?><div class="sip-policy-warning"><b>تعذر استخدام البيانات المشفرة المجهزة</b><span><?= h($credentialPolicyError) ?></span></div><?php endif; ?>
    <div class="sip-sections">
        <section class="sip-card sip-personal">
            <h3>المعلومات الشخصية</h3>
            <dl>
                <div><dt>الاسم الثلاثي</dt><dd><?= h($fullName) ?></dd></div>
                <div><dt>رقم المشترك</dt><dd>#<?= (int)$subscriberId ?></dd></div>
                <div><dt>رقم الهاتف</dt><dd dir="ltr"><?= h($phone ?: '—') ?></dd></div>
                <div class="sip-wide"><dt>العنوان</dt><dd><?= h($address ?: '—') ?></dd></div>
                <?php if($nationalId !== ''): ?><div><dt>الرقم الوطني</dt><dd dir="ltr"><?= h($nationalId) ?></dd></div><?php endif; ?>
                <?php if($documentType !== '' || $documentNumber !== ''): ?>
                    <div><dt>الوثيقة</dt><dd><?= h(trim($documentType . ' ' . $documentNumber) ?: '—') ?></dd></div>
                <?php endif; ?>
            </dl>
        </section>

        <section class="sip-card sip-account">
            <h3>معلومات الحساب</h3>
            <dl>
                <div class="sip-wide"><dt>اسم حساب PPPoE</dt><dd dir="ltr"><?= h($pppUsername ?: '—') ?></dd></div>
                <div class="sip-wide"><dt>كلمة المرور</dt><dd dir="ltr"><?= h($pppPassword ?: '—') ?></dd></div>
            </dl>
        </section>

        <section class="sip-card sip-service">
            <h3>معلومات الخدمة</h3>
            <dl>
                <div><dt>السرعة</dt><dd><?= h($speedName) ?></dd></div>
                <div><dt>الباقة</dt><dd><?= h($packageName) ?></dd></div>
                <div><dt>الـ Rate Limit</dt><dd dir="ltr"><?= h($rateLimit) ?></dd></div>
                <div><dt>الملف التعريفي</dt><dd dir="ltr"><?= h($profile) ?></dd></div>
                <div><dt>نوع IP</dt><dd><?= h($ipType) ?></dd></div>
                <div><dt>الحجز</dt><dd dir="ltr"><?= h($reservation) ?></dd></div>
                <div><dt>الحصة</dt><dd><?= h($quotaLabel) ?></dd></div>
            </dl>
        </section>
    </div>

    <section class="sip-qr-section">
        <h3>رموز الاتصال</h3>
        <div class="sip-qr-grid">
            <article class="sip-qr-card sip-account-qr">
                <h4>حساب الإنترنت</h4>
                <?php if($credentialPolicyError === ''): ?><div class="sip-qr" data-qr="<?= h($accountQr) ?>"></div><?php else: ?><div class="sip-qr sip-qr-unavailable">غير جاهز للطباعة</div><?php endif; ?>
                <p><b>الحساب:</b> <span dir="ltr"><?= h($pppUsername ?: '—') ?></span></p>
                <p><b>كلمة المرور:</b> <span dir="ltr"><?= h($pppPassword ?: '—') ?></span></p>
            </article>
            <?php foreach($wifiRows as $wifi): ?>
                <article class="sip-qr-card">
                    <h4>شبكة <?= h($wifi['label']) ?></h4>
                    <div class="sip-qr" data-qr="<?= h($wifi['qr']) ?>"></div>
                    <p><b>اسم الشبكة:</b> <span dir="ltr"><?= h($wifi['ssid']) ?></span></p>
                    <p><b>كلمة المرور:</b> <span dir="ltr"><?= h($wifi['password'] ?: 'بدون كلمة مرور') ?></span></p>
                </article>
            <?php endforeach; ?>
        </div>
    </section>

    <footer class="sip-footer">
        <span><?= h($company['company_name']) ?></span>
        <span><?= h($programName) ?></span>
        <span>تاريخ الطباعة: <?= h(date('Y-m-d H:i')) ?></span>
    </footer>
</main>

<?= ua_asset_tag_js('qrcode_js') ?>
<?php ua_output_print_bootstrap($conn, 'subscriber_profile_print', (string)$subscriberId); ?>
<script>
(() => {
    const renderQr = (element) => {
        const value = element.dataset.qr || '';
        if (!value) return;
        try {
            if (window.QRCode) {
                new QRCode(element, {text: value, width: 152, height: 152, correctLevel: QRCode.CorrectLevel.M});
            } else if (window.QRLocal) {
                element.replaceChildren(QRLocal.create(value, 4).toCanvas(152));
            }
        } catch (error) {
            element.textContent = 'QR';
        }
    };
    document.querySelectorAll('.sip-qr[data-qr]').forEach(renderQr);
    document.getElementById('sipPrintButton')?.addEventListener('click', () => window.print());
    <?php if($autoPrint): ?>window.setTimeout(() => window.print(), 450);<?php endif; ?>
})();
</script>
</body>
</html>
