<?php
require_once __DIR__ . '/layout.php';
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/includes/header.php';

$error = '';
$success = '';

$username = '';
$email = '';
$password = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    $display_name = trim($_POST['display_name'] ?? '');
    $bio = trim($_POST['bio'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $expertise = trim($_POST['expertise'] ?? '');

    // ----------------------
    // VALIDATION
    // ----------------------
    if ($username === '' || $email === '' || $password === '') {
        $error = 'Please fill in all required fields.';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = 'Please enter a valid email address.';
    }

    // Auto slug if empty
    if (!$error && empty($slug) && !empty($display_name)) {
        $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $display_name)));
    }

    // ----------------------
    // IMAGE UPLOAD
    // ----------------------
    $profile_image = null;

    if (!$error && isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
        $fileTmp = $_FILES['profile_image']['tmp_name'];
        $fileName = $_FILES['profile_image']['name'];
        $fileSize = $_FILES['profile_image']['size'];

        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        $fileType = mime_content_type($fileTmp);

        if (!in_array($fileType, $allowedTypes)) {
            $error = 'Only JPG, PNG or WEBP images are allowed.';
        } elseif ($fileSize > 2 * 1024 * 1024) { // 2MB
            $error = 'Image must be under 2MB.';
        } else {
            $ext = pathinfo($fileName, PATHINFO_EXTENSION);
            $newFileName = uniqid('author_', true) . '.' . $ext;

            $uploadDir = __DIR__ . '/../uploads/authors/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            $destination = $uploadDir . $newFileName;

            if (move_uploaded_file($fileTmp, $destination)) {
                $profile_image = 'uploads/authors/' . $newFileName;
            } else {
                $error = 'Failed to upload image.';
            }
        }
    }

    // ----------------------
    // INSERT USER
    // ----------------------
    if (!$error) {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM admin_users WHERE username = ? OR email = ? OR slug = ?");
        $stmt->execute([$username, $email, $slug]);
        $exists = $stmt->fetchColumn();

        if ($exists) {
            $error = 'Username, email or slug already exists.';
        } else {
            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $pdo->prepare("
                INSERT INTO admin_users 
                (username, email, password_hash, display_name, bio, profile_image, slug, expertise, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            if ($stmt->execute([
                $username,
                $email,
                $password_hash,
                $display_name,
                $bio,
                $profile_image,
                $slug,
                $expertise
            ])) {
                $success = 'User created successfully!';
                $username = $email = $password = '';
            } else {
                $error = 'Database error while creating user.';
            }
        }
    }
}
?>

<h1>Create New User</h1>

<?php if ($error): ?>
  <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($success): ?>
  <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<form method="post" enctype="multipart/form-data">

  <div class="mb-3">
    <label class="form-label">Username *</label>
    <input type="text" name="username" class="form-control" required value="<?= htmlspecialchars($username) ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Email *</label>
    <input type="email" name="email" class="form-control" required value="<?= htmlspecialchars($email) ?>">
  </div>

  <div class="mb-3">
    <label class="form-label">Password *</label>
    <input type="password" name="password" class="form-control" required>
  </div>

  <hr>

  <h5>Author Profile (Optional)</h5>

  <div class="mb-3">
    <label class="form-label">Display Name</label>
    <input type="text" name="display_name" class="form-control">
  </div>

  <div class="mb-3">
    <label class="form-label">Bio</label>
    <textarea name="bio" class="form-control" rows="3"></textarea>
  </div>

  <div class="mb-3">
    <label class="form-label">Profile Image</label>
    <input type="file" name="profile_image" class="form-control" accept="image/*">
  </div>

  <div class="mb-3">
    <label class="form-label">Slug</label>
    <input type="text" name="slug" class="form-control" placeholder="auto-generated if blank">
  </div>

  <div class="mb-3">
    <label class="form-label">Expertise</label>
    <input type="text" name="expertise" class="form-control" placeholder="UK Parks, Disney">
  </div>

  <button type="submit" class="btn btn-primary">Create User</button>
</form>