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

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

// Define consumption periods
$consumption_periods = [
    'monthly' => 'شهري',
    'bimonthly' => 'كل شهرين',
    'quarterly' => 'كل ثلاثة أشهر'
];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subscriber_id = $_POST['subscriber_id'] ?? null;
    $reading_date = $_POST['reading_date'] ?? '';
    $current_reading = $_POST['current_reading'] ?? '';
    $consumption_period = $_POST['consumption_period'] ?? '';

    if (!$subscriber_id || !$reading_date || !$current_reading || !$consumption_period) {
        $error_msg = 'جميع الحقول مطلوبة';
    } else {
        try {
            $db->exec('BEGIN TRANSACTION');
            
            // Create billing calculator instance
            $billing = new BillingCalculator($db);
            
            // Get previous reading
            $previous_reading = $db->querySingle("SELECT current_reading FROM consumption WHERE subscriber_id = $subscriber_id ORDER BY reading_date DESC LIMIT 1") ?? 0;
            
            // Calculate consumption
            $consumption = $current_reading - $previous_reading;
            if ($consumption < 0) {
                throw new Exception('القراءة الحالية أقل من القراءة السابقة');
            }

            // Insert consumption record
            $stmt = $db->prepare('INSERT INTO consumption (subscriber_id, previous_reading, current_reading, reading_date, consumption_period) VALUES (:subscriber_id, :previous_reading, :current_reading, :reading_date, :consumption_period)');
            $stmt->bindValue(':subscriber_id', $subscriber_id, SQLITE3_INTEGER);
            $stmt->bindValue(':previous_reading', $previous_reading, SQLITE3_FLOAT);
            $stmt->bindValue(':current_reading', $current_reading, SQLITE3_FLOAT);
            $stmt->bindValue(':reading_date', $reading_date);
            $stmt->bindValue(':consumption_period', $consumption_period);
            $stmt->execute();
            
            // Get consumption ID
            $consumption_id = $db->lastInsertRowID();
            
            // Calculate due date (15 days from reading date)
            $due_date = date('Y-m-d', strtotime('+15 days', strtotime($reading_date)));
            
            // Create invoice using the billing calculator
            $billing->createInvoice($consumption_id, $due_date);
            
            $db->exec('COMMIT');
            logActivity('إدخال قراءة', "تم إدخال قراءة للمشترك رقم $subscriber_id");
            $success_msg = 'تم إدخال القراءة وإنشاء الفاتورة بنجاح';
            header('Location: consumption.php');
            exit;
            
        } catch (Exception $e) {
            try {
                $db->exec('ROLLBACK');
            } catch (Exception $rollbackError) {
                // Ignore rollback errors
            }
            $error_msg = $e->getMessage();
        }
    }
}

// Get all subscribers
$subscribers_query = "SELECT id, meter_number, full_name FROM subscribers WHERE status = 1 ORDER BY CAST(meter_number AS INTEGER)";
$subscribers_result = $db->query($subscribers_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.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
</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 ($error_msg): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo htmlspecialchars($error_msg); ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

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

                <div class="card">
                    <div class="card-body">
                        <form method="post" class="needs-validation" novalidate>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="subscriber_id" class="form-label">المشترك</label>
                                    <select class="form-select" id="subscriber_id" name="subscriber_id" required>
                                        <option value="">اختر المشترك</option>
                                        <?php while ($subscriber = $subscribers_result->fetchArray(SQLITE3_ASSOC)): ?>
                                            <option value="<?php echo $subscriber['id']; ?>">
                                                <?php echo htmlspecialchars($subscriber['meter_number'] . ' - ' . $subscriber['full_name']); ?>
                                            </option>
                                        <?php endwhile; ?>
                                    </select>
                                    <div class="invalid-feedback">
                                        يرجى اختيار المشترك
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <label for="reading_date" class="form-label">تاريخ القراءة</label>
                                    <input type="date" class="form-control" id="reading_date" name="reading_date" required>
                                    <div class="invalid-feedback">
                                        يرجى إدخال تاريخ القراءة
                                    </div>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="current_reading" class="form-label">القراءة الحالية</label>
                                    <input type="number" step="0.01" class="form-control" id="current_reading" name="current_reading" required>
                                    <div class="invalid-feedback">
                                        يرجى إدخال القراءة الحالية
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <label for="consumption_period" class="form-label">فترة الاستهلاك</label>
                                    <select class="form-select" id="consumption_period" name="consumption_period" required>
                                        <option value="">اختر فترة الاستهلاك</option>
                                        <?php foreach ($consumption_periods as $value => $label): ?>
                                            <option value="<?php echo $value; ?>"><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <div class="invalid-feedback">
                                        يرجى اختيار فترة الاستهلاك
                                    </div>
                                </div>
                            </div>

                            <div class="text-end">
                                <button type="submit" class="btn btn-primary">حفظ القراءة</button>
                            </div>
                        </form>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    // Form validation
    (function () {
        'use strict'
        var forms = document.querySelectorAll('.needs-validation')
        Array.prototype.slice.call(forms).forEach(function (form) {
            form.addEventListener('submit', function (event) {
                if (!form.checkValidity()) {
                    event.preventDefault()
                    event.stopPropagation()
                }
                form.classList.add('was-validated')
            }, false)
        })
    })()
    </script>
</body>
</html>
