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

$db = getDB();

// Get date range from query parameters
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$selected_invoices = !empty($_GET['selected_invoices']) ? explode(',', $_GET['selected_invoices']) : [];

// Get settings
$settings = $db->query('SELECT * FROM settings LIMIT 1')->fetchArray(SQLITE3_ASSOC);

// Get a single invoice number for all invoices in this batch
$batch_invoice_number = getNextInvoiceNumber();

// Build query based on whether specific invoices are selected
$query = 'SELECT i.id, i.subscriber_id, i.consumption_id, i.invoice_number, i.fixed_fees, i.collective_entitlement_amount, i.consumption_amount, i.penalties, i.total_amount, i.due_date, i.status,
         s.meter_number, s.full_name, s.address, s.national_id,
         c.previous_reading, c.current_reading, c.reading_date
         FROM invoices i 
         JOIN subscribers s ON i.subscriber_id = s.id 
         JOIN consumption c ON i.consumption_id = c.id
         WHERE c.reading_date BETWEEN :start_date AND :end_date';

if (!empty($selected_invoices)) {
    $query .= ' AND i.id IN (' . implode(',', array_map('intval', $selected_invoices)) . ')';
}

$query .= ' ORDER BY s.meter_number, c.reading_date';

$stmt = $db->prepare($query);
$stmt->bindValue(':start_date', $start_date);
$stmt->bindValue(':end_date', $end_date);
$result = $stmt->execute();

$invoices = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $invoices[] = $row;
}

// Update all invoices in this batch with the same invoice number
$update_stmt = $db->prepare('UPDATE invoices SET invoice_number = :invoice_number WHERE id = :id');
foreach ($invoices as $invoice) {
    $update_stmt->bindValue(':invoice_number', $batch_invoice_number, SQLITE3_TEXT);
    $update_stmt->bindValue(':id', $invoice['id'], SQLITE3_INTEGER);
    $update_stmt->execute();
}

// Get consumption tiers
$tiers_result = $db->query('SELECT * FROM consumption_tiers ORDER BY start_range');
$tiers = [];
while ($row = $tiers_result->fetchArray(SQLITE3_ASSOC)) {
    $tiers[] = $row;
}
?>
<!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: A4;
            margin: 0;
        }
        body {
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.4;
            font-size: 12px;
        }
        .invoice {
            width: 210mm;
            height: 148.5mm; /* Half A4 */
            padding: 5mm;
            box-sizing: border-box;
            position: relative;
            border: 1px dotted #333;
        }
        .invoice:nth-child(even) {
            border-bottom: none;
        }
        .header {
            text-align: center;
            margin-bottom: 5px;
            border-bottom: 2px solid #333;
            padding-bottom: 10px;
        }
        .logo {
            max-height: 40px;
            margin-bottom: 5px;
        }
        .billing-details {
            width: 100%;
            border-collapse: collapse;
            margin: 10px 0;
        }
        .billing-details th, .billing-details td {
            padding: 3px;
            text-align: right;
            border: 1px solid #ddd;
        }
        .billing-details th {
            background-color: #f5f5f5;
            font-weight: bold;
        }
        .total-row {
            font-weight: bold;
            background-color: #f0f0f0;
        }
        .footer {
            position: absolute;
            bottom: 10mm;
            left: 10mm;
            right: 10mm;
            text-align: center;
            font-size: 10px;
            color: #666;
        }
        .qr-code {
            position: absolute;
            bottom: 10mm;
            left: 10mm;
            width: 50px;
            height: 50px;
        }
        .watermark {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            font-size: 60px;
            color: rgba(0,0,0,0.03);
            white-space: nowrap;
            pointer-events: none;
        }
        @media print {
            .no-print {
                display: none;
            }
        }
        .due-date {
            color: #dc3545;
            font-weight: bold;
        }
        .tiers-table {
            width: 100%;
            font-size: 10px;
            margin-top: 10px;
        }
        .tiers-table th,
        .tiers-table td {
            border: 1px solid #ddd;
            padding: 4px;
            text-align: center;
        }
    </style>
</head>
<body>
    <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.location.href='invoices.php'" style="padding: 10px 20px; font-size: 16px; margin-right: 10px;">عودة</button>
    </div>

    <?php foreach ($invoices as $invoice): ?>
        <div class="invoice">
            <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>رقم الفاتورة: <?php echo htmlspecialchars($batch_invoice_number); ?></div>
            </div>
            
            <table style="width: 100%; margin-bottom: 10px;">
                <tr>
                    <td style="width: 50%;">
                        <strong>رقم العداد:</strong> <?php echo htmlspecialchars($invoice['meter_number']); ?><br>
                        <strong>الاسم الكامل:</strong> <?php echo htmlspecialchars($invoice['full_name']); ?><br>
                        <strong>رقم البطاقة الوطنية:</strong> <?php echo htmlspecialchars($invoice['national_id']); ?><br>
                        <strong>العنوان:</strong> <?php echo htmlspecialchars($invoice['address']); ?>
                    </td>
                    <td style="width: 50%;">
                        <strong>تاريخ القراءة:</strong> <?php echo htmlspecialchars(date('Y-m-d', strtotime($invoice['reading_date']))); ?><br>
                        <strong>القراءة السابقة:</strong> <?php echo htmlspecialchars($invoice['previous_reading']); ?><br>
                        <strong>القراءة الحالية:</strong> <?php echo htmlspecialchars($invoice['current_reading']); ?><br>
                        <strong>الاستهلاك:</strong> <?php echo htmlspecialchars($invoice['current_reading'] - $invoice['previous_reading']); ?> متر مكعب
                    </td>
                </tr>
            </table>

            <table class="billing-details">
                <tr>
                    <th colspan="2">تفاصيل الفاتورة</th>
                </tr>
                <tr>
                    <td>المستحقات الثابتة</td>
                    <td><?php echo number_format($invoice['fixed_fees'], 2); ?> درهم</td>
                </tr>
                <tr>
                    <td>مبلغ الاستحقاق الجماعي</td>
                    <td><?php echo number_format($invoice['collective_entitlement_amount'], 2); ?> درهم</td>
                </tr>
                <tr>
                    <td>مبلغ الاستهلاك</td>
                    <td><?php echo number_format($invoice['consumption_amount'], 2); ?> درهم</td>
                </tr>
                <?php if ($invoice['penalties'] > 0): ?>
                <tr>
                    <td>الغرامات</td>
                    <td><?php echo number_format($invoice['penalties'], 2); ?> درهم</td>
                </tr>
                <?php endif; ?>
                <tr class="total-row">
                    <td>المجموع الإجمالي</td>
                    <td><?php echo number_format($invoice['total_amount'], 2); ?> درهم</td>
                </tr>
            </table>

            <div style="margin-top: 20px;">
                <p><strong>تاريخ الاستحقاق:</strong> <?php echo htmlspecialchars(date('Y-m-d', strtotime($invoice['due_date']))); ?></p>
                <p style="font-size: 11px; margin-top: 10px;">
                    ملاحظة: يرجى أداء المستحقات قبل تاريخ الاستحقاق لتجنب غرامات التأخير.
                    في حالة عدم الأداء في الوقت المحدد، سيتم تطبيق غرامة بنسبة <?php echo htmlspecialchars($settings['penalty_rate']); ?>%.
                </p>
            </div>

            <div class="footer">
                <?php if ($invoice['status'] === 'paid'): ?>
                    <div style="color: #28a745; font-weight: bold; font-size: 24px; transform: rotate(-30deg); position: absolute; top: 50%; left: 50%; margin-left: -50px;">مؤدى</div>
                <?php endif; ?>
                <div>يرجى الاحتفاظ بهذه الفاتورة - <?php echo htmlspecialchars($settings['association_name']); ?></div>
            </div>
        </div>
    <?php endforeach; ?>
</body>
</html>
