<?php

declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/system/bootstrap.php';

$currentUser = myronRequireAuthenticatedUser();
$auth = myronAuthRepository();
$csrfToken = myronCsrfToken();
$requestedUserId = trim((string) ($_GET['user'] ?? ''));
$isAdmin = myronUserCanAccessAdministration($currentUser);
$targetUserId = $requestedUserId !== '' && $isAdmin ? $requestedUserId : (string) $currentUser['id'];
$targetUser = $auth->findUserById($targetUserId);

if ($targetUser === null) {
    myronRenderForbidden('That profile could not be found.');
}

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    try {
        myronRequireCsrf($_POST['csrf_token'] ?? null);
        $action = trim((string) ($_POST['action'] ?? ''));
        $postedUserId = trim((string) ($_POST['user_id'] ?? ''));
        $isOwnProfile = $postedUserId === (string) $currentUser['id'];

        if (!$isOwnProfile && !$isAdmin) {
            throw new RuntimeException('You cannot update another user profile.');
        }

        if ($action === 'save-profile') {
            $auth->updateProfile($postedUserId, $_POST);
            $query = [];
            if ($isAdmin && !$isOwnProfile) {
                $query['user'] = $postedUserId;
            }

            myronRedirectWithFlash(myronBuildAdminUrl('identity.profile', $query), 'Profile settings saved.', 'success');
        }

        if ($action === 'save-password') {
            $password = (string) ($_POST['password'] ?? '');
            $confirm = (string) ($_POST['password_confirm'] ?? '');
            if ($password !== $confirm) {
                throw new RuntimeException('Passwords must match.');
            }

            $auth->updatePassword($postedUserId, $password);
            $query = [];
            if ($isAdmin && !$isOwnProfile) {
                $query['user'] = $postedUserId;
            }

            myronRedirectWithFlash(myronBuildAdminUrl('identity.profile', $query), 'Password updated.', 'success');
        }

        throw new RuntimeException('Unknown profile action.');
    } catch (Throwable $exception) {
        $query = [];
        if ($isAdmin && $targetUserId !== (string) $currentUser['id']) {
            $query['user'] = $targetUserId;
        }
        myronRedirectWithFlash(myronBuildAdminUrl('identity.profile', $query), $exception->getMessage(), 'error');
    }
}

myronRenderAdminShellStart($currentUser, [
    'title' => 'Profile',
    'titleContext' => 'Profile',
    'activeItem' => '',
]);
?>
<div class="mc-workspace__header">
  <?php myronRenderAdminBreadcrumbs([
      ['label' => 'Account', 'href' => myronBuildAdminUrl('identity.profile')],
      ['label' => 'Profile'],
  ]); ?>
  <div class="mc-workspace__title-row">
    <h1 class="mc-workspace__title">Profile</h1>
  </div>
  <p class="mc-workspace__subtitle">Manage user identity details, public profile fields, and password settings.</p>
</div>

<div class="mc-page-canvas mc-page-canvas--site">
  <div class="sg-main">
    <div class="mc-profile-layout">
      <section class="sg-section mc-profile-panel">
        <div class="mc-profile-hero">
          <div class="mc-profile-hero__avatar">
            <?php if (trim((string) ($targetUser['avatar_url'] ?? '')) !== ''): ?>
            <img src="<?= myronEscape((string) $targetUser['avatar_url']) ?>" alt="<?= myronEscape((string) $targetUser['display_name']) ?>">
            <?php else: ?>
            <span><?= myronEscape(myronUserInitials((string) $targetUser['display_name'])) ?></span>
            <?php endif; ?>
          </div>
          <div>
            <h2 class="mc-profile-hero__title"><?= myronEscape((string) $targetUser['display_name']) ?></h2>
            <p class="mc-profile-hero__meta"><?= myronEscape((string) ($targetUser['effective_role_name'] ?? $targetUser['role_name'] ?? '')) ?> · <?= myronEscape((string) $targetUser['email']) ?></p>
          </div>
        </div>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="save-profile">
          <input type="hidden" name="user_id" value="<?= myronEscape((string) $targetUser['id']) ?>">

          <label class="sg-field">
            <span class="sg-field__label">User Name</span>
            <input class="sg-field__control" type="text" value="<?= myronEscape((string) $targetUser['username']) ?>" readonly>
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Email</span>
            <input class="sg-field__control" type="email" name="email" required value="<?= myronEscape((string) $targetUser['email']) ?>">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">First Name</span>
            <input class="sg-field__control" type="text" name="first_name" value="<?= myronEscape((string) ($targetUser['first_name'] ?? '')) ?>">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Last Name</span>
            <input class="sg-field__control" type="text" name="last_name" value="<?= myronEscape((string) ($targetUser['last_name'] ?? '')) ?>">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Display Name</span>
            <input class="sg-field__control" type="text" name="display_name" required value="<?= myronEscape((string) $targetUser['display_name']) ?>">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Avatar</span>
            <input class="sg-field__control" type="url" name="avatar_url" value="<?= myronEscape((string) ($targetUser['avatar_url'] ?? '')) ?>" placeholder="https://example.com/avatar.jpg">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Job Title</span>
            <input class="sg-field__control" type="text" name="job_title" value="<?= myronEscape((string) ($targetUser['job_title'] ?? '')) ?>">
          </label>

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Bio</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="bio" rows="4"><?= myronEscape((string) ($targetUser['bio'] ?? '')) ?></textarea>
          </label>

          <label class="sg-field sg-field--full">
            <span class="sg-field__label">Schema SameAs URLs</span>
            <textarea class="sg-field__control sg-field__control--textarea" name="same_as_urls" rows="3"><?= myronEscape(implode("\n", array_map('strval', (array) json_decode((string) ($targetUser['same_as_urls_json'] ?? '[]'), true)))) ?></textarea>
          </label>

          <div class="sg-field sg-field--full">
            <span class="sg-field__label">Social Profiles</span>
            <div class="mc-profile-social-grid">
              <input class="sg-field__control" type="url" name="facebook_url" value="<?= myronEscape((string) ($targetUser['facebook_url'] ?? '')) ?>" placeholder="Facebook URL">
              <input class="sg-field__control" type="url" name="x_url" value="<?= myronEscape((string) ($targetUser['x_url'] ?? '')) ?>" placeholder="X URL">
              <input class="sg-field__control" type="url" name="pinterest_url" value="<?= myronEscape((string) ($targetUser['pinterest_url'] ?? '')) ?>" placeholder="Pinterest URL">
              <input class="sg-field__control" type="url" name="linkedin_url" value="<?= myronEscape((string) ($targetUser['linkedin_url'] ?? '')) ?>" placeholder="LinkedIn URL">
              <input class="sg-field__control" type="url" name="youtube_url" value="<?= myronEscape((string) ($targetUser['youtube_url'] ?? '')) ?>" placeholder="YouTube URL">
              <input class="sg-field__control" type="url" name="instagram_url" value="<?= myronEscape((string) ($targetUser['instagram_url'] ?? '')) ?>" placeholder="Instagram URL">
              <input class="sg-field__control" type="url" name="tiktok_url" value="<?= myronEscape((string) ($targetUser['tiktok_url'] ?? '')) ?>" placeholder="TikTok URL">
            </div>
          </div>

          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Profile Settings</button>
          </div>
        </form>
      </section>

      <section class="sg-section mc-profile-panel">
        <h2 class="sg-section__title">Password</h2>
        <p class="sg-section__subtitle">Set a new password for this account.</p>

        <form method="post" class="sg-form-grid">
          <input type="hidden" name="csrf_token" value="<?= myronEscape($csrfToken) ?>">
          <input type="hidden" name="action" value="save-password">
          <input type="hidden" name="user_id" value="<?= myronEscape((string) $targetUser['id']) ?>">

          <label class="sg-field">
            <span class="sg-field__label">New Password</span>
            <input class="sg-field__control" type="password" name="password" required placeholder="At least 8 characters">
          </label>

          <label class="sg-field">
            <span class="sg-field__label">Confirm Password</span>
            <input class="sg-field__control" type="password" name="password_confirm" required placeholder="Repeat password">
          </label>

          <div class="sg-card__actions">
            <button class="sg-button sg-button--primary" type="submit">Save Password</button>
          </div>
        </form>
      </section>
    </div>
  </div>
</div>
<?php myronRenderAdminShellEnd(); ?>
