<?php
require_once 'config/config.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

$message = '';
$name = '';
$email_prefix = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name         = trim($_POST['name']);
    $email_prefix = trim($_POST['email']);
    $email        = $email_prefix . '@mzayentours.com';
    $password     = password_hash($_POST['password'], PASSWORD_DEFAULT);

    $stmt = $conn->prepare("INSERT INTO users (name, email, password) VALUES (?, ?, ?)");
    $stmt->bind_param("sss", $name, $email, $password);
    if ($stmt->execute()) {
        $message = "<div class='alert alert-success'>{$lang['save_user2']} ✅</div>";
        $name = '';
        $email_prefix = '';
    } else {
        $message = "<div class='alert alert-danger'>Error: " . $stmt->error . "</div>";
    }
}
?>

<?php include 'header.php'; ?>

<div class="main-content p-4" style="flex: 1;">
    <h3 class="mb-4"><?= $lang['add_user'] ?></h3>

    <?= $message ?>

    <form method="POST" class="row g-3">
        <div class="col-md-6">
            <label class="form-label"><?= $lang['name'] ?></label>
            <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($name) ?>" required>
        </div>

        <div class="col-md-6">
            <label class="form-label"><?= $lang['email'] ?></label>
            <div class="input-group">
                <input type="text" name="email" class="form-control" value="<?= htmlspecialchars($email_prefix) ?>" required>
                <span class="input-group-text">@mzayentours.com</span>
            </div>
        </div>

        <div class="col-md-6">
            <label class="form-label"><?= $lang['password'] ?></label>
            <input type="password" name="password" class="form-control" required>
        </div>

        <div class="col-12">
            <button type="submit" class="btn btn-primary"><?= $lang['save_user'] ?></button>
        </div>
    </form>
</div>

<?php include 'includes/footer.php'; ?>
