<?php
require_once __DIR__ . '/auth.php';

$pageTitle = 'My Profile';

if (!function_exists('app_setting')) {
    function app_setting(PDO $pdo, string $key, string $default = ''): string {
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
            $stmt->execute([$key]);
            $value = $stmt->fetchColumn();
            return ($value !== false && $value !== null && $value !== '') ? (string)$value : $default;
        } catch (Throwable $e) {
            return $default;
        }
    }
}

if (!function_exists('access_label')) {
    function access_label(string $level): string {
        $labels = [
            'guest' => 'Guest',
            'member' => 'Member',
            'training' => 'Training',
            'leader' => 'Leader',
            'premium' => 'Premium',
            'admin' => 'Admin',
            'founder' => 'Founder'
        ];

        $level = strtolower(trim($level));
        return $labels[$level] ?? ucfirst($level ?: 'Member');
    }
}

$profileTitle = app_setting($pdo, 'menu_profile', 'My Profile');
$pageTitle = $profileTitle;

$error = '';
$notice = '';

function profile_upload_image(string $fieldName, string $currentPath): string {
    if (empty($_FILES[$fieldName]['name']) || empty($_FILES[$fieldName]['tmp_name'])) {
        return $currentPath;
    }

    $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
    $original = basename($_FILES[$fieldName]['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        return $currentPath;
    }

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

    $safeBase = preg_replace('/[^a-zA-Z0-9_-]/', '_', pathinfo($original, PATHINFO_FILENAME));
    $filename = 'profile_' . (int)($_SESSION['user_id'] ?? 0) . '_' . date('Ymd_His') . '.' . $ext;
    $target = $dir . '/' . $filename;

    if (move_uploaded_file($_FILES[$fieldName]['tmp_name'], $target)) {
        return 'uploads/profiles/' . $filename;
    }

    return $currentPath;
}

$userId = (int)($_SESSION['user_id'] ?? 0);

try {
    $cols = [];
    $stmt = $pdo->query("SHOW COLUMNS FROM users");
    foreach ($stmt->fetchAll() as $row) {
        $cols[] = $row['Field'];
    }

    $adds = [];
    if (!in_array('display_name', $cols, true)) $adds[] = "ADD COLUMN display_name VARCHAR(120) NULL";
    if (!in_array('profile_image', $cols, true)) $adds[] = "ADD COLUMN profile_image VARCHAR(255) NULL";
    if (!in_array('bio', $cols, true)) $adds[] = "ADD COLUMN bio TEXT NULL";
    if (!in_array('team_group', $cols, true)) $adds[] = "ADD COLUMN team_group VARCHAR(120) NULL";
    if (!in_array('skills_interests', $cols, true)) $adds[] = "ADD COLUMN skills_interests TEXT NULL";
    if (!in_array('website_url', $cols, true)) $adds[] = "ADD COLUMN website_url VARCHAR(255) NULL";
    if (!in_array('profile_visibility', $cols, true)) $adds[] = "ADD COLUMN profile_visibility VARCHAR(30) NOT NULL DEFAULT 'members'";
    if (!in_array('gender', $cols, true)) $adds[] = "ADD COLUMN gender VARCHAR(20) NULL";

    if ($adds) {
        $pdo->exec("ALTER TABLE users " . implode(", ", $adds));
    }
} catch (Throwable $e) {
    $error = $e->getMessage();
}

try {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$userId]);
    $user = $stmt->fetch();

    if (!$user) {
        throw new Exception('User not found.');
    }
} catch (Throwable $e) {
    $user = [];
    $error = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$error) {
    try {
        $displayName = trim($_POST['display_name'] ?? '');
        $bio = trim($_POST['bio'] ?? '');
        $teamGroup = trim($_POST['team_group'] ?? '');
        $skillsInterests = trim($_POST['skills_interests'] ?? '');
        $websiteUrl = trim($_POST['website_url'] ?? '');
        $visibility = trim($_POST['profile_visibility'] ?? 'members');
        $gender = trim($_POST['gender'] ?? '');

        $allowedVisibility = ['private', 'members', 'public'];
        $allowedGender = ['male', 'female', ''];
        if (!in_array($visibility, $allowedVisibility, true)) {
            $visibility = 'members';
        }

        if (!in_array($gender, $allowedGender, true)) {
            $gender = '';
        }

        $profileImage = profile_upload_image('profile_image_upload', $user['profile_image'] ?? '');

        $stmt = $pdo->prepare("
            UPDATE users
            SET display_name = ?,
                bio = ?,
                team_group = ?,
                skills_interests = ?,
                website_url = ?,
                profile_visibility = ?,
                gender = ?,
                profile_image = ?
            WHERE id = ?
        ");
        $stmt->execute([
            $displayName,
            $bio,
            $teamGroup,
            $skillsInterests,
            $websiteUrl,
            $visibility,
            $gender,
            $profileImage,
            $userId
        ]);

        $notice = 'Profile updated.';

        $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? LIMIT 1");
        $stmt->execute([$userId]);
        $user = $stmt->fetch();

    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}

require_once __DIR__ . '/includes/header.php';

$displayName = $user['display_name'] ?? ($user['username'] ?? '');
$accessLevel = $user['access_level'] ?? 'member';
$profileImage = $user['profile_image'] ?? '';
?>

<main>
<section class="section">
<div class="container">
<div class="panel">

<h1><?php echo h($profileTitle); ?></h1>
<p class="muted">Universal profile for communities, ministries, courses, coaching groups, memberships, and teams.</p>

<?php if ($notice): ?>
<div class="notice"><?php echo h($notice); ?></div>
<?php endif; ?>

<?php if ($error): ?>
<div class="error"><?php echo h($error); ?></div>
<?php endif; ?>

<div class="admin-grid">

<div class="card">
<h2>Profile Preview</h2>

<?php if (!empty($profileImage)): ?>
<img src="<?php echo h($profileImage); ?>?v=<?php echo time(); ?>" alt="Profile Image" style="max-width:140px;border-radius:18px;margin-bottom:1rem;">
<?php endif; ?>

<h3><?php echo h($displayName ?: 'Display Name'); ?></h3>
<p class="muted"><?php echo h($user['email'] ?? ''); ?></p>
<p><strong>Access Level:</strong> <?php echo h(access_label($accessLevel)); ?></p>
<?php if (!empty($user['gender'])): ?>
<p><strong>Gender:</strong> <?php echo h(ucfirst($user['gender'])); ?></p>
<?php endif; ?>

<?php if (!empty($user['team_group'])): ?>
<p><strong>Group / Team:</strong> <?php echo h($user['team_group']); ?></p>
<?php endif; ?>

<?php if (!empty($user['bio'])): ?>
<p><?php echo nl2br(h($user['bio'])); ?></p>
<?php endif; ?>

<?php if (!empty($user['website_url'])): ?>
<p><a href="<?php echo h($user['website_url']); ?>" target="_blank" rel="noopener">Website / Link</a></p>
<?php endif; ?>
</div>

<div class="card">
<h2>Edit Profile</h2>

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

<label>Display Name</label>
<input name="display_name" value="<?php echo h($user['display_name'] ?? ''); ?>" placeholder="Name shown to others">

<label>Profile Image</label>
<input type="file" name="profile_image_upload" accept="image/*">

<label>Bio / About</label>
<textarea name="bio" placeholder="Short introduction"><?php echo h($user['bio'] ?? ''); ?></textarea>

<label>Group / Team</label>
<input name="team_group" value="<?php echo h($user['team_group'] ?? ''); ?>" placeholder="Team, group, class, department, or community">

<label>Skills / Interests</label>
<textarea name="skills_interests" placeholder="Skills, interests, gifts, subjects, services, or focus areas"><?php echo h($user['skills_interests'] ?? ''); ?></textarea>

<label>Website / Social Link</label>
<input name="website_url" value="<?php echo h($user['website_url'] ?? ''); ?>" placeholder="https://example.com">

<label>Gender</label>
<select name="gender">
<option value="">Not selected</option>
<option value="female" <?php echo (($user['gender'] ?? '') === 'female') ? 'selected' : ''; ?>>Female</option>
<option value="male" <?php echo (($user['gender'] ?? '') === 'male') ? 'selected' : ''; ?>>Male</option>
</select>

<label>Profile Visibility</label>
<select name="profile_visibility">
<option value="private" <?php echo (($user['profile_visibility'] ?? '') === 'private') ? 'selected' : ''; ?>>Private</option>
<option value="members" <?php echo (($user['profile_visibility'] ?? 'members') === 'members') ? 'selected' : ''; ?>>Members Only</option>
<option value="public" <?php echo (($user['profile_visibility'] ?? '') === 'public') ? 'selected' : ''; ?>>Public</option>
</select>

<div class="btn-row">
<button type="submit" class="btn btn-primary">Save Profile</button>
</div>

</form>
</div>

</div>

</div>
</div>
</section>
</main>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
