<?php
session_start();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); 

if (!isset($_SESSION['authenticated']) || $_SESSION['authenticated'] !== true) {
    header('Location: admin.php');
    exit;
}
$dataFile = __DIR__ . '/data.json';
$message = '';
$data = [
    'name' => 'MADISON LIPPY',
    'link' => 'https://a.vlmjm1.com/10e02e21-dd1f-45b8-a149-5bbc69ec9c4d?aff_id=387305&aff_sub5=SF_006OG00000IE3Of&source=CHELSEYLEIGH',
    'photos_count' => 917,
    'videos_count' => 367,
    'profile_image' => 'img/profile.jpeg',
    'livestream_image' => '',
    'gallery_images' => [
        'img/gallery1.jpeg',
        'img/gallery2.jpeg',
        'img/gallery3.jpeg',
        'img/gallery4.jpeg'
    ]
];

if (file_exists($dataFile)) {
    $content = file_get_contents($dataFile);
    $parsed = json_decode($content, true);
    if (is_array($parsed)) {
        $data = array_replace_recursive($data, $parsed);
    }
}
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    unset($_SESSION['flash_message']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $updated = [
        'name' => trim($_POST['name'] ?? $data['name']),
        'link' => trim($_POST['link'] ?? $data['link']),
        'photos_count' => (int) ($_POST['photos_count'] ?? $data['photos_count']),
        'videos_count' => (int) ($_POST['videos_count'] ?? $data['videos_count']),
        'profile_image' => $data['profile_image'],
        'livestream_image' => $data['livestream_image'] ?? '',
        'gallery_images' => $data['gallery_images'],
        'gallery_videos' => $data['gallery_videos'] ?? []
    ];
    $filesToDelete = [];

    //  Handle Profile Image Deletion
    if (isset($_POST['delete_profile']) && $_POST['delete_profile'] === '1') {
        if (!empty($updated['profile_image'])) {
            $filesToDelete[$updated['profile_image']] = true;
        }
        $updated['profile_image'] = '';
    }

    // Handle Livestream Image Deletion
    if (isset($_POST['delete_livestream']) && $_POST['delete_livestream'] === '1') {
        if (!empty($updated['livestream_image'])) {
            $filesToDelete[$updated['livestream_image']] = true;
        }
        $updated['livestream_image'] = '';
    }

    //  Handle Profile Image Upload
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
        $fileTmp = $_FILES['profile_image']['tmp_name'];
        $fileSize = $_FILES['profile_image']['size'];
        
        $fileType = mime_content_type($fileTmp);
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        $maxSize = 20 * 1024 * 1024; // 20 MB

        if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
            $ext = 'jpg';
            if ($fileType === 'image/png') $ext = 'png';
            if ($fileType === 'image/webp') $ext = 'webp';
            
            $newName = 'img/profile_' . bin2hex(random_bytes(3)) . '.' . $ext;
            
            if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                if (!empty($updated['profile_image'])) {
                    $filesToDelete[$updated['profile_image']] = true;
                }
                $updated['profile_image'] = $newName;
            }
        }
    }

    // Handle Livestream Image Upload
    if (isset($_FILES['livestream_image']) && $_FILES['livestream_image']['error'] === UPLOAD_ERR_OK) {
        $fileTmp = $_FILES['livestream_image']['tmp_name'];
        $fileSize = $_FILES['livestream_image']['size'];
        
        $fileType = mime_content_type($fileTmp);
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
        
        if (in_array($fileType, $allowedTypes) && $fileSize <= (20 * 1024 * 1024)) {
            $ext = 'jpg';
            if ($fileType === 'image/png') $ext = 'png';
            if ($fileType === 'image/webp') $ext = 'webp';
            
            $newName = 'img/livestream_' . bin2hex(random_bytes(3)) . '.' . $ext;
            
            if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                if (!empty($updated['livestream_image'])) {
                    $filesToDelete[$updated['livestream_image']] = true;
                }
                $updated['livestream_image'] = $newName;
            }
        }
    }

        // GALLERY IMAGES LOGIC
    $maxGalleryLimit = 6;

    // Handle Deletions First
    if (!empty($_POST['delete_gallery']) && is_array($_POST['delete_gallery'])) {
        $deleteIndices = $_POST['delete_gallery'];
        rsort($deleteIndices);
        
        foreach ($deleteIndices as $index) {
            if (isset($updated['gallery_images'][$index])) {
                $filesToDelete[$updated['gallery_images'][$index]] = true;
                unset($updated['gallery_images'][$index]);
            }
        }
    }

    // Handle Replacements 
    if (!empty($_FILES['replace_gallery']['name']) && is_array($_FILES['replace_gallery']['name'])) {
        foreach ($_FILES['replace_gallery']['name'] as $index => $name) {
            if ($_FILES['replace_gallery']['error'][$index] === UPLOAD_ERR_OK) {
                $fileTmp = $_FILES['replace_gallery']['tmp_name'][$index];
                $fileSize = $_FILES['replace_gallery']['size'][$index];
                $fileType = mime_content_type($fileTmp);
                $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                
                if (in_array($fileType, $allowedTypes) && $fileSize <= (20 * 1024 * 1024)) {
                    $ext = 'jpg';
                    if ($fileType === 'image/png') $ext = 'png';
                    if ($fileType === 'image/webp') $ext = 'webp';
                    
                    $newName = 'img/gallery_' . bin2hex(random_bytes(3)) . '.' . $ext;
                    
                    if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                        if (isset($updated['gallery_images'][$index])) {
                            $filesToDelete[$updated['gallery_images'][$index]] = true;
                        }
                        $updated['gallery_images'][$index] = $newName;
                    }
                }
            }
        }
    }

    // Handle New Additions (Appending to the end)
    if (!empty($_FILES['new_gallery']['name']) && is_array($_FILES['new_gallery']['name'])) {
        foreach ($_FILES['new_gallery']['name'] as $i => $name) {
    

            if ($_FILES['new_gallery']['error'][$i] === UPLOAD_ERR_OK) {
                $fileTmp = $_FILES['new_gallery']['tmp_name'][$i];
                $fileSize = $_FILES['new_gallery']['size'][$i];
                $fileType = mime_content_type($fileTmp);
                $allowedTypes = ['image/jpeg', 'image/png', 'image/webp'];
                
                if (in_array($fileType, $allowedTypes) && $fileSize <= (20 * 1024 * 1024)) {
                    $ext = 'jpg';
                    if ($fileType === 'image/png') $ext = 'png';
                    if ($fileType === 'image/webp') $ext = 'webp';
                    
                    $newName = 'img/gallery_' . bin2hex(random_bytes(3)) . '.' . $ext;
                    
                    if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                        $updated['gallery_images'][] = $newName; // Append to end of array
                    }
                }
            }
        }
    }
    
    // Re-index the array to slide remaining images left and remove holes
    $updated['gallery_images'] = array_values($updated['gallery_images']);

    //
    if (!empty($_POST['delete_video']) && is_array($_POST['delete_video'])) {
        $deleteIndices = $_POST['delete_video'];
        rsort($deleteIndices);
        foreach ($deleteIndices as $index) {
            if (isset($updated['gallery_videos'][$index])) {
                $filesToDelete[$updated['gallery_videos'][$index]] = true;
                unset($updated['gallery_videos'][$index]);
            }
        }
        // Re-index moved to the end of the section
    }

    if (!empty($_FILES['replace_video']['name']) && is_array($_FILES['replace_video']['name'])) {
        foreach ($_FILES['replace_video']['name'] as $index => $name) {
            if ($_FILES['replace_video']['error'][$index] === UPLOAD_ERR_OK) {
                $fileTmp = $_FILES['replace_video']['tmp_name'][$index];
                $fileSize = $_FILES['replace_video']['size'][$index];
                $fileType = mime_content_type($fileTmp);
                $allowedTypes = ['video/mp4', 'video/webm'];
                
                if (in_array($fileType, $allowedTypes) && $fileSize <= (1024 * 1024 * 1024)) {
                    $ext = ($fileType === 'video/webm') ? 'webm' : 'mp4';
                    $newName = 'img/video_' . bin2hex(random_bytes(3)) . '.' . $ext;
                    if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                        if (isset($updated['gallery_videos'][$index])) {
                            $filesToDelete[$updated['gallery_videos'][$index]] = true;
                        }
                        $updated['gallery_videos'][$index] = $newName;
                    }
                }
            }
        }
    }

    if (!empty($_FILES['new_video']['name']) && is_array($_FILES['new_video']['name'])) {
        foreach ($_FILES['new_video']['name'] as $i => $name) {
            if ($_FILES['new_video']['error'][$i] === UPLOAD_ERR_OK) {
                $fileTmp = $_FILES['new_video']['tmp_name'][$i];
                $fileSize = $_FILES['new_video']['size'][$i];
                $fileType = mime_content_type($fileTmp);
                $allowedTypes = ['video/mp4', 'video/webm'];
                
                if (in_array($fileType, $allowedTypes) && $fileSize <= (1024 * 1024 * 1024)) {
                    $ext = ($fileType === 'video/webm') ? 'webm' : 'mp4';
                    $newName = 'img/video_' . bin2hex(random_bytes(3)) . '.' . $ext;
                    if (move_uploaded_file($fileTmp, __DIR__ . '/' . $newName)) {
                        $updated['gallery_videos'][] = $newName;
                    }
                }
            }
        }
    }

    $updated['gallery_videos'] = array_values($updated['gallery_videos']);


    //  Save changes to data.json
    if (file_put_contents($dataFile, json_encode($updated, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)) !== false) {
        
        // Safely delete old files ONLY AFTER JSON write succeeds
        foreach (array_keys($filesToDelete, ) as $oldPath) {
            if (strpos($oldPath, 'img/') === 0 && file_exists(__DIR__ . '/' . $oldPath)) {
                unlink(__DIR__ . '/' . $oldPath);
            }
        }
        $_SESSION['flash_message'] = 'Changes saved successfully.';
        header("Location: edit.php");
        exit;
    } else {
        $_SESSION['flash_message'] = 'Error: Could not save changes to data.json.';
        header("Location: edit.php");
        exit;
    }
}



function esc($value) {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin · Page Variables</title>
<link rel="icon" href="data:,">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
    :root {
        --bg: #0f1115;
        --panel: #161a22;
        --panel-2: #1d2230;
        --border: #2a2f3d;
        --accent: #ff4d6d;
        --accent-2: #6c5ce7;
        --text: #e8eaf0;
        --muted: #8a90a3;
    }
    body {
        background: radial-gradient(circle at top left, #1a1f2e 0%, var(--bg) 55%);
        color: var(--text);
        font-family: 'Segoe UI', Arial, sans-serif;
        min-height: 100vh;
    }
    .topbar {
        border-bottom: 1px solid var(--border);
        background: rgba(22, 26, 34, 0.85);
        backdrop-filter: blur(6px);
    }
    .topbar .brand {
        font-weight: 700;
        letter-spacing: .04em;
    }
    .brand-mark {
        width: 34px; height: 34px;
        border-radius: 9px;
        background: linear-gradient(135deg, var(--accent), var(--accent-2));
        display: inline-flex; align-items: center; justify-content: center;
        font-size: 1.1rem;
    }
    .page-wrap {
        max-width: 1040px;
        margin: 0 auto;
        padding: 32px 20px 60px;
    }
    .panel {
        background: var(--panel);
        border: 1px solid var(--border);
        border-radius: 16px;
    }
    .panel-header {
        padding: 20px 24px;
        border-bottom: 1px solid var(--border);
    }
    .panel-body { padding: 24px; }
    .section-title {
        font-size: .78rem;
        text-transform: uppercase;
        letter-spacing: .08em;
        color: var(--muted);
        font-weight: 600;
        margin-bottom: 14px;
    }
    .form-label {
        font-size: .82rem;
        font-weight: 600;
        color: var(--text);
        margin-bottom: 6px;
    }
    .form-control {
        background: var(--panel-2);
        border: 1px solid var(--border);
        color: var(--text);
        border-radius: 10px;
        padding: .6rem .85rem;
    }
    .form-control:focus {
        background: var(--panel-2);
        color: var(--text);
        border-color: var(--accent);
        box-shadow: 0 0 0 .2rem rgba(255, 77, 109, .15);
    }
    .form-text { color: var(--muted); }
    .input-icon-group { position: relative; }
    .input-icon-group .bi {
        position: absolute;
        top: 50%; left: 14px;
        transform: translateY(-50%);
        color: var(--muted);
        pointer-events: none;
    }
    .input-icon-group input { padding-left: 38px; }
    .stat-card {
        background: var(--panel-2);
        border: 1px solid var(--border);
        border-radius: 12px;
        padding: 16px 18px;
    }
    .stat-card .bi { font-size: 1.4rem; color: var(--accent); }
    .btn-save {
        background: linear-gradient(135deg, var(--accent), var(--accent-2));
        border: none;
        color: #fff;
        font-weight: 600;
        padding: .65rem 1.6rem;
        border-radius: 10px;
        box-shadow: 0 6px 16px rgba(255, 77, 109, .25);
    }
    .btn-save:hover { filter: brightness(1.08); color: #fff; }
    .btn-outline-soft {
        border: 1px solid var(--border);
        color: var(--text);
        border-radius: 10px;
        padding: .65rem 1.4rem;
        background: transparent;
    }
    .btn-outline-soft:hover {
        background: var(--panel-2);
        color: var(--text);
        border-color: var(--accent);
    }
    .alert-success {
        background: rgba(46, 204, 113, .12);
        border: 1px solid rgba(46, 204, 113, .35);
        color: #6fe3a0;
        border-radius: 10px;
    }
    .media-thumb {
        width: 100%;
        aspect-ratio: 1 / 1;
        object-fit: cover;
        border-radius: 10px;
        border: 1px solid var(--border);
        background: var(--panel-2);
    }
    .media-label {
        font-size: .72rem;
        color: var(--muted);
        margin-top: 6px;
        text-align: center;
        word-break: break-all;
    }
    .profile-thumb {
        width: 88px; height: 88px;
        object-fit: cover;
        border-radius: 14px;
        border: 2px solid var(--border);
    }
    code {
        background: var(--panel-2);
        padding: 2px 6px;
        border-radius: 6px;
        color: #ffb3c1;
    }
    .divider {
        border-color: var(--border);
        opacity: 1;
    }

    /* Profile Card */
    .profile-image-card {
        position:relative;
        width:220px;
        height:220px;
        border-radius:14px;
        overflow:hidden;
        background-color: var(--panel-2);
        border: 1px solid var(--border);
        box-shadow: 0 6px 15px rgba(0,0,0,0.25);
    }
    .profile-preview{
        width:100%;
        height:100%;
        object-fit:cover;
    }
    .image-actions {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    background: rgba(22, 26, 34, 0.85);
    backdrop-filter: blur(4px); 
    display: flex;
    justify-content: space-around;
    padding: 12px 0;
    border-top: 1px solid var(--border);
    }
    .replace-btn, .delete-btn {
    background: transparent;
    border: none;
    color: var(--muted);
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 6px;
    transition: color 0.2s ease;
    }
   .replace-btn:hover { color: #fff; }
   .delete-btn:hover { color: #ff4d6d; } 

       /* Gallery Upload Card Hover Effects */
    .upload-card { transition: all 0.2s ease; }
    .upload-card:hover {
        border-color: var(--accent) !important;
        background: rgba(255, 77, 109, 0.05) !important;
    }
    .upload-card:hover .upload-icon { color: var(--accent) !important; }

    .nav-tabs .nav-link { color: #b0b5c4; }
    .nav-tabs .nav-link:hover { color: var(--text); }
    .nav-tabs .nav-link.active { color: var(--text) !important; background: transparent !important; border-color: var(--border) var(--border) var(--panel) !important; }

</style>
</head>
<body>

<div class="topbar py-3">
    <div class="page-wrap py-0 d-flex align-items-center justify-content-between">
        <span class="brand d-flex align-items-center gap-2">
            <span class="brand-mark"><i class="bi bi-sliders"></i></span>
            <span class="d-none d-sm-inline">Admin</span>
            <span class="d-inline d-sm-none">Admin</span>
        </span>
        <div class="d-flex align-items-center gap-2">
            <a href="index.php" class="btn btn-outline-soft btn-sm" style="padding: 6px 12px; font-size: 0.85rem;">
                <i class="bi bi-box-arrow-up-right"></i> <span class="d-none d-sm-inline">View Profile</span><span class="d-inline d-sm-none">View</span>
            </a>
            <a href="logout.php" class="btn btn-sm" style="border-radius: 10px; padding: 6px 12px; background-color: #ff4d6d; border: none; color: #e8eaf0; font-weight: 600; font-size: 0.85rem;">Logout</a>
        </div>
    </div>
</div>

<div class="page-wrap">

    <?php if ($message): ?>
        <div id="successAlert" class="alert alert-success d-flex align-items-center gap-2 mb-4">
            <i class="bi bi-check-circle-fill"></i>
            <div><?= $message ?></div>
        </div>
        <script>
            setTimeout(() => {
                const alert = document.getElementById('successAlert');
                if (alert) {
                    alert.style.transition = "opacity 0.5s ease";
                    alert.style.opacity = "0";
                    setTimeout(() => alert.style.display = "none", 500);
                }
            }, 3000);
        </script>
    <?php endif ?>

    <div class="row g-4">
        <div class="col-lg-8">
            <div class="panel mb-4">
                <div class="panel-header d-flex align-items-center gap-2">
                    <i class="bi bi-person-circle"></i>
                    <span class="fw-semibold">Profile Details</span>
                </div>
                <div class="panel-body">
                    <form method="post" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label class="form-label">NAME</label>
                            <div class="input-icon-group">
                                <i class="bi bi-person"></i>
                                <input name="name" class="form-control" value="<?= esc($data['name']) ?>" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">AFFILIATE LINK</label>
                            <div class="input-icon-group">
                                <i class="bi bi-link-45deg"></i>
                                <input name="link" type="url" class="form-control" value="<?= esc($data['link']) ?>" required>
                            </div>
                            <div class="form-text">Used for every anchor/button on the page.</div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label fw-bold mb-3" style="color: var(--text);">PROFILE IMAGE</label>
                            <div class="profile-image-card">
                                <!-- Image Preview -->
                                 <img src="<?=esc ($data['profile_image']) ?>"class="profile-preview" alt="Profile Image">

                                 <!-- Hiddden File Input -->
                                  <input type="file" id="profileImageInput" name="profile_image" hidden  accept="image/*">
                                  <input type="hidden" id="deleteProfileFlag" name="delete_profile" value="0">
                                  <!-- Button-->
                                  <div class="image-actions">
                                    <button type="button" class="replace-btn" id="replaceProfileBtn">
                                        <i class="bi bi-pencil-square"></i>Replace </button>
                                        
                                        <button type="button" class="delete-btn" id="deleteProfileBtn">
                                        <i class="bi bi-trash"></i>Delete </button>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label class="form-label fw-bold mb-3" style="color: var(--text);">LIVESTREAM IMAGE</label>
                                <div class="profile-image-card" style="width: 100%; max-width: 350px; height: 180px;">
                                     <img src="<?= !empty($data['livestream_image']) ? esc($data['livestream_image']) : 'https://placehold.co/400x200?text=Default+(Profile+Image)' ?>" class="livestream-preview" alt="Livestream Banner" style="width:100%; height:100%; object-fit:cover;">
                                      <input type="file" id="livestreamImageInput" name="livestream_image" hidden accept="image/*">
                                      <input type="hidden" id="deleteLivestreamFlag" name="delete_livestream" value="0">
                                      <div class="image-actions">
                                        <button type="button" class="replace-btn" id="replaceLivestreamBtn">
                                            <i class="bi bi-pencil-square"></i>Upload </button>
                                            
                                        <button type="button" class="delete-btn" id="deleteLivestreamBtn">
                                            <i class="bi bi-trash"></i>Remove </button>
                                      </div>
                                </div>
                                <div class="form-text mt-2">If no banner is uploaded, the profile image will be used.</div>
                            </div>
                        
                                        
                                  <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">VIDEOS COUNT</label>
                                <div class="input-icon-group">
                                    <i class="bi bi-camera-video"></i>
                                    <input name="videos_count" type="number" min="0" class="form-control" value="<?= esc($data['videos_count']) ?>" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">PHOTOS COUNT</label>
                                <div class="input-icon-group">
                                    <i class="bi bi-image"></i>
                                    <input name="photos_count" type="number" min="0" class="form-control" value="<?= esc($data['photos_count']) ?>" required>
                                </div>
                            </div>
                        </div>
                        <div class="mb-4 mt-5">
                            <ul class="nav nav-tabs mb-4" id="mediaTabs" role="tablist" style="border-bottom-color: var(--border);">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active fw-bold" id="photos-tab" data-bs-toggle="tab" data-bs-target="#photos-pane" type="button" role="tab">PHOTOS (<?= count($data['gallery_images']) ?>)</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link fw-bold" id="videos-tab" data-bs-toggle="tab" data-bs-target="#videos-pane" type="button" role="tab">VIDEOS (<?= count($data['gallery_videos'] ?? []) ?>)</button>
                                </li>
                            </ul>
                            
                            <div class="tab-content" id="mediaTabsContent">
                                <!-- PHOTOS PANE -->
                                <div class="tab-pane fade show active" id="photos-pane" role="tabpanel">
                                    <div class="row g-3" id="gallery-container">
                                        <?php
                                         $galleryCount = count($data['gallery_images']);
                                         for ($i=0; $i<$galleryCount; $i++):
                                         $image = $data['gallery_images'][$i];
                                         ?>
                                         <div class="col-6 col-md-4 col-lg-4" id="gallery-wrapper-<?= $i ?>">
                                             <div class="profile-image-card" style="width:100%; aspect-ratio: 1 / 1;">
                                                 <img src="<?= esc($image) ?>" class="profile-preview" id="gallery-preview-<?= $i ?>">
                                                 <input type="file" id="galleryReplaceInput-<?= $i ?>" name="replace_gallery[<?= $i ?>]" hidden accept="image/*">
                                                 <div class="image-actions">
                                                     <button type="button" class="replace-btn" onclick="document.getElementById('galleryReplaceInput-<?= $i ?>').click();">
                                                         <i class="bi bi-pencil-square"></i> Replace
                                                     </button>
                                                     <button type="button" class="delete-btn" onclick="deleteGalleryImage(<?= $i ?>)">
                                                         <i class="bi bi-trash"></i> Delete
                                                     </button>
                                                 </div>
                                              </div>
                                         </div>
                                        <?php endfor; ?>

                                        <div class="col-6 col-md-4 col-lg-4">
                                            <div class="profile-image-card upload-card d-flex flex-column align-items-center justify-content-center" style="width:100%; aspect-ratio: 1 / 1; border: 2px dashed var(--border); background: transparent; cursor: pointer;" onclick="document.getElementById('galleryNewInput').click();">
                                                <i class="bi bi-plus-lg upload-icon" style="font-size: 2rem; color: var(--muted);"></i>
                                                <div class="mt-2 text-muted small fw-bold">Upload</div>
                                            </div>
                                        </div>
                                    </div>
                                    <input type="file" id="galleryNewInput" name="new_gallery[]" multiple hidden accept="image/*">
                                </div>
                                
                                <!-- VIDEOS PANE -->
                                <div class="tab-pane fade" id="videos-pane" role="tabpanel">
                                    <div class="row g-3" id="videos-container">
                                        <?php
                                         $videoCount = count($data['gallery_videos'] ?? []);
                                         for ($i=0; $i<$videoCount; $i++):
                                         $video = $data['gallery_videos'][$i];
                                         ?>
                                         <div class="col-6 col-md-4 col-lg-4" id="video-wrapper-<?= $i ?>">
                                             <div class="profile-image-card" style="width:100%; aspect-ratio: 1 / 1; position: relative; overflow: hidden; border-radius: 12px; border: 1px solid var(--border);">
                                                 <video src="<?= esc($video) ?>" class="profile-preview" id="video-preview-<?= $i ?>" style="object-fit: cover; width: 100%; height: 100%;" controls></video>
                                                 <input type="file" id="videoReplaceInput-<?= $i ?>" name="replace_video[<?= $i ?>]" hidden accept="video/mp4,video/webm">
                                                 <div class="image-actions">
                                                     <button type="button" class="replace-btn" onclick="document.getElementById('videoReplaceInput-<?= $i ?>').click();">
                                                         <i class="bi bi-pencil-square"></i> Replace
                                                     </button>
                                                     <button type="button" class="delete-btn" onclick="deleteVideo(<?= $i ?>)">
                                                         <i class="bi bi-trash"></i> Delete
                                                     </button>
                                                 </div>
                                             </div>
                                         </div>
                                         <?php endfor; ?>
                                         
                                         <div class="col-6 col-md-4 col-lg-4">
                                            <div class="profile-image-card upload-card-video d-flex flex-column align-items-center justify-content-center" style="width:100%; aspect-ratio: 1 / 1; border: 2px dashed var(--border); background: transparent; cursor: pointer;" onclick="document.getElementById('videoNewInput').click();">
                                                <i class="bi bi-plus-lg upload-icon-video" style="font-size: 2rem; color: var(--muted);"></i>
                                                <div class="mt-2 text-muted small fw-bold">Upload Video</div>
                                            </div>
                                         </div>
                                    </div>
                                    <input type="file" id="videoNewInput" name="new_video[]" multiple hidden accept="video/mp4,video/webm">
                                </div>
                            </div>
                        </div>
                        <hr class="divider my-4">
                        <div class="d-flex align-items-center gap-2">
                            <button class="btn-save"><i class="bi bi-save2 me-1"></i> Save</button>
                            <a class="btn btn-outline-soft" href="index.php">Cancel</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="panel mb-4">
                <div class="panel-header d-flex align-items-center gap-2">
                    <i class="bi bi-eye"></i>
                    <span class="fw-semibold">Live Preview</span>
                </div>
                <div class="panel-body">
                    <div class="d-flex align-items-center gap-3 mb-3">
                        <img src="<?= esc($data['profile_image']) ?>" alt="Profile" class="profile-thumb" onerror="this.src='https://placehold.co/88x88?text=N/A'">
                        <div>
                            <div class="fw-semibold"><?= esc($data['name']) ?></div>
                            <div class="small text-muted">Profile photo</div>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="stat-card text-center">
                                <i class="bi bi-camera-video d-block mb-1"></i>
                                <div class="fw-bold"><?= esc($data['videos_count']) ?></div>
                                <div class="small text-muted">Videos</div>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="stat-card text-center">
                                <i class="bi bi-image d-block mb-1"></i>
                                <div class="fw-bold"><?= esc($data['photos_count']) ?></div>
                                <div class="small text-muted">Photos</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



</div>
    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" style="max-width: 340px;">
        <div class="modal-content" style="background-color: var(--panel); border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 10px 30px rgba(0,0,0,0.5);">
          <div class="modal-body text-center py-4 px-4">
            <i class="bi bi-exclamation-circle mb-3" style="font-size: 3.5rem; color: #ff4d6d;"></i>
            <h5 class="mb-4 fw-bold" id="deleteModalMessage" style="color: var(--text);">Are you sure?</h5>
            <div class="d-flex justify-content-center gap-3">
              <button type="button" class="btn btn-outline-soft w-50" data-bs-dismiss="modal">Cancel</button>
              <button type="button" class="btn w-50" id="deleteModalConfirmBtn" style="background-color: #ff4d6d; color: white; border: none; font-weight: 600;">Delete</button>
            </div>
          </div>
        </div>
      </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
    let pendingDeleteAction = null;
    let deleteModalInstance = null;
    
    document.addEventListener("DOMContentLoaded", function() {
        deleteModalInstance = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
        
        document.getElementById('deleteModalConfirmBtn').addEventListener('click', function() {
            if (pendingDeleteAction) pendingDeleteAction();
            deleteModalInstance.hide();
        });
    });
    const replaceBtn = document.getElementById('replaceProfileBtn');
    const deleteBtn = document.getElementById('deleteProfileBtn');
    const profileInput = document.getElementById('profileImageInput');
    const profilePreview = document.querySelector('.profile-preview');
    const deleteFlag = document.getElementById("deleteProfileFlag");
    const PLACEHOLDER = "https://placehold.co/220x220?text=No+Image";

    //Btn clicked trigger the hidden file input 
    replaceBtn.addEventListener('click' , function(){
        profileInput.click();
    });

    profileInput.addEventListener("change",function(){
        const file = this.files[0];
        
        if(!file) return;
        profilePreview.src = URL.createObjectURL(file);
        deleteFlag.value = "0";
        
    });

    deleteBtn.addEventListener("click",() => {
       document.getElementById('deleteModalMessage').innerText = "Delete the current profile image?";
       pendingDeleteAction = () => {
           profilePreview.src = PLACEHOLDER;
           deleteFlag.value = "1";
           profileInput.value = "";
       };
       deleteModalInstance.show();
     });

    const replaceLsBtn = document.getElementById('replaceLivestreamBtn');
    const deleteLsBtn = document.getElementById('deleteLivestreamBtn');
    const lsInput = document.getElementById('livestreamImageInput');
    const lsPreview = document.querySelector('.livestream-preview');
    const deleteLsFlag = document.getElementById('deleteLivestreamFlag');
    const PLACEHOLDER_LS = "https://placehold.co/400x200?text=Default+(Profile+Image)";

    replaceLsBtn.addEventListener('click', function(){
        lsInput.click();
    });

    lsInput.addEventListener("change", function(){
        const file = this.files[0];
        if(!file) return;
        lsPreview.src = URL.createObjectURL(file);
        deleteLsFlag.value = "0";
    });

    deleteLsBtn.addEventListener("click", () => {
       document.getElementById('deleteModalMessage').innerText = "Remove the custom livestream banner?";
       pendingDeleteAction = () => {
           lsPreview.src = PLACEHOLDER_LS;
           deleteLsFlag.value = "1";
           lsInput.value = "";
       };
       deleteModalInstance.show();
    });

     //Gallery Images
     //preview for replace 
     <?php for ($i=0; $i<$galleryCount; $i++): ?>
        const replaceGallery<?= $i ?> = document.getElementById('galleryReplaceInput-<?= $i ?>');
        if (replaceGallery<?= $i?>) {
            replaceGallery<?= $i?>.addEventListener('change',function(){
                const file = this.files[0];
                if (!file) return;
                document.getElementById('gallery-preview-<?= $i ?>').src = URL.createObjectURL(file);
            });
        }
        <?php endfor; ?>

        //Handle deletion Frontend
         function deleteGalleryImage(index) {
        document.getElementById('deleteModalMessage').innerText = "Delete this gallery image?";
        pendingDeleteAction = () => {
            document.getElementById('gallery-wrapper-' + index).style.display = 'none';
            document.getElementById('galleryReplaceInput-' + index).value = '';
            const hiddenDelete = document.createElement('input');
            hiddenDelete.type = 'hidden';
            hiddenDelete.name = 'delete_gallery[]';
            hiddenDelete.value = index;
            document.getElementById('gallery-container').appendChild(hiddenDelete);
        };
        deleteModalInstance.show();
    }
    // Handle Additions (Alerting the user)
    document.getElementById('galleryNewInput').addEventListener('change', function() {
        if (this.files.length > 0) {
            const uploadCardTxt = document.querySelector('.upload-card .text-muted');
            if(uploadCardTxt) uploadCardTxt.innerText = this.files.length + " file(s) ready to save";
            const uploadCardIcon = document.querySelector('.upload-card .upload-icon');
            if(uploadCardIcon) {
                uploadCardIcon.classList.remove('bi-plus-lg');
                uploadCardIcon.classList.add('bi-check2-circle');
                uploadCardIcon.style.color = '#2ecc71';
            }
        }
    });

    // Handle Videos Additions
    document.getElementById('videoNewInput').addEventListener('change', function() {
        if (this.files.length > 0) {
            const uploadCardTxt = document.querySelector('.upload-card-video .text-muted');
            if(uploadCardTxt) uploadCardTxt.innerText = this.files.length + " video(s) ready to save";
            const uploadCardIcon = document.querySelector('.upload-card-video .upload-icon-video');
            if(uploadCardIcon) {
                uploadCardIcon.classList.remove('bi-plus-lg');
                uploadCardIcon.classList.add('bi-check2-circle');
                uploadCardIcon.style.color = '#2ecc71';
            }
        }
    });

    // Handle videos replacements preview
    <?php $videoCount = count($data['gallery_videos'] ?? []); for ($i=0; $i<$videoCount; $i++): ?>
    if(document.getElementById('videoReplaceInput-<?= $i ?>')) {
        document.getElementById('videoReplaceInput-<?= $i ?>').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;
            document.getElementById('video-preview-<?= $i ?>').src = URL.createObjectURL(file);
        });
    }
    <?php endfor; ?>

    // Handle Videos Deletion
    function deleteVideo(index) {
        document.getElementById('deleteModalMessage').innerText = "Delete this video?";
        pendingDeleteAction = () => {
            document.getElementById('video-wrapper-' + index).style.display = 'none';
            document.getElementById('videoReplaceInput-' + index).value = '';
            
            const hiddenDelete = document.createElement('input');
            hiddenDelete.type = 'hidden';
            hiddenDelete.name = 'delete_video[]';
            hiddenDelete.value = index;
            document.getElementById('videos-container').appendChild(hiddenDelete);
        };
        deleteModalInstance.show();
    }

    // Toggle tab active styles
    document.querySelectorAll('#mediaTabs .nav-link').forEach(tab => {
        tab.addEventListener('click', function() {
            document.querySelectorAll('#mediaTabs .nav-link').forEach(t => {
                t.style.color = 'var(--muted)';
            });
            this.style.color = 'var(--text)';
        });
    });
      
    </script>
</body>
</html>
