<?php

function requireProtectionPassword() {
    if (!isset($_SESSION['protection_verified'])) {
        $error = null;
        
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['protection_password'])) {
            try {
                $db = getDB();
                
                // Create table if not exists
                $db->exec('CREATE TABLE IF NOT EXISTS protection_settings (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    password TEXT NOT NULL
                )');
                
                // Check if we have any password set
                $check = $db->query('SELECT COUNT(*) as count FROM protection_settings');
                $row = $check->fetchArray(SQLITE3_ASSOC);
                
                if ($row['count'] == 0) {
                    // Insert default password if none exists
                    $db->exec("INSERT INTO protection_settings (password) VALUES ('code1234')");
                }
                
                $stmt = $db->prepare('SELECT password FROM protection_settings ORDER BY id DESC LIMIT 1');
                $result = $stmt->execute();
                
                if ($result) {
                    $row = $result->fetchArray(SQLITE3_ASSOC);
                    $stored_password = $row['password'];
                    
                    if ($_POST['protection_password'] === $stored_password) {
                        $_SESSION['protection_verified'] = true;
                        header('Location: ' . $_SERVER['PHP_SELF']);
                        exit;
                    }
                    $error = 'كلمة المرور غير صحيحة';
                } else {
                    $error = 'خطأ في قراءة كلمة المرور';
                }
            } catch (Exception $e) {
                error_log('Protection password error: ' . $e->getMessage());
                $error = 'حدث خطأ في النظام. الرجاء المحاولة مرة أخرى';
            }
        }
        
        // Show password form
        ?>
        <!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">
        </head>
        <body>
            <div class="container mt-5">
                <div class="row justify-content-center">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-body">
                                <h3 class="card-title text-center mb-4">تأكيد كلمة المرور</h3>
                                <?php if ($error): ?>
                                    <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                                <?php endif; ?>
                                <form method="POST">
                                    <div class="mb-3">
                                        <label for="protection_password" class="form-label">كلمة المرور</label>
                                        <input type="password" class="form-control" id="protection_password" name="protection_password" required autofocus>
                                    </div>
                                    <button type="submit" class="btn btn-primary w-100">تأكيد</button>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
    return true;
}
