<?php
require_once 'config/init.php';
require_once 'includes/auth.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');
            
            // 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);
            
            if ($stmt->execute()) {
                $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; ?>

                <form method="POST" class="card">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">المشترك</label>
                                    <select class="form-select" 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>

                                <div class="mb-3">
                                    <label class="form-label">تاريخ القراءة</label>
                                    <input type="date" class="form-control" name="reading_date" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">القراءة الحالية</label>
                                    <input type="number" step="0.01" min="0" class="form-control" name="current_reading" required>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">فترة الاستهلاك</label>
                                    <select class="form-select" name="consumption_period" required>
                                        <?php foreach ($consumption_periods as $period => $label): ?>
                                            <option value="<?php echo $period; ?>"><?php echo $label; ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

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

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
