<?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(date('Y-m-d', strtotime($invoice['due_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>

            <?php
            // Calculate consumption by tiers
            $consumption = $invoice['current_reading'] - $invoice['previous_reading'];
            $remaining_consumption = $consumption;
            $tier_details = [];
            
            foreach ($tiers as $tier) {
                $tier_start = $tier['start_range'];
                $tier_end = $tier['end_range'];
                $price_per_unit = $tier['price_per_unit'];
                
                if ($tier_end === null) {
                    // Last tier
                    if ($remaining_consumption > 0) {
                        $tier_details[] = [
                            'range' => $tier_start . ' فما فوق',
                            'consumption' => $remaining_consumption,
                            'price' => $price_per_unit,
                            'amount' => $remaining_consumption * $price_per_unit
                        ];
                    }
                    break;
                }
                
                $tier_consumption = min($remaining_consumption, $tier_end - $tier_start);
                if ($tier_consumption > 0) {
                    $tier_details[] = [
                        'range' => $tier_start . ' - ' . $tier_end,
                        'consumption' => $tier_consumption,
                        'price' => $price_per_unit,
                        'amount' => $tier_consumption * $price_per_unit
                    ];
                    $remaining_consumption -= $tier_consumption;
                }
                
                if ($remaining_consumption <= 0) {
                    break;
                }
            }
            ?>

            <?php if (!empty($tier_details)): ?>
         
            <?php endif; ?>

            <table class="billing-details">
                <?php
                // Get the consumption amount
                $consumption = $invoice['current_reading'] - $invoice['previous_reading'];
                
                // Get consumption threshold from settings
                $settings_stmt = $db->query('SELECT consumption_threshold FROM settings LIMIT 1');
                $settings_row = $settings_stmt->fetchArray(SQLITE3_ASSOC);
                $consumption_threshold = $settings_row['consumption_threshold'];
                
                if ($consumption > $consumption_threshold) {
                    // Find the applicable tier for consumption above threshold
                    $applicable_tier = null;
                    foreach ($tiers as $tier) {
                        if ($consumption >= $tier['start_range'] && 
                            ($tier['end_range'] === null || $consumption <= $tier['end_range'])) {
                            $applicable_tier = $tier;
                            break;
                        }
                    }
                }
                ?>
                
                <tr>
                    <th>الشطر (متر مكعب)</th>
                    <th>الاستهلاك (متر مكعب)</th>
                    <th>السعر (درهم)</th>
                    <th>المبلغ (درهم)</th>
                </tr>
                
                <?php if ($consumption > 0): ?>
                    <?php if ($consumption > $consumption_threshold && $applicable_tier): ?>
                        <tr>
                            <td>
                                <?php 
                                echo $applicable_tier['start_range'] . ' - ';
                                echo $applicable_tier['end_range'] ? $applicable_tier['end_range'] : '∞';
                                ?>
                            </td>
                            <td><?php echo $consumption; ?></td>
                            <td><?php echo number_format($applicable_tier['price_per_unit'], 2); ?></td>
                            <td><?php echo number_format($invoice['consumption_amount'], 2); ?></td>
                        </tr>
                    <?php else: ?>
                        <?php 
                        $remaining_consumption = $consumption;
                        foreach ($tiers as $tier) {
                            if ($remaining_consumption <= 0) break;
                            
                            $tier_end = $tier['end_range'];
                            if ($tier_end === null || $tier_end > $consumption_threshold) {
                                $tier_end = $consumption_threshold;
                            }
                            
                            $tier_range = $tier_end - $tier['start_range'];
                            $tier_consumption = min($remaining_consumption, $tier_range);
                            
                            if ($tier_consumption > 0):
                            ?>
                                <tr>
                                    <td>
                                        <?php echo $tier['start_range'] . ' - ' . $tier_end; ?>
                                    </td>
                                    <td><?php echo $tier_consumption; ?></td>
                                    <td><?php echo number_format($tier['price_per_unit'], 2); ?></td>
                                    <td><?php echo number_format($tier_consumption * $tier['price_per_unit'], 2); ?></td>
                                </tr>
                            <?php
                                $remaining_consumption -= $tier_consumption;
                            endif;
                        }
                        ?>
                    <?php endif; ?>
                <?php endif; ?>

                <?php if ($invoice['fixed_fees'] > 0): ?>
                <tr>
                    <td colspan="3"><strong>المستحقات الثابتة:</strong></td>
                    <td><?php echo number_format($invoice['fixed_fees'], 2); ?> درهم</td>
                </tr>
                <?php endif; ?>

                <tr class="total-row">
                    <td colspan="3"><strong>المجموع:</strong></td>
                    <td><strong><?php echo number_format($invoice['total_amount'], 2); ?> درهم</strong></td>
                </tr>
            </table>

            <div style="margin-top: 20px;">
                <p style="font-size: 11px; margin-top: 10px;">
                    ملاحظة: يرجى أداء المستحقات قبل تاريخ الاستحقاق لتجنب غرامات التأخير.
                   
                </p>
            </div>

            <div class="footer">
                <?php if ($invoice['status'] === 'paid'): ?>
                    <div style="color: #28a745; font-weight: bold; font-size: 44px; 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>
