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

$db = getDB();
$success = isset($_GET['success']) ? $_GET['success'] : null;
$error = null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $consumption_id = $_POST['consumption_id'] ?? 0;
    $new_reading = $_POST['new_reading'] ?? 0;
    $correction_reason = $_POST['correction_reason'] ?? '';
    
    if ($consumption_id && $new_reading) {
        try {
            $db->exec('BEGIN TRANSACTION');
            
            // Get consumption record
            $stmt = $db->prepare('SELECT c.*, s.meter_number FROM consumption c JOIN subscribers s ON c.subscriber_id = s.id WHERE c.id = :id');
            $stmt->bindValue(':id', $consumption_id, SQLITE3_INTEGER);
            $consumption = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
            
            if (!$consumption) {
                throw new Exception('لم يتم العثور على القراءة المحددة');
            }
            
            // Get related invoice
            $stmt = $db->prepare('SELECT * FROM invoices WHERE consumption_id = :consumption_id');
            $stmt->bindValue(':consumption_id', $consumption_id, SQLITE3_INTEGER);
            $invoice = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
            
            // Update consumption reading
            $stmt = $db->prepare('UPDATE consumption SET current_reading = :new_reading WHERE id = :id');
            $stmt->bindValue(':new_reading', $new_reading, SQLITE3_FLOAT);
            $stmt->bindValue(':id', $consumption_id, SQLITE3_INTEGER);
            $stmt->execute();
            
            // If there's an invoice, recalculate it
            if ($invoice) {
                // Calculate new consumption
                $consumption_amount = $new_reading - $consumption['previous_reading'];
                
                // Get tariff settings
                $settings = json_decode(file_get_contents('config/settings.json'), true);
                $tariff = $settings['tariff'] ?? [];
                
                // Calculate new amount
                $amount = 0;
                foreach ($tariff as $tier) {
                    if ($consumption_amount > $tier['from']) {
                        $tier_consumption = min(
                            $consumption_amount - $tier['from'],
                            ($tier['to'] ?? PHP_FLOAT_MAX) - $tier['from']
                        );
                        $amount += $tier_consumption * $tier['price'];
                    }
                }
                
                // Update invoice
                $total_amount = $amount + $invoice['fixed_fees'] + $invoice['penalties'];
                $stmt = $db->prepare('UPDATE invoices SET amount = :amount, total_amount = :total_amount WHERE id = :id');
                $stmt->bindValue(':amount', $amount, SQLITE3_FLOAT);
                $stmt->bindValue(':total_amount', $total_amount, SQLITE3_FLOAT);
                $stmt->bindValue(':id', $invoice['id'], SQLITE3_INTEGER);
                $stmt->execute();
            }
            
            // Log the correction
            logActivity('تصحيح قراءة', sprintf("رقم العداد: %s، القراءة القديمة: %s، القراءة الجديدة: %s، السبب: %s", 
                $consumption['meter_number'],
                $consumption['current_reading'],
                $new_reading,
                $correction_reason
            ));
            
            $db->exec('COMMIT');
            header('Location: correct_readings.php?success=1');
            exit;
            
        } catch (Exception $e) {
            $db->exec('ROLLBACK');
            $error = 'حدث خطأ أثناء تصحيح القراءة: ' . $e->getMessage();
        }
    }
}

// Get readings with subscriber info
$query = "SELECT 
    c.*,
    s.meter_number,
    s.full_name,
    i.id as invoice_id,
    i.total_amount,
    (
        SELECT current_reading 
        FROM consumption prev 
        WHERE prev.subscriber_id = c.subscriber_id 
        AND prev.reading_date < c.reading_date 
        ORDER BY reading_date DESC 
        LIMIT 1
    ) as previous_reading
FROM consumption c
JOIN subscribers s ON c.subscriber_id = s.id
LEFT JOIN invoices i ON c.id = i.consumption_id
WHERE c.id IN (
    SELECT MAX(id)
    FROM consumption
    GROUP BY subscriber_id
)
AND s.status = 1
ORDER BY CAST(s.meter_number AS INTEGER)";

$result = $db->query($query);
?>
<!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>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        .table th {
            background-color: #f8f9fa;
            white-space: nowrap;
        }
        .consumption-positive {
            color: #28a745;
        }
        .consumption-negative {
            color: #dc3545;
        }
        .consumption-zero {
            color: #6c757d;
        }
        /* Dashboard styles */
        .sidebar {
            position: fixed;
            top: 0;
            right: 0;
            bottom: 0;
            z-index: 100;
            padding: 48px 0 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
        }
        .sidebar-sticky {
            position: relative;
            top: 0;
            height: calc(100vh - 48px);
            padding-top: .5rem;
            overflow-x: hidden;
            overflow-y: auto;
        }
        .navbar {
            box-shadow: inset 0 -1px 0 rgba(0, 0, 0, .1);
        }
        @media (max-width: 767.98px) {
            .sidebar {
                top: 5rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <?php include 'includes/sidebar.php'; ?>

            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">تصحيح القراءات</h1>
                </div>

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        تم تصحيح القراءة بنجاح
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <div class="table-responsive">
                    <table class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>رقم العداد</th>
                                <th>اسم المشترك</th>
                                <th>تاريخ القراءة</th>
                                <th>القراءة السابقة</th>
                                <th>القراءة الحالية</th>
                                <th>الاستهلاك</th>
                                <th>رقم الفاتورة</th>
                                <th>المبلغ الإجمالي</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while ($row = $result->fetchArray(SQLITE3_ASSOC)): 
                                $consumption = $row['current_reading'] - ($row['previous_reading'] ?? 0);
                                $consumption_class = $consumption > 0 ? 'consumption-positive' : ($consumption < 0 ? 'consumption-negative' : 'consumption-zero');
                            ?>
                                <tr>
                                    <td class="fw-bold"><?php echo htmlspecialchars($row['meter_number']); ?></td>
                                    <td><?php echo htmlspecialchars($row['full_name']); ?></td>
                                    <td><?php echo date('Y-m-d', strtotime($row['reading_date'])); ?></td>
                                    <td><?php echo number_format($row['previous_reading'] ?? 0, 2); ?></td>
                                    <td><?php echo number_format($row['current_reading'], 2); ?></td>
                                    <td class="<?php echo $consumption_class; ?>"><?php echo number_format($consumption, 2); ?></td>
                                    <td><?php echo $row['invoice_id'] ? $row['invoice_id'] : '-'; ?></td>
                                    <td><?php echo $row['total_amount'] ? number_format($row['total_amount'], 2) : '-'; ?></td>
                                    <td>
                                        <button type="button" class="btn btn-warning btn-sm"
                                                data-bs-toggle="modal"
                                                data-bs-target="#correctReadingModal"
                                                data-consumption-id="<?php echo $row['id']; ?>"
                                                data-current-reading="<?php echo $row['current_reading']; ?>"
                                                data-previous-reading="<?php echo $row['previous_reading'] ?? 0; ?>"
                                                data-subscriber-name="<?php echo htmlspecialchars($row['full_name']); ?>"
                                                data-meter-number="<?php echo htmlspecialchars($row['meter_number']); ?>"
                                                data-reading-date="<?php echo date('Y-m-d', strtotime($row['reading_date'])); ?>">
                                            <i class="bi bi-pencil-square"></i>
                                            تصحيح القراءة
                                        </button>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </main>
        </div>
    </div>

    <!-- Correct Reading Modal -->
    <div class="modal fade" id="correctReadingModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">تصحيح القراءة</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" id="correctReadingForm">
                    <div class="modal-body">
                        <input type="hidden" name="consumption_id" id="consumptionIdInput">
                        
                        <div class="alert alert-info">
                            <h6 class="alert-heading mb-1">معلومات المشترك:</h6>
                            <p class="mb-1" id="subscriberInfo"></p>
                            <p class="mb-0" id="readingInfo"></p>
                        </div>
                        
                        <div class="mb-3">
                            <label for="new_reading" class="form-label">القراءة الجديدة</label>
                            <input type="number" step="0.01" min="0" class="form-control" id="new_reading" name="new_reading" required>
                            <div class="form-text text-danger d-none" id="readingWarning">
                                تنبيه: القراءة الجديدة أقل من القراءة السابقة!
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="correction_reason" class="form-label">سبب التصحيح</label>
                            <textarea class="form-control" id="correction_reason" name="correction_reason" rows="3" required></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                        <button type="submit" class="btn btn-primary">حفظ التصحيح</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const correctReadingModal = document.getElementById('correctReadingModal');
            const newReadingInput = document.getElementById('new_reading');
            const readingWarning = document.getElementById('readingWarning');
            let previousReading = 0;
            
            correctReadingModal.addEventListener('show.bs.modal', function(event) {
                const button = event.relatedTarget;
                const consumptionId = button.getAttribute('data-consumption-id');
                const currentReading = button.getAttribute('data-current-reading');
                previousReading = parseFloat(button.getAttribute('data-previous-reading'));
                const subscriberName = button.getAttribute('data-subscriber-name');
                const meterNumber = button.getAttribute('data-meter-number');
                const readingDate = button.getAttribute('data-reading-date');
                
                document.getElementById('consumptionIdInput').value = consumptionId;
                document.getElementById('new_reading').value = currentReading;
                document.getElementById('subscriberInfo').textContent = 
                    `${subscriberName} (رقم العداد: ${meterNumber})`;
                document.getElementById('readingInfo').textContent = 
                    `القراءة السابقة: ${previousReading}`;
                
                // Reset form
                document.getElementById('correction_reason').value = '';
                readingWarning.classList.add('d-none');
            });
            
            // Check if new reading is less than previous reading
            newReadingInput.addEventListener('input', function() {
                const newReading = parseFloat(this.value);
                if (newReading < previousReading) {
                    readingWarning.classList.remove('d-none');
                } else {
                    readingWarning.classList.add('d-none');
                }
            });
        });
    </script>
</body>
</html>
