<?php
$profileImage = $customerInfo['Image'] ?? ($customerInfo['image'] ?? base_url('assets/images/avatars/01.png'));
$bio = isset($customerInfo['Bio']) ? trim($customerInfo['Bio']) : ($customerInfo['bio'] ?? '');
$tags = $customerInfo['Tags'] ?? ($customerInfo['tags'] ?? []);
if (is_string($tags)) {
    $decodedTags = json_decode($tags, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decodedTags)) {
        $tags = $decodedTags;
    }
}
$tags = is_array($tags) ? array_filter($tags) : [];

$socialLinksRaw = $customerInfo['SocialLink'] ?? ($customerInfo['socialLinks'] ?? []);
if (is_string($socialLinksRaw)) {
    $decodedLinks = json_decode($socialLinksRaw, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decodedLinks)) {
        $socialLinksRaw = $decodedLinks;
    }
}
$socialLinks = is_array($socialLinksRaw) ? $socialLinksRaw : [];

$blockedUsers = $customerInfo['BlockedUsers'] ?? ($customerInfo['blockedUsers'] ?? []);
if (is_string($blockedUsers)) {
    $decodedBlocked = json_decode($blockedUsers, true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decodedBlocked)) {
        $blockedUsers = $decodedBlocked;
    }
}
$blockedUsers = is_array($blockedUsers) ? $blockedUsers : [];

$socialIconMap = [
    'instagram' => 'bi-instagram',
    'youtube'   => 'bi-youtube',
    'tiktok'    => 'bi-tiktok',
    'facebook'  => 'bi-facebook',
    'twitter'   => 'bi-twitter',
    'x'         => 'bi-twitter',
    'linkedin'  => 'bi-linkedin',
    'website'   => 'bi-link-45deg',
];

function displayValue($value)
{
    if (is_array($value)) {
        return json_encode($value, JSON_PRETTY_PRINT);
    }
    if (is_bool($value)) {
        return $value ? 'Yes' : 'No';
    }
    return htmlspecialchars((string)$value);
}
?>

<!--start main wrapper-->
<main class="main-wrapper">
  <div class="main-content customer-profile">
    <div class="profile-header card border-0 shadow-sm mb-4">
      <div class="card-body d-flex flex-column flex-lg-row align-items-lg-center gap-4">
        <div class="profile-avatar">
          <img src="<?php echo htmlspecialchars($profileImage); ?>" alt="Profile image" class="img-fluid rounded-circle">
        </div>
        <div class="flex-grow-1">
          <div class="d-flex flex-column flex-md-row align-items-md-center justify-content-between gap-3">
            <div>
              <div class="d-flex align-items-center gap-2 mb-1">
                <h3 class="profile-name mb-0"><?php echo isset($customerInfo['fullName']) ? htmlspecialchars($customerInfo['fullName']) : 'Unnamed User'; ?></h3>
                <?php if (!empty($customerInfo['tickRequestStatus']) && strtolower($customerInfo['tickRequestStatus']) === 'approved'): ?>
                  <span class="badge bg-primary-soft text-primary"><i class="bi bi-patch-check-fill me-1"></i>Verified</span>
                <?php endif; ?>
              </div>
              <p class="text-muted mb-2">@<?php echo isset($customerInfo['userName']) ? htmlspecialchars($customerInfo['userName']) : 'username'; ?></p>
              <?php if (!empty($bio)): ?>
                <p class="profile-bio mb-2"><i class="bi bi-quote me-2 text-primary"></i><?php echo nl2br(htmlspecialchars($bio)); ?></p>
              <?php endif; ?>
              <?php if (!empty($tags)): ?>
                <div class="profile-tags mb-2">
                  <?php foreach ($tags as $tag): ?>
                    <span class="badge bg-light text-primary">#<?php echo htmlspecialchars($tag); ?></span>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
              <?php if (!empty($socialLinks)): ?>
                <div class="profile-social d-flex flex-wrap gap-2">
                  <?php foreach ($socialLinks as $name => $url):
                    if (empty($url)) continue;
                    $key = strtolower($name);
                    $icon = $socialIconMap[$key] ?? 'bi-link-45deg';
                  ?>
                    <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" rel="noopener" class="btn btn-outline-primary btn-sm">
                      <i class="bi <?php echo $icon; ?> me-1"></i><?php echo ucwords($key); ?>
                    </a>
                  <?php endforeach; ?>
                </div>
              <?php endif; ?>
      </div>
            <div class="profile-actions text-md-end">
              <a href="<?php echo base_url(); ?>customer/editCustomer/<?php echo $customerId; ?>" class="btn btn-warning me-2">
          <i class="bi bi-pencil"></i> Edit
        </a>
        <a href="<?php echo base_url(); ?>customer/customers" class="btn btn-secondary">
          <i class="bi bi-arrow-left"></i> Back to Customers
        </a>
      </div>
    </div>
        </div>
      </div>
      <div class="card-footer bg-transparent border-0 pt-0">
        <div class="row row-cols-2 row-cols-md-4 g-3 text-center">
          <div class="col">
            <div class="stat-block">
              <span class="stat-label">Followers</span>
              <span class="stat-value"><?php echo isset($customerInfo['userFollowers']) ? count($customerInfo['userFollowers']) : 0; ?></span>
            </div>
          </div>
          <div class="col">
            <div class="stat-block">
              <span class="stat-label">Following</span>
              <span class="stat-value"><?php echo isset($customerInfo['userFollowings']) ? count($customerInfo['userFollowings']) : 0; ?></span>
            </div>
          </div>
          <div class="col">
            <div class="stat-block">
              <span class="stat-label">Warnings</span>
              <?php $warnings = isset($customerInfo['NooFwarning']) ? (int)$customerInfo['NooFwarning'] : 0; ?>
              <span class="stat-value <?php echo $warnings === 0 ? 'text-success' : ($warnings < 3 ? 'text-warning' : 'text-danger'); ?>"><?php echo $warnings; ?></span>
            </div>
          </div>
          <div class="col">
            <div class="stat-block">
              <span class="stat-label">Coins</span>
              <span class="stat-value text-primary"><?php echo isset($customerInfo['userCoins']) ? number_format($customerInfo['userCoins']) : 0; ?></span>
            </div>
          </div>
        </div>
      </div>
          </div>

    <div class="row g-4">
      <div class="col-xl-6">
        <div class="card border-0 shadow-sm h-100">
          <div class="card-header bg-white border-0">
            <h5 class="mb-0">Account Overview</h5>
          </div>
          <div class="card-body">
            <div class="row g-3">
              <div class="col-sm-6">
                <span class="overview-label">Email</span>
                <span class="overview-value"><?php echo isset($customerInfo['email']) ? htmlspecialchars($customerInfo['email']) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Role</span>
                <span class="overview-value badge bg-light text-dark"><?php echo isset($customerInfo['userRole']) ? htmlspecialchars($customerInfo['userRole']) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Status</span>
                <span class="overview-value">
                  <?php $isActive = isset($customerInfo['IsActive']) ? $customerInfo['IsActive'] : true; ?>
                  <span class="badge <?php echo $isActive ? 'bg-success' : 'bg-danger'; ?>"><?php echo $isActive ? 'Active' : 'Suspended'; ?></span>
                </span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Login Method</span>
                <span class="overview-value"><?php echo isset($customerInfo['loginMethod']) ? htmlspecialchars($customerInfo['loginMethod']) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Platform</span>
                <span class="overview-value"><?php echo isset($customerInfo['platform']) ? htmlspecialchars($customerInfo['platform']) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Join Date</span>
                <span class="overview-value"><?php echo isset($customerInfo['joinDate']) ? date('M j, Y g:i A', $customerInfo['joinDate'] / 1000) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Last Active</span>
                <span class="overview-value"><?php echo isset($customerInfo['lastActiveDate']) ? date('M j, Y g:i A', $customerInfo['lastActiveDate'] / 1000) : 'N/A'; ?></span>
              </div>
              <div class="col-sm-6">
                <span class="overview-label">Blocked Users</span>
                <span class="overview-value">
                  <?php if (!empty($blockedUsers)): ?>
                    <span class="badge bg-danger-soft text-danger"><?php echo count($blockedUsers); ?> blocked</span>
                  <?php else: ?>
                    <span class="text-muted">None</span>
                  <?php endif; ?>
                </span>
              </div>
          </div>
          </div>
        </div>
          </div>

      <div class="col-xl-6">
        <div class="card border-0 shadow-sm h-100">
          <div class="card-header bg-white border-0 d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Account Meta</h5>
            <?php if (!empty($blockedUsers)): ?>
              <span class="badge bg-danger-soft text-danger"><i class="bi bi-shield-exclamation me-1"></i>Contains blocked users</span>
            <?php endif; ?>
          </div>
          <div class="card-body">
            <div class="meta-table">
              <?php
              $safeData = $customerInfo;
              unset(
                $safeData['fullName'],
                $safeData['userName'],
                $safeData['email'],
                $safeData['userRole'],
                $safeData['IsActive'],
                $safeData['NooFwarning'],
                $safeData['userCoins'],
                $safeData['loginMethod'],
                $safeData['platform'],
                $safeData['joinDate'],
                $safeData['lastActiveDate'],
                $safeData['userFollowers'],
                $safeData['userFollowings'],
                $safeData['password'],
                $safeData['token'],
                $safeData['id'],
                $safeData['Image'],
                $safeData['image'],
                $safeData['Bio'],
                $safeData['bio'],
                $safeData['Tags'],
                $safeData['tags'],
                $safeData['SocialLink'],
                $safeData['socialLinks'],
                $safeData['BlockedUsers'],
                $safeData['blockedUsers']
              );
              ?>
              ?>
              <?php if (!empty($safeData)): ?>
                <?php foreach ($safeData as $key => $value): ?>
                  <div class="meta-row">
                    <span class="meta-key"><?php echo ucfirst(str_replace('_', ' ', $key)); ?></span>
                    <span class="meta-value"><?php echo displayValue($value); ?></span>
                  </div>
                <?php endforeach; ?>
              <?php endif; ?>
              <?php if (!empty($socialLinks)): ?>
                <div class="meta-row">
                  <span class="meta-key">Social Links</span>
                  <span class="meta-value social-links-list">
                    <?php foreach ($socialLinks as $name => $url): ?>
                      <?php if (empty($url)) continue; ?>
                      <a href="<?php echo htmlspecialchars($url); ?>" target="_blank" rel="noopener" class="d-inline-flex align-items-center me-3 mb-1">
                        <i class="bi bi-link-45deg me-1"></i><?php echo ucwords($name); ?>
                      </a>
                    <?php endforeach; ?>
                  </span>
                </div>
              <?php endif; ?>
            </div>
            <?php if (!empty($blockedUsers)): ?>
              <div class="mt-3">
                <h6 class="fw-semibold">Blocked Users</h6>
                <div class="blocked-grid">
                  <?php foreach ($blockedUsers as $blockedId => $status): ?>
                    <div class="blocked-item">
                      <span class="blocked-id" title="<?php echo htmlspecialchars($blockedId); ?>"><?php echo htmlspecialchars($blockedId); ?></span>
                      <span class="badge bg-danger-soft text-danger text-capitalize"><?php echo htmlspecialchars($status); ?></span>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>
            <?php endif; ?>
          </div>
        </div>
      </div>
          </div>

    <div class="card mt-4">
      <div class="card-header bg-white border-0 d-flex flex-column flex-md-row align-items-md-center justify-content-between">
        <div>
          <h5 class="mb-1">Posts by <?php echo isset($customerInfo['fullName']) ? htmlspecialchars($customerInfo['fullName']) : 'this user'; ?></h5>
          <p class="text-muted mb-0">Latest uploads from this creator</p>
        </div>
      </div>
      <div class="card-body">
        <div id="customer-posts-feed" class="row g-4">
          <?php if (!empty($customerPosts)): ?>
            <?php $this->load->view('foryou/_posts', ['posts' => $customerPosts, 'context' => 'customer']); ?>
          <?php endif; ?>
          </div>

        <div id="customer-posts-loader" class="text-center py-4 <?php echo !empty($customerPosts) && $postsPagination['hasMore'] ? '' : 'd-none'; ?>">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Loading...</span>
          </div>
        </div>

        <div id="customer-posts-empty" class="text-center py-5 <?php echo empty($customerPosts) ? '' : 'd-none'; ?>">
          <img src="<?php echo base_url('assets/images/empty-state.svg'); ?>" alt="No posts" class="empty-illustration mb-3">
          <h6 class="fw-semibold">No posts found for this user</h6>
          <p class="text-muted mb-0">When this creator publishes, their content will appear here.</p>
        </div>
      </div>
    </div>
  </div>
</main>
<!--end main wrapper-->

<style>
  .customer-profile {
    padding: 1.5rem;
  }
  .profile-header {
    background: linear-gradient(135deg, rgba(79, 70, 229, 0.08), rgba(14, 165, 233, 0.08));
  }
  .profile-avatar img {
    width: 120px;
    height: 120px;
    object-fit: cover;
    border-radius: 50%;
    border: 4px solid #fff;
    box-shadow: 0 8px 18px rgba(79, 70, 229, 0.15);
  }
  .profile-name {
    font-weight: 700;
  }
  .profile-bio {
    font-size: 0.95rem;
    max-width: 560px;
  }
  .profile-tags .badge {
    margin-right: 0.35rem;
  }
  .profile-social .btn {
    border-radius: 999px;
    font-weight: 500;
  }
  .stat-block {
    background: #fff;
    border-radius: 14px;
    padding: 1rem 0.75rem;
    box-shadow: 0 6px 16px rgba(15, 23, 42, 0.08);
  }
  .stat-label {
    display: block;
    font-size: 0.75rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: #6b7280;
  }
  .stat-value {
    display: block;
    font-size: 1.25rem;
    font-weight: 700;
  }
  .overview-label {
    display: block;
    font-size: 0.8rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: #6b7280;
    margin-bottom: 0.25rem;
  }
  .overview-value {
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
  }
  .meta-table {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 1rem;
  }
  .meta-row {
    background: #f9fafb;
    border-radius: 12px;
    padding: 0.75rem 1rem;
  }
  .meta-key {
    display: block;
    font-size: 0.75rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: #6b7280;
  }
  .meta-value {
    font-weight: 600;
    color: #111827;
  }
  .blocked-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 0.75rem;
  }
  .blocked-item {
    background: rgba(239, 68, 68, 0.08);
    border-radius: 10px;
    padding: 0.65rem 0.75rem;
  }
  .blocked-id {
    display: block;
    font-weight: 600;
    font-size: 0.85rem;
    color: #991b1b;
  }
  #customer-posts-feed .post-card {
    border-radius: 18px;
    overflow: hidden;
  }
  #customer-posts-feed .post-video {
    width: 100%;
    max-height: 320px;
    object-fit: cover;
  }
  #customer-posts-feed .author-avatar {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid rgba(79, 70, 229, 0.2);
  }
  #customer-posts-feed .author-avatar.placeholder {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: rgba(79, 70, 229, 0.1);
    color: #4f46e5;
    font-size: 1.25rem;
  }
  #customer-posts-feed .song-chip {
    display: inline-flex;
    align-items: center;
    padding: 0.35rem 0.75rem;
    border-radius: 999px;
    background: rgba(79, 70, 229, 0.08);
    color: #4f46e5;
    font-size: 0.85rem;
  }
  #customer-posts-feed .meta-grid {
    border: 1px solid rgba(0,0,0,0.05);
    border-radius: 12px;
    padding: 0.75rem;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 0.5rem 1rem;
    background: #f9fafb;
  }
  #customer-posts-feed .meta-label {
    font-size: 0.75rem;
    text-transform: uppercase;
    letter-spacing: 0.05em;
    color: #6b7280;
  }
  #customer-posts-feed .meta-value {
    font-weight: 500;
    color: #111827;
  }
  #customer-posts-feed .foryou-post-card.fade-out {
    opacity: 0;
    transition: opacity 0.3s ease;
  }
  .empty-illustration {
    max-width: 160px;
    opacity: 0.8;
  }
  @media (max-width: 767px) {
    .meta-table {
      grid-template-columns: 1fr;
    }
  }
  .bg-primary-soft { background: rgba(79, 70, 229, 0.12) !important; }
  .bg-success-soft { background: rgba(16, 185, 129, 0.12) !important; }
  .bg-warning-soft { background: rgba(251, 191, 36, 0.20) !important; }
  .bg-danger-soft { background: rgba(239, 68, 68, 0.15) !important; }
  .bg-secondary-soft { background: rgba(107, 114, 128, 0.15) !important; }
</style>

<script>
  (function() {
    const feedEl = document.getElementById('customer-posts-feed');
    const loaderEl = document.getElementById('customer-posts-loader');
    const emptyEl = document.getElementById('customer-posts-empty');
    if (!feedEl || !loaderEl || !emptyEl) return;

    let currentPage = <?php echo (int)($postsPagination['current'] ?? 1); ?>;
    const perPage = <?php echo (int)($postsPagination['perPage'] ?? 9); ?>;
    let hasMore = <?php echo !empty($postsPagination['hasMore']) ? 'true' : 'false'; ?>;
    let isLoading = false;
    const customerId = '<?php echo htmlspecialchars($customerId); ?>';

    const toggleEmptyState = () => {
      const hasCards = !!feedEl.querySelector('.foryou-post-card');
      if (hasCards) {
        emptyEl.classList.add('d-none');
      } else {
        emptyEl.classList.remove('d-none');
      }
    };

    const loadMore = () => {
      if (isLoading || !hasMore) return;
      isLoading = true;
      loaderEl.classList.remove('d-none');

      const params = new URLSearchParams({
        page: currentPage + 1,
        customerId: customerId
      });

      fetch('<?php echo base_url('customer/loadCustomerPosts'); ?>?' + params.toString(), {
        headers: { 'X-Requested-With': 'XMLHttpRequest' }
      })
        .then(res => res.json())
        .then(data => {
          if (data && data.success) {
            if (data.html) {
              const temp = document.createElement('div');
              temp.innerHTML = data.html;
              temp.querySelectorAll('.foryou-post-card').forEach(card => feedEl.appendChild(card));
              attachMarkHandlers();
              currentPage = data.page;
              hasMore = data.hasMore;
              toggleEmptyState();
            } else {
              hasMore = false;
            }
          } else {
            hasMore = false;
          }
        })
        .catch(() => { hasMore = false; })
        .finally(() => {
          loaderEl.classList.toggle('d-none', !hasMore);
          isLoading = false;
        });
    };

    const observer = new IntersectionObserver(entries => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          loadMore();
        }
      });
    }, { rootMargin: '200px' });

    observer.observe(loaderEl);

    const attachMarkHandlers = () => {
      document.querySelectorAll('.btn-delete-post').forEach(btn => {
        if (btn.dataset.bound === 'true') return;
        btn.dataset.bound = 'true';
        btn.addEventListener('click', () => {
          const postId = btn.getAttribute('data-post-id');
          if (!postId || btn.disabled) return;

          btn.disabled = true;
          btn.innerHTML = '<span class="spinner-border spinner-border-sm me-1"></span>Deleting...';

          fetch('<?php echo base_url('foryou/deletePost'); ?>', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
              'X-Requested-With': 'XMLHttpRequest'
            },
            body: 'postId=' + encodeURIComponent(postId)
          })
            .then(res => res.json())
            .then(data => {
              if (data && data.success) {
                const card = btn.closest('.foryou-post-card');
                if (card) {
                  card.classList.add('fade-out');
                  setTimeout(() => card.remove(), 300);
                }
              } else {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-trash me-1"></i>Delete Post';
              }
              toggleEmptyState();
            })
            .catch(() => {
              btn.disabled = false;
              btn.innerHTML = '<i class="bi bi-trash me-1"></i>Delete Post';
            });
        });
      });
    };

    attachMarkHandlers();
    toggleEmptyState();

    const mutationObserver = new MutationObserver(() => {
      attachMarkHandlers();
      toggleEmptyState();
    });
    mutationObserver.observe(feedEl, { childList: true });
  })();
</script>

