<?php
/**
 * إعدادات الطباعة - تقرير النتائج، الفاتورة، الباركود
 */
use App\Core\Auth;
use App\Core\Tenant;

$tenantId = Tenant::id();
$action = $_GET['action'] ?? 'index';

if (!($auth instanceof Auth) || !$auth->can('settings.manage')) {
    http_response_code(403);
    echo 'غير مسموح بالوصول';
    return;
}

$printKeys = [
    'print_report_paper' => 'A4',
    'print_report_color' => '#0d9488',
    'print_report_logo' => '1',
    'print_report_footer' => '',
    'print_report_show_qr' => '1',
    'print_report_font_size' => 'normal',
    'print_report_orientation' => 'portrait',
    'print_report_margin' => 'normal',
    'print_report_header_text' => '',
    'print_report_watermark' => '1',
    'print_report_table_striped' => '1',
    'print_invoice_paper' => 'A4',
    'print_invoice_show_qr' => '1',
    'print_invoice_footer' => '',
    'print_invoice_color' => '#0d9488',
    'print_invoice_orientation' => 'portrait',
    'print_invoice_show_items' => '1',
    'print_barcode_height' => '60',
    'print_barcode_code' => 'Code128',
    'print_barcode_show_text' => '1',
];

if ($action === 'save' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $reset = isset($_POST['reset_defaults']);
    $pairs = $reset ? [
        'print_report_paper' => 'A4',
        'print_report_color' => '#0d9488',
        'print_report_logo' => '1',
        'print_report_footer' => '',
        'print_report_show_qr' => '1',
        'print_report_font_size' => 'normal',
        'print_report_orientation' => 'portrait',
        'print_report_margin' => 'normal',
        'print_report_header_text' => '',
        'print_report_watermark' => '1',
        'print_report_table_striped' => '1',
        'print_invoice_paper' => 'A4',
        'print_invoice_show_qr' => '1',
        'print_invoice_footer' => '',
        'print_invoice_color' => '#0d9488',
        'print_invoice_orientation' => 'portrait',
        'print_invoice_show_items' => '1',
        'print_barcode_height' => '60',
        'print_barcode_code' => 'Code128',
        'print_barcode_show_text' => '1',
    ] : [
        'print_report_paper' => in_array($_POST['print_report_paper'] ?? '', ['A4', 'Letter']) ? $_POST['print_report_paper'] : 'A4',
        'print_report_color' => preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['print_report_color'] ?? '') ? $_POST['print_report_color'] : '#0d9488',
        'print_report_logo' => isset($_POST['print_report_logo']) ? '1' : '0',
        'print_report_footer' => trim($_POST['print_report_footer'] ?? ''),
        'print_report_show_qr' => isset($_POST['print_report_show_qr']) ? '1' : '0',
        'print_report_font_size' => in_array($_POST['print_report_font_size'] ?? '', ['small', 'normal', 'large']) ? $_POST['print_report_font_size'] : 'normal',
        'print_report_orientation' => in_array($_POST['print_report_orientation'] ?? '', ['portrait', 'landscape']) ? $_POST['print_report_orientation'] : 'portrait',
        'print_report_margin' => in_array($_POST['print_report_margin'] ?? '', ['small', 'normal', 'large']) ? $_POST['print_report_margin'] : 'normal',
        'print_report_header_text' => trim($_POST['print_report_header_text'] ?? ''),
        'print_report_watermark' => isset($_POST['print_report_watermark']) ? '1' : '0',
        'print_report_table_striped' => isset($_POST['print_report_table_striped']) ? '1' : '0',
        'print_invoice_paper' => in_array($_POST['print_invoice_paper'] ?? '', ['A4', 'Letter']) ? $_POST['print_invoice_paper'] : 'A4',
        'print_invoice_show_qr' => isset($_POST['print_invoice_show_qr']) ? '1' : '0',
        'print_invoice_footer' => trim($_POST['print_invoice_footer'] ?? ''),
        'print_invoice_color' => preg_match('/^#[0-9a-fA-F]{6}$/', $_POST['print_invoice_color'] ?? '') ? $_POST['print_invoice_color'] : '#0d9488',
        'print_invoice_orientation' => in_array($_POST['print_invoice_orientation'] ?? '', ['portrait', 'landscape']) ? $_POST['print_invoice_orientation'] : 'portrait',
        'print_invoice_show_items' => isset($_POST['print_invoice_show_items']) ? '1' : '0',
        'print_barcode_height' => (string)min(120, max(30, (int)($_POST['print_barcode_height'] ?? 60))),
        'print_barcode_code' => in_array($_POST['print_barcode_code'] ?? '', ['Code128', 'Code39', 'EAN-13']) ? $_POST['print_barcode_code'] : 'Code128',
        'print_barcode_show_text' => isset($_POST['print_barcode_show_text']) ? '1' : '0',
    ];
    $_SESSION['print_settings_msg'] = $reset ? 'تم استعادة الإعدادات الافتراضية.' : 'تم حفظ إعدادات الطباعة.';
    try {
        $hasTenant = false;
        try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
        $stmt = $hasTenant
            ? $db->prepare('INSERT INTO settings (tenant_id, setting_key, setting_value, updated_at) VALUES (?, ?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()')
            : $db->prepare('INSERT INTO settings (setting_key, setting_value, updated_at) VALUES (?, ?, NOW()) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value), updated_at = NOW()');
        foreach ($pairs as $k => $v) {
            $hasTenant ? $stmt->execute([$tenantId, $k, $v]) : $stmt->execute([$k, $v]);
        }
    } catch (Throwable $e) {}
    header('Location: index.php?page=print_settings');
    exit;
}

try {
    $hasTenant = false;
    try { $db->query('SELECT tenant_id FROM settings LIMIT 1'); $hasTenant = true; } catch (Throwable $e) {}
    if ($hasTenant) {
        $stmt = $db->prepare('SELECT setting_key, setting_value FROM settings WHERE tenant_id = ? AND setting_key LIKE "print_%"');
        $stmt->execute([$tenantId]);
    } else {
        $stmt = $db->query('SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE "print_%"');
    }
    if ($stmt) {
        foreach ($stmt->fetchAll() as $r) {
            if (isset($printKeys[$r['setting_key']])) {
                $printKeys[$r['setting_key']] = (string)($r['setting_value'] ?? '');
            }
        }
    }
} catch (Throwable $e) {}
?>
<div class="page-header">
    <h1>🖨️ إعدادات الطباعة</h1>
    <a href="index.php?page=settings" class="btn-secondary">← الإعدادات</a>
</div>

<?php if (!empty($_SESSION['print_settings_msg'])): ?>
<div class="alert alert-success"><?php echo htmlspecialchars($_SESSION['print_settings_msg'], ENT_QUOTES, 'UTF-8'); unset($_SESSION['print_settings_msg']); ?></div>
<?php endif; ?>

<?php
$lastOrderId = 0;
$lastInvoiceId = 0;
$printStats = ['total_prints' => 0, 'today_prints' => 0, 'official_prints' => 0];
try {
    $tenantAnd = '';
    try { $db->query('SELECT tenant_id FROM lab_orders LIMIT 1'); $tenantAnd = ' AND tenant_id = ' . (int)$tenantId; } catch (Throwable $e) {}
    $o = $db->query('SELECT id FROM lab_orders WHERE 1=1' . $tenantAnd . ' ORDER BY id DESC LIMIT 1')->fetch();
    if ($o) $lastOrderId = (int)$o['id'];
    $i = $db->query('SELECT i.id FROM invoices i JOIN lab_orders o ON o.id=i.order_id WHERE 1=1' . $tenantAnd . ' ORDER BY i.id DESC LIMIT 1')->fetch();
    if ($i) $lastInvoiceId = (int)$i['id'];
    try {
        $db->query('SELECT id FROM print_log LIMIT 1');
        $st = $db->prepare('SELECT COUNT(*) FROM print_log WHERE tenant_id = ?');
        $st->execute([$tenantId]);
        $printStats['total_prints'] = (int)$st->fetchColumn();
        $st = $db->prepare('SELECT COUNT(*) FROM print_log WHERE tenant_id = ? AND DATE(created_at) = CURDATE()');
        $st->execute([$tenantId]);
        $printStats['today_prints'] = (int)$st->fetchColumn();
        $st = $db->prepare('SELECT COUNT(*) FROM print_log WHERE tenant_id = ? AND print_type = "official"');
        $st->execute([$tenantId]);
        $printStats['official_prints'] = (int)$st->fetchColumn();
    } catch (Throwable $e) {}
} catch (Throwable $e) {}
?>
<div class="print-settings-page settings-page">
    <div class="stats-cards print-stats" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:24px;">
        <div class="stat-card" style="background:linear-gradient(135deg,var(--bg-card),rgba(13,148,136,0.05));border:1px solid var(--border);border-radius:8px;padding:16px;">
            <div style="color:var(--text-muted);font-size:0.85em;margin-bottom:4px;">🖨️ إجمالي الطباعة</div>
            <div style="font-size:1.8em;font-weight:700;color:var(--text-primary);"><?php echo number_format($printStats['total_prints']); ?></div>
        </div>
        <div class="stat-card" style="background:linear-gradient(135deg,var(--bg-card),rgba(59,130,246,0.05));border:1px solid var(--border);border-radius:8px;padding:16px;">
            <div style="color:var(--text-muted);font-size:0.85em;margin-bottom:4px;">📅 طباعة اليوم</div>
            <div style="font-size:1.8em;font-weight:700;color:var(--primary);"><?php echo number_format($printStats['today_prints']); ?></div>
        </div>
        <div class="stat-card" style="background:linear-gradient(135deg,var(--bg-card),rgba(34,197,94,0.05));border:1px solid var(--border);border-radius:8px;padding:16px;">
            <div style="color:var(--text-muted);font-size:0.85em;margin-bottom:4px;">✅ نسخ رسمية</div>
            <div style="font-size:1.8em;font-weight:700;color:var(--success);"><?php echo number_format($printStats['official_prints']); ?></div>
        </div>
    </div>
    
    <div class="print-presets-section" style="background:var(--bg-card);border:1px solid var(--border);border-radius:var(--radius);padding:20px;margin-bottom:24px;">
        <div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;">
            <span style="font-size:1.5rem;">⚡</span>
            <div>
                <h4 style="margin:0 0 4px;font-size:1rem;font-weight:600;">قوالب جاهزة</h4>
                <p style="margin:0;color:var(--text-muted);font-size:0.85em;">اختر قالباً جاهزاً لتطبيق إعدادات شائعة بسرعة</p>
            </div>
        </div>
        <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;">
            <button type="button" class="btn-secondary" onclick="applyPreset('compact')" style="text-align:right;padding:12px;">
                <div style="font-weight:600;margin-bottom:4px;">📄 مدمج</div>
                <div style="font-size:0.85em;color:var(--text-muted);">خط صغير، هوامش صغيرة</div>
            </button>
            <button type="button" class="btn-secondary" onclick="applyPreset('standard')" style="text-align:right;padding:12px;">
                <div style="font-weight:600;margin-bottom:4px;">📋 قياسي</div>
                <div style="font-size:0.85em;color:var(--text-muted);">إعدادات افتراضية</div>
            </button>
            <button type="button" class="btn-secondary" onclick="applyPreset('official')" style="text-align:right;padding:12px;">
                <div style="font-weight:600;margin-bottom:4px;">🏛️ رسمي</div>
                <div style="font-size:0.85em;color:var(--text-muted);">أفقي، خط كبير، علامة مائية</div>
            </button>
            <button type="button" class="btn-secondary" onclick="applyPreset('minimal')" style="text-align:right;padding:12px;">
                <div style="font-weight:600;margin-bottom:4px;">✨ مختصر</div>
                <div style="font-size:0.85em;color:var(--text-muted);">بدون QR، بدون علامة مائية</div>
            </button>
        </div>
    </div>
    
    <form method="post" action="index.php?page=print_settings&action=save" id="printSettingsForm">
        <div class="settings-section print-settings-card">
            <div class="print-settings-header">
                <span class="print-settings-icon">📋</span>
                <div>
                    <h3>تقرير النتائج</h3>
                    <p class="settings-desc">إعدادات طباعة تقرير نتائج الفحوصات المخبرية</p>
                </div>
                <?php if ($lastOrderId > 0): ?><a href="index.php?page=print_result&order_id=<?php echo $lastOrderId; ?>" target="_blank" class="btn-secondary btn-sm">معاينة تقرير</a><?php endif; ?>
            </div>
            <div class="form-grid">
                <div>
                    <label>حجم الورق</label>
                    <select name="print_report_paper">
                        <option value="A4" <?php echo $printKeys['print_report_paper'] === 'A4' ? 'selected' : ''; ?>>A4</option>
                        <option value="Letter" <?php echo $printKeys['print_report_paper'] === 'Letter' ? 'selected' : ''; ?>>Letter</option>
                    </select>
                </div>
                <div>
                    <label>حجم الخط</label>
                    <select name="print_report_font_size">
                        <option value="small" <?php echo ($printKeys['print_report_font_size'] ?? 'normal') === 'small' ? 'selected' : ''; ?>>صغير (12px)</option>
                        <option value="normal" <?php echo ($printKeys['print_report_font_size'] ?? 'normal') === 'normal' ? 'selected' : ''; ?>>عادي (13px)</option>
                        <option value="large" <?php echo ($printKeys['print_report_font_size'] ?? '') === 'large' ? 'selected' : ''; ?>>كبير (15px)</option>
                    </select>
                </div>
                <div>
                    <label>اتجاه الطباعة</label>
                    <select name="print_report_orientation">
                        <option value="portrait" <?php echo ($printKeys['print_report_orientation'] ?? 'portrait') === 'portrait' ? 'selected' : ''; ?>>عمودي</option>
                        <option value="landscape" <?php echo ($printKeys['print_report_orientation'] ?? '') === 'landscape' ? 'selected' : ''; ?>>أفقي</option>
                    </select>
                </div>
                <div>
                    <label>الهوامش</label>
                    <select name="print_report_margin">
                        <option value="small" <?php echo ($printKeys['print_report_margin'] ?? 'normal') === 'small' ? 'selected' : ''; ?>>صغيرة (5mm)</option>
                        <option value="normal" <?php echo ($printKeys['print_report_margin'] ?? 'normal') === 'normal' ? 'selected' : ''; ?>>عادية (10mm)</option>
                        <option value="large" <?php echo ($printKeys['print_report_margin'] ?? '') === 'large' ? 'selected' : ''; ?>>كبيرة (20mm)</option>
                    </select>
                </div>
                <div>
                    <label>لون العنوان والحدود</label>
                    <div class="print-color-row">
                        <input type="color" id="printColorPicker" name="print_report_color" value="<?php echo htmlspecialchars($printKeys['print_report_color'], ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="text" id="printColorHex" value="<?php echo htmlspecialchars($printKeys['print_report_color'], ENT_QUOTES, 'UTF-8'); ?>" maxlength="7" placeholder="#0d9488" pattern="^#[0-9a-fA-F]{6}$">
                    </div>
                </div>
                <div class="full-width">
                    <label>نص الترويسة (اختياري)</label>
                    <input type="text" name="print_report_header_text" value="<?php echo htmlspecialchars($printKeys['print_report_header_text'] ?? '', ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: مختبر معتمد من وزارة الصحة">
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_report_logo" value="1" <?php echo $printKeys['print_report_logo'] === '1' ? 'checked' : ''; ?>>
                        إظهار شعار المختبر (من العلامة التجارية)
                    </label>
                    <?php
                    $currentLogo = '';
                    try {
                        $stmt = $db->prepare('SELECT logo_url FROM tenants WHERE id = ?');
                        $stmt->execute([$tenantId]);
                        $t = $stmt->fetch();
                        if ($t && !empty($t['logo_url'])) {
                            $currentLogo = $t['logo_url'];
                        }
                    } catch (Throwable $e) {}
                    ?>
                    <?php if (empty($currentLogo)): ?>
                    <small style="color:#dc2626;display:block;margin-top:4px;">⚠️ لا يوجد شعار محمّل. <a href="index.php?page=tenant_settings" style="color:var(--primary);">حمّل شعار من هنا</a></small>
                    <?php else: ?>
                    <small style="color:var(--success);display:block;margin-top:4px;">✅ الشعار محمّل: <?php echo htmlspecialchars(basename($currentLogo), ENT_QUOTES, 'UTF-8'); ?></small>
                    <?php endif; ?>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_report_show_qr" value="1" <?php echo $printKeys['print_report_show_qr'] === '1' ? 'checked' : ''; ?>>
                        إظهار رمز QR للتحقق من صحة التقرير
                    </label>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_report_watermark" value="1" <?php echo ($printKeys['print_report_watermark'] ?? '1') === '1' ? 'checked' : ''; ?>>
                        إظهار العلامة المائية ("نسخة للاطلاع" / "نسخة رسمية")
                    </label>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_report_table_striped" value="1" <?php echo ($printKeys['print_report_table_striped'] ?? '1') === '1' ? 'checked' : ''; ?>>
                        تلوين صفوف الجدول بالتناوب (خطوط متناوبة)
                    </label>
                </div>
                <div class="full-width">
                    <label>نص التذييل (اختياري)</label>
                    <input type="text" name="print_report_footer" value="<?php echo htmlspecialchars($printKeys['print_report_footer'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="مثال: مختبر معتمد — للمراجعة فقط">
                </div>
            </div>
        </div>

        <div class="settings-section print-settings-card">
            <div class="print-settings-header">
                <span class="print-settings-icon">🧾</span>
                <div>
                    <h3>الفاتورة</h3>
                    <p class="settings-desc">إعدادات طباعة الفواتير</p>
                </div>
                <?php if ($lastInvoiceId > 0): ?><a href="index.php?page=print_invoice&invoice_id=<?php echo $lastInvoiceId; ?>" target="_blank" class="btn-secondary btn-sm">معاينة فاتورة</a><?php endif; ?>
            </div>
            <div class="form-grid">
                <div>
                    <label>حجم الورق</label>
                    <select name="print_invoice_paper">
                        <option value="A4" <?php echo $printKeys['print_invoice_paper'] === 'A4' ? 'selected' : ''; ?>>A4</option>
                        <option value="Letter" <?php echo $printKeys['print_invoice_paper'] === 'Letter' ? 'selected' : ''; ?>>Letter</option>
                    </select>
                </div>
                <div>
                    <label>اتجاه الطباعة</label>
                    <select name="print_invoice_orientation">
                        <option value="portrait" <?php echo ($printKeys['print_invoice_orientation'] ?? 'portrait') === 'portrait' ? 'selected' : ''; ?>>عمودي</option>
                        <option value="landscape" <?php echo ($printKeys['print_invoice_orientation'] ?? '') === 'landscape' ? 'selected' : ''; ?>>أفقي</option>
                    </select>
                </div>
                <div>
                    <label>لون العنوان</label>
                    <div class="print-color-row">
                        <input type="color" id="invoiceColorPicker" name="print_invoice_color" value="<?php echo htmlspecialchars($printKeys['print_invoice_color'] ?? $printKeys['print_report_color'], ENT_QUOTES, 'UTF-8'); ?>">
                        <input type="text" id="invoiceColorHex" value="<?php echo htmlspecialchars($printKeys['print_invoice_color'] ?? $printKeys['print_report_color'], ENT_QUOTES, 'UTF-8'); ?>" maxlength="7" placeholder="#0d9488">
                    </div>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_invoice_show_qr" value="1" <?php echo $printKeys['print_invoice_show_qr'] === '1' ? 'checked' : ''; ?>>
                        إظهار رمز QR للتحقق من صحة الفاتورة
                    </label>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_invoice_show_items" value="1" <?php echo ($printKeys['print_invoice_show_items'] ?? '1') === '1' ? 'checked' : ''; ?>>
                        إظهار تفاصيل البنود (الإجمالي، الخصم، المدفوع، المتبقي)
                    </label>
                </div>
                <div class="full-width">
                    <label>نص التذييل (اختياري)</label>
                    <input type="text" name="print_invoice_footer" value="<?php echo htmlspecialchars($printKeys['print_invoice_footer'], ENT_QUOTES, 'UTF-8'); ?>" placeholder="شكراً لتعاملكم معنا">
                </div>
            </div>
        </div>

        <div class="settings-section print-settings-card">
            <div class="print-settings-header">
                <span class="print-settings-icon">📊</span>
                <div>
                    <h3>الباركود (العينات)</h3>
                    <p class="settings-desc">إعدادات طباعة باركود العينات</p>
                </div>
                <a href="index.php?page=samples" class="btn-secondary btn-sm">صفحة العينات</a>
            </div>
            <div class="form-grid">
                <div>
                    <label>ارتفاع الباركود (px)</label>
                    <input type="number" name="print_barcode_height" min="30" max="120" value="<?php echo (int)$printKeys['print_barcode_height']; ?>">
                </div>
                <div>
                    <label>نوع الباركود</label>
                    <select name="print_barcode_code">
                        <option value="Code128" <?php echo $printKeys['print_barcode_code'] === 'Code128' ? 'selected' : ''; ?>>Code 128</option>
                        <option value="Code39" <?php echo $printKeys['print_barcode_code'] === 'Code39' ? 'selected' : ''; ?>>Code 39</option>
                        <option value="EAN-13" <?php echo $printKeys['print_barcode_code'] === 'EAN-13' ? 'selected' : ''; ?>>EAN-13</option>
                    </select>
                </div>
                <div class="full-width">
                    <label class="settings-checkbox">
                        <input type="checkbox" name="print_barcode_show_text" value="1" <?php echo ($printKeys['print_barcode_show_text'] ?? '1') === '1' ? 'checked' : ''; ?>>
                        إظهار نص الباركود أسفل الرمز
                    </label>
                </div>
            </div>
        </div>

        <div class="settings-section print-settings-card" style="background:#f8fafc;border-color:#e2e8f0;">
            <div class="print-settings-header">
                <span class="print-settings-icon">💡</span>
                <div>
                    <h3>نصائح الطباعة</h3>
                    <p class="settings-desc">إرشادات لطباعة أفضل</p>
                </div>
            </div>
            <ul style="margin:0;padding-right:20px;color:var(--text-muted);line-height:1.8;">
                <li>استخدم <strong>اتجاه أفقي</strong> للتقارير الطويلة أو الجداول الكبيرة</li>
                <li>العلامة المائية تساعد في التمييز بين النسخ الرسمية والنسخ للاطلاع</li>
                <li>رمز QR يسمح بالتحقق من صحة التقرير/الفاتورة عبر الإنترنت</li>
                <li>التذييل يظهر في أسفل كل صفحة مطبوعة</li>
                <li>يمكنك استخدام القوالب الجاهزة لتطبيق إعدادات شائعة بسرعة</li>
            </ul>
        </div>

        <div class="form-actions print-settings-actions">
            <button type="submit" class="btn-primary">💾 حفظ إعدادات الطباعة</button>
            <button type="button" class="btn-secondary" onclick="if(confirm('استعادة الإعدادات الافتراضية؟')){ document.getElementById('resetForm').submit(); }">🔄 استعادة الافتراضي</button>
            <a href="index.php?page=settings" class="btn-secondary">← العودة للإعدادات</a>
        </div>
    </form>
<form id="resetForm" method="post" action="index.php?page=print_settings&action=save" style="display:none;">
    <input type="hidden" name="reset_defaults" value="1">
</form>
</div>

<script>
(function(){
    function syncColor(pickerId, hexId) {
        var picker = document.getElementById(pickerId);
        var hex = document.getElementById(hexId);
        if (!picker || !hex) return;
        picker.addEventListener('input', function(){ hex.value = this.value; });
        hex.addEventListener('input', function(){
            if (/^#[0-9a-fA-F]{6}$/.test(this.value)) picker.value = this.value;
        });
        hex.addEventListener('blur', function(){
            if (!/^#[0-9a-fA-F]{6}$/.test(this.value) && picker.value) hex.value = picker.value;
        });
    }
    syncColor('printColorPicker', 'printColorHex');
    syncColor('invoiceColorPicker', 'invoiceColorHex');
    
    function applyPreset(type) {
        var form = document.getElementById('printSettingsForm');
        if (!form) return;
        var presets = {
            compact: {
                'print_report_font_size': 'small',
                'print_report_margin': 'small',
                'print_report_orientation': 'portrait',
                'print_report_show_qr': '0',
                'print_report_watermark': '0'
            },
            standard: {
                'print_report_font_size': 'normal',
                'print_report_margin': 'normal',
                'print_report_orientation': 'portrait',
                'print_report_show_qr': '1',
                'print_report_watermark': '1'
            },
            official: {
                'print_report_font_size': 'large',
                'print_report_margin': 'large',
                'print_report_orientation': 'landscape',
                'print_report_show_qr': '1',
                'print_report_watermark': '1',
                'print_report_logo': '1'
            },
            minimal: {
                'print_report_show_qr': '0',
                'print_report_watermark': '0',
                'print_report_logo': '0',
                'print_report_footer': ''
            }
        };
        var preset = presets[type];
        if (!preset) return;
        for (var key in preset) {
            var el = form.querySelector('[name="' + key + '"]');
            if (el) {
                if (el.type === 'checkbox') el.checked = preset[key] === '1';
                else el.value = preset[key];
            }
        }
        if (confirm('تم تطبيق القالب "' + type + '". هل تريد الحفظ الآن؟')) form.submit();
    }
    window.applyPreset = applyPreset;
})();
</script>

<style>
.print-settings-header { display: flex; align-items: flex-start; gap: 16px; margin-bottom: 20px; flex-wrap: wrap; }
.print-settings-icon { font-size: 2rem; line-height: 1; }
.print-settings-header h3 { margin: 0 0 4px; }
.print-settings-header .settings-desc { margin: 0; }
.print-color-row { display: flex; align-items: center; gap: 10px; }
.print-color-row input[type="color"] { width: 48px; height: 38px; padding: 2px; cursor: pointer; border-radius: 6px; border: 1px solid var(--border); }
.print-color-row input[type="text"] { width: 90px; padding: 8px 12px; font-family: monospace; font-size: 0.9rem; }
.print-presets-section button { white-space: nowrap; }
.print-presets-section { background: linear-gradient(135deg, rgba(13,148,136,0.05), rgba(13,148,136,0.02)); }
.print-presets-section h4 { color: var(--text-secondary); }
.print-settings-card { transition: box-shadow 0.2s, transform 0.1s; }
.print-settings-card:hover { box-shadow: var(--shadow-md); transform: translateY(-1px); }
.print-presets-section button { transition: all 0.2s; border: 1px solid var(--border); }
.print-presets-section button:hover { background: var(--primary); color: #fff; border-color: var(--primary); transform: translateY(-2px); }
</style>
