<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

$db = getDB();
$error_msg = null;

// Get invoice ID from URL
$invoice_id = $_GET['invoice_id'] ?? null;

if (!$invoice_id) {
    $error_msg = 'رقم الفاتورة غير موجود';
} else {
    // Get invoice details with subscriber information
    $query = 'SELECT i.*, s.meter_number, s.full_name, s.address, s.national_id,
             c.previous_reading, c.current_reading, c.reading_date, i.payment_date
             FROM invoices i 
             JOIN subscribers s ON i.subscriber_id = s.id 
             JOIN consumption c ON i.consumption_id = c.id
             WHERE i.id = :invoice_id';
    
    $stmt = $db->prepare($query);
    $stmt->bindValue(':invoice_id', $invoice_id, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $invoice = $result->fetchArray(SQLITE3_ASSOC);
    
    if (!$invoice) {
        $error_msg = 'الفاتورة غير موجودة';
    }
}

// Get settings
$settings = $db->query('SELECT * FROM settings LIMIT 1')->fetchArray(SQLITE3_ASSOC);
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>توصيل الأداء</title>
    <style>
        @page {
            size: A6;
            margin: 0;
        }
        body {
            margin: 0;
            padding: 10mm;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.4;
            font-size: 12px;
        }
        .receipt {
            width: 148mm; /* A6 width */
            padding: 5mm;
            box-sizing: border-box;
            position: relative;
        }
        .header {
            text-align: center;
            margin-bottom: 5mm;
            border-bottom: 1px solid #000;
            padding-bottom: 3mm;
        }
        .logo {
            max-height: 30mm;
            margin-bottom: 2mm;
        }
        .content {
            margin-bottom: 5mm;
        }
        .info-table {
            width: 100%;
            margin-bottom: 5mm;
            border-collapse: collapse;
        }
        .info-table td {
            padding: 2mm;
            vertical-align: top;
        }
        .footer {
            text-align: center;
            margin-top: 10mm;
            font-size: 10px;
            color: #666;
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 40px;
            color: rgba(0,0,0,0.03);
            white-space: nowrap;
            pointer-events: none;
        }
        @media print {
            .no-print {
                display: none;
            }
        }
    </style>
</head>
<body>
    <?php if ($error_msg): ?>
        <div class="alert alert-danger">
            <?php echo htmlspecialchars($error_msg); ?>
        </div>
    <?php else: ?>
        <div class="no-print" style="padding: 20px; background: #f8f9fa; text-align: center;">
            <button onclick="window.print()" style="padding: 10px 20px; font-size: 16px;">طباعة التوصيل</button>
            <button onclick="window.close()" style="padding: 10px 20px; font-size: 16px; margin-right: 10px;">إغلاق</button>
        </div>

        <div class="receipt">
            <div class="watermark"><?php echo htmlspecialchars($settings['association_name']); ?></div>
            
            <div class="header">
                <?php if ($settings['logo_path']): ?>
                    <img src="<?php echo htmlspecialchars($settings['logo_path']); ?>" alt="Logo" class="logo">
                <?php endif; ?>
                <h2><?php echo htmlspecialchars($settings['association_name']); ?></h2>
                <h3>توصيل الأداء</h3>
            </div>
            
            <div class="content">
                <table class="info-table">
                    <tr>
                        <td><strong>رقم الفاتورة:</strong></td>
                        <td><?php echo htmlspecialchars($invoice['invoice_number']); ?></td>
                    </tr>
                    <tr>
                        <td><strong>رقم العداد:</strong></td>
                        <td><?php echo htmlspecialchars($invoice['meter_number']); ?></td>
                    </tr>
                    <tr>
                        <td><strong>الاسم الكامل:</strong></td>
                        <td><?php echo htmlspecialchars($invoice['full_name']); ?></td>
                    </tr>
                    <tr>
                        <td><strong>رقم البطاقة الوطنية:</strong></td>
                        <td><?php echo htmlspecialchars($invoice['national_id']); ?></td>
                    </tr>
                    <tr>
                        <td><strong>تاريخ الأداء:</strong></td>
                        <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($invoice['payment_date']))); ?></td>
                    </tr>
                    <tr>
                        <td><strong>المبلغ المؤدى:</strong></td>
                        <td><?php echo number_format($invoice['total_amount'], 2); ?> درهم</td>
                    </tr>
                </table>
            </div>

            <div class="footer">
                <p>تم إصدار هذا التوصيل بتاريخ: <?php echo date('Y-m-d H:i'); ?></p>
                <?php echo nl2br(htmlspecialchars($settings['receipt_footer'] ?? '')); ?>
            </div>
        </div>
    <?php endif; ?>

    <script>
        // Auto print when page loads
        window.onload = function() {
            if (!<?php echo $error_msg ? 'true' : 'false'; ?>) {
                window.print();
            }
        };
    </script>
</body>
</html>
