<?php
session_start();
if (!isset($_SESSION['user_id'])) { die("Unauthorized."); }
require_once 'db.php';

$bill_id = $_GET['id'] ?? null;
if (!$bill_id) { die("Bill ID missing."); }

try {
    // 1. جلب بيانات الفاتورة والمشترك كاملة
    $stmt = $pdo->prepare("
        SELECT b.*, 
               c.name as customer_name, c.sub_no, c.phone, c.system_type, 
               c.ampere_qty, c.monthly_fixed_fee, c.custom_amp_price
        FROM bills b 
        JOIN customers c ON b.customer_id = c.id 
        WHERE b.id = ?
    ");
    $stmt->execute([$bill_id]);
    $bill = $stmt->fetch();

    if (!$bill) { die("Bill not found."); }

    // 2. جلب أسعار الشهر التاريخية
    $price_stmt = $pdo->prepare("SELECT * FROM monthly_pricing WHERE month = ? AND year = ?");
    $price_stmt->execute([$bill['month'], $bill['year']]);
    $pricing = $price_stmt->fetch();

    if (!$pricing) { die("Pricing data missing for this period."); }

    $usage_cost_usd = 0;
    $usage_cost_lbp = 0;
    $reading = null;
    $consumption = 0;
    $unit_price_display = "";
    $exchange_rate = $pricing['exchange_rate'] ?: 0;

    // 3. تحليل تكلفة الاستهلاك حسب النوع
    if ($bill['system_type'] === 'meter') {
        $r_stmt = $pdo->prepare("SELECT * FROM meter_readings WHERE meter_id = ? AND month = ? AND year = ?");
        $r_stmt->execute([$bill['customer_id'], $bill['month'], $bill['year']]);
        $reading = $r_stmt->fetch();
        
        if ($reading && $exchange_rate > 0) {
            $consumption = $reading['current_reading'] - $reading['previous_reading'];
            $usage_cost_lbp = $consumption * $pricing['price_kwh'];
            $usage_cost_usd = $usage_cost_lbp / $exchange_rate;
            $unit_price_display = number_format($pricing['price_kwh']) . " L.L";
        }
    } else {
        // نظام الأمبير: سعر خاص أو عام
        $applied_rate = ($bill['custom_amp_price'] > 0) ? $bill['custom_amp_price'] : $pricing['price_amp'];
        $usage_cost_usd = $bill['ampere_qty'] * $applied_rate;
        $usage_cost_lbp = $usage_cost_usd * $exchange_rate;
        $unit_price_display = "$" . number_format($applied_rate, 2);
    }

    $rated_fee_usd = ($bill['ampere_qty'] * ($pricing['fee_per_rated_amp'] ?? 0));
    $rated_fee_lbp = $rated_fee_usd * $exchange_rate;
    
    $fixed_sub_fee_lbp = ($bill['monthly_fixed_fee'] ?? 0);
    $fixed_sub_fee_usd = ($fixed_sub_fee_lbp > 0 && $exchange_rate > 0) ? ($fixed_sub_fee_lbp / $exchange_rate) : 0;

    $previous_debt = $bill['amount_usd'] - ($usage_cost_usd + $rated_fee_usd + $fixed_sub_fee_usd);
    if ($previous_debt < 0.01) $previous_debt = 0;
    $previous_debt_lbp = $previous_debt * $exchange_rate;

    $total_lbp = $bill['amount_usd'] * $exchange_rate;

} catch (PDOException $e) { die($e->getMessage()); }
?>

<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="utf-8">
    <title>فاتورة #<?= $bill['bill_number'] ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;900&display=swap" rel="stylesheet">
    <style>
        @page { margin: 0; }
        body { 
            font-family: 'Cairo', sans-serif; 
            width: 80mm; 
            margin: 0 auto; 
            padding: 4mm; 
            font-size: 17px; 
            line-height: 1.5; 
            color: #000; 
            background: #fff;
            font-weight: 700;
        }
        .text-center { text-align: center; }
        .bold { font-weight: 700; }
        .black { font-weight: 900; }
        
        .header h2 { margin: 0; font-size: 32px; font-weight: 900; letter-spacing: -1px; line-height: 1.2; }
        .header p { margin: 5px 0; font-size: 15px; font-weight: 700; }
        
        .divider { border-top: 2px dashed #000; margin: 12px 0; }
        .solid-divider { border-top: 3px solid #000; margin: 12px 0; }
        
        .row { display: flex; justify-content: space-between; margin-bottom: 6px; }
        .label { flex: 1; text-align: right; }
        .value { font-weight: 900; text-align: left; }
        
        .price-box {
            background: #f8f8f8;
            padding: 15px 10px;
            border: 3px solid #000;
            margin: 20px 0;
        }

        .total-lbp-text {
            font-size: 36px;
            display: block;
            margin: 10px 0;
            line-height: 1;
            font-weight: 900;
        }

        .footer { margin-top: 25px; font-size: 13px; font-weight: 700; border-top: 2px solid #000; padding-top: 15px; }
        
        @media print { 
            .no-print { display: none; }
            body { padding: 3mm; width: 100%; }
        }
    </style>
</head>
<body>

    <div class="no-print">
        <button onclick="window.print()" style="width:100%; padding:20px; margin-bottom:20px; font-weight:900; cursor:pointer; background:#000; color:#fff; border:none; border-radius:15px; font-family:'Cairo'; font-size: 18px;">إضغط لطباعة الوصل</button>
    </div>

    <div class="header text-center">
        <h2>كهرباء أسامة</h2>
        <p class="black">إدارة المولدات والخدمات الكهربائية</p>
        <div class="divider"></div>
        <p class="black" style="font-size: 20px;">فاتورة شهر: <?= $bill['month'] ?> / <?= $bill['year'] ?></p>
        <p>تاريخ الإصدار: <?= date('Y-m-d', strtotime($bill['created_at'])) ?></p>
    </div>

    <div class="solid-divider"></div>

    <div class="customer-info">
        <div class="row"><span class="label">المشترك:</span><span class="value" style="font-size: 20px;"><?= htmlspecialchars($bill['customer_name']) ?></span></div>
        <div class="row"><span class="label">الاشتراك:</span><span class="value">#<?= $bill['sub_no'] ?></span></div>
        <div class="row"><span class="label">قوة الخط:</span><span class="value"><?= $bill['ampere_qty'] ?> أمبير</span></div>
    </div>

    <div class="divider"></div>

    <div class="details">
        <?php if ($bill['system_type'] === 'meter'): ?>
            <div class="row"><span>قراءة حالية:</span><span class="value"><?= number_format($reading['current_reading'] ?? 0, 1) ?></span></div>
            <div class="row"><span>قراءة سابقة:</span><span class="value"><?= number_format($reading['previous_reading'] ?? 0, 1) ?></span></div>
            <div class="row"><span class="bold">الاستهلاك:</span><span class="value black" style="font-size: 20px;"><?= number_format($consumption, 1) ?> KWh</span></div>
            <div class="row"><span>سعر الكيلو:</span><span class="value"><?= $unit_price_display ?></span></div>
            <div class="row"><span class="bold">ثمن الطاقة ($):</span><span class="value">$<?= number_format($usage_cost_usd, 2) ?></span></div>
            <div class="row"><span class="bold">ثمن الطاقة (ل.ل):</span><span class="value"><?= number_format($usage_cost_lbp) ?> L.L</span></div>
        <?php else: ?>
            <div class="row"><span>كمية الأمبير:</span><span class="value"><?= $bill['ampere_qty'] ?> A</span></div>
            <div class="row"><span>سعر الأمبير:</span><span class="value"><?= $unit_price_display ?></span></div>
            <div class="row"><span class="bold">ثمن الاشتراك ($):</span><span class="value">$<?= number_format($usage_cost_usd, 2) ?></span></div>
            <div class="row"><span class="bold">ثمن الاشتراك (ل.ل):</span><span class="value"><?= number_format($usage_cost_lbp) ?> L.L</span></div>
        <?php endif; ?>

        <div class="divider"></div>

        <?php if ($rated_fee_usd > 0): ?>
            <div class="row"><span>رسم قدرة ($):</span><span class="value">$<?= number_format($rated_fee_usd, 2) ?></span></div>
        <?php endif; ?>
        
        <div class="row"><span>رسم ثابت (ل.ل):</span><span class="value"><?= number_format($fixed_sub_fee_lbp) ?> L.L</span></div>

        <?php if ($previous_debt > 0.01): ?>
            <div class="row bold"><span>دين سابق (ل.ل):</span><span class="value"><?= number_format($previous_debt_lbp) ?> L.L</span></div>
        <?php endif; ?>
    </div>

    <div class="price-box text-center">
        <div class="row" style="margin-bottom: 5px; align-items: center;">
            <span class="bold" style="font-size: 20px;">المجموع النهائي:</span>
            <span class="black" style="font-size: 24px;">$<?= number_format($bill['amount_usd'], 2) ?></span>
        </div>
        <div style="border-top: 2px solid #000; margin: 10px 0;"></div>
        <span class="black total-lbp-text">
            <?= number_format($total_lbp) ?> L.L
        </span>
        <p style="font-size: 13px; margin-top: 10px; font-weight: 900;">سعر الصرف: <?= number_format($exchange_rate) ?> ل.ل</p>
    </div>

    <div class="footer text-center">
        <p class="black" style="font-size: 16px;">شكراً لثقتكم بكهرباء أسامة</p>
        <p>الوصل يعتبر لاغياً بدون توقيع الجابي</p>
        <p style="font-size: 10px; margin-top: 8px;">Software v5.5 - High Visibility Mode</p>
    </div>

    <script>
        window.onload = function(){ 
            window.print(); 
            window.onafterprint = function(){ window.close(); };
        };
    </script>
</body>
</html>