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

// ----------------------
// CURRENT USER ROLE
// ----------------------
$currentUserRole = strtolower($_SESSION['admin_role'] ?? 'writer');

$id = $_GET['id'] ?? null;

if (!$id) {

    echo "<h1>User not found</h1>";
    exit;

}

// ----------------------
// FETCH USER
// ----------------------
$stmt = $pdo->prepare("SELECT * FROM admin_users WHERE id = ?");
$stmt->execute([$id]);

$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$user) {

    echo "<h1>User not found</h1>";
    exit;

}

// ----------------------
// ROLE PROTECTION
// ----------------------
$targetUserRole = strtolower($user['role'] ?? 'writer');

if (
    $targetUserRole === 'admin'
    && $currentUserRole !== 'admin'
) {

    http_response_code(403);

    echo "<h1>403 - Access Denied</h1>";
    echo "<p>You do not have permission to edit admin users.</p>";

    exit;

}

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

// ----------------------
// HANDLE POST
// ----------------------
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 === '') {

        $error = 'Username and email are required.';

    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {

        $error = 'Invalid email.';

    }

    // ----------------------
    // AUTO SLUG
    // ----------------------
    if (!$error && empty($slug) && !empty($display_name)) {

        $slug = strtolower(
            trim(
                preg_replace('/[^A-Za-z0-9-]+/', '-', $display_name)
            )
        );

    }

    // ----------------------
    // IMAGE UPLOAD
    // ----------------------
    $profile_image = $user['profile_image']; // keep existing

    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 allowed.';

        } elseif ($fileSize > 2 * 1024 * 1024) {

            $error = 'Max size 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 = 'Image upload failed.';

            }

        }

    }

    // ----------------------
    // UPDATE
    // ----------------------
    if (!$error) {

        // Check uniqueness (excluding current user)
        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM admin_users 
            WHERE (
                username = ? 
                OR email = ? 
                OR slug = ?
            )
            AND id != ?
        ");

        $stmt->execute([
            $username,
            $email,
            $slug,
            $id
        ]);

        if ($stmt->fetchColumn()) {

            $error = 'Username, email or slug already exists.';

        } else {

            // ----------------------
            // PASSWORD CHANGE
            // ----------------------
            if (!empty($password)) {

                $password_hash = password_hash(
                    $password,
                    PASSWORD_DEFAULT
                );

                $stmt = $pdo->prepare("
                    UPDATE admin_users SET
                        username = ?,
                        email = ?,
                        password_hash = ?,
                        display_name = ?,
                        bio = ?,
                        profile_image = ?,
                        slug = ?,
                        expertise = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $username,
                    $email,
                    $password_hash,
                    $display_name,
                    $bio,
                    $profile_image,
                    $slug,
                    $expertise,
                    $id
                ]);

            } else {

                // ----------------------
                // NO PASSWORD CHANGE
                // ----------------------
                $stmt = $pdo->prepare("
                    UPDATE admin_users SET
                        username = ?,
                        email = ?,
                        display_name = ?,
                        bio = ?,
                        profile_image = ?,
                        slug = ?,
                        expertise = ?
                    WHERE id = ?
                ");

                $stmt->execute([
                    $username,
                    $email,
                    $display_name,
                    $bio,
                    $profile_image,
                    $slug,
                    $expertise,
                    $id
                ]);

            }

            $success = 'User updated successfully!';

            // Refresh user data
            $stmt = $pdo->prepare("
                SELECT * 
                FROM admin_users 
                WHERE id = ?
            ");

            $stmt->execute([$id]);

            $user = $stmt->fetch(PDO::FETCH_ASSOC);

        }

    }

}
?>

<h1>Edit 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($user['username']) ?>"
        >

    </div>

    <div class="mb-3">

        <label class="form-label">
            Email *
        </label>

        <input 
            type="email"
            name="email"
            class="form-control"
            required
            value="<?= htmlspecialchars($user['email']) ?>"
        >

    </div>

    <div class="mb-3">

        <label class="form-label">
            New Password (leave blank to keep)
        </label>

        <input 
            type="password"
            name="password"
            class="form-control"
        >

    </div>

    <hr>

    <h5>Author Profile</h5>

    <div class="mb-3">

        <label class="form-label">
            Display Name
        </label>

        <input 
            type="text"
            name="display_name"
            class="form-control"
            value="<?= htmlspecialchars($user['display_name'] ?? '') ?>"
        >

    </div>

    <div class="mb-3">

        <label class="form-label">
            Bio
        </label>

        <textarea 
            name="bio"
            class="form-control"
            rows="3"
        ><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>

    </div>

    <div class="mb-3">

        <label class="form-label">
            Current Image
        </label>

        <br>

        <?php if (!empty($user['profile_image'])): ?>

            <img 
                src="/<?= $user['profile_image'] ?>"
                style="width:80px; border-radius:50%;"
            >

        <?php else: ?>

            <p>No image</p>

        <?php endif; ?>

    </div>

    <div class="mb-3">

        <label class="form-label">
            Change 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"
            value="<?= htmlspecialchars($user['slug'] ?? '') ?>"
        >

    </div>

    <div class="mb-3">

        <label class="form-label">
            Expertise
        </label>

        <input 
            type="text"
            name="expertise"
            class="form-control"
            value="<?= htmlspecialchars($user['expertise'] ?? '') ?>"
        >

    </div>

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

</form>