<?php
/**
 * gallery_logic.php - প্রতিষ্ঠানের ফটো গ্যালারি ম্যানেজমেন্ট সিস্টেম
 */

// ১. সেশন শুরু
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// ২. Helper Function (সবার উপরে ডিফাইন করা হলো যাতে এরর না আসে)
if (!function_exists('mysqli_real_escape_with_safe')) {
    function mysqli_real_escape_with_safe($conn, $data) {
        // null চেক যুক্ত করা হয়েছে
        $data = $data ?? "";
        return mysqli_real_escape_string($conn, htmlspecialchars($data));
    }
}

// ৩. ডিরেক্টরি সেটআপ
$upload_base = 'assets/files/gallery/';
if (!file_exists($upload_base)) {
    mkdir($upload_base, 0777, true);
}

// ৪. নতুন অ্যালবাম তৈরি করা
if (isset($_POST['create_album'])) {
    $name = mysqli_real_escape_with_safe($conn, $_POST['album_name']);
    $desc = mysqli_real_escape_with_safe($conn, $_POST['album_desc']); 
    $date = mysqli_real_escape_with_safe($conn, $_POST['album_date']);
    
    $query = "INSERT INTO gallery_albums (album_name, album_desc, album_date) VALUES ('$name', '$desc', '$date')";
    if (mysqli_query($conn, $query)) {
        $_SESSION['gallery_msg'] = 'album_created';
    }
    echo "<script>window.location.href='admin.php?view=gallery';</script>";
    exit();
}

// ৫. অ্যালবাম এডিট লজিক
if (isset($_POST['update_album'])) {
    $album_id = intval($_POST['album_id']);
    $name = mysqli_real_escape_with_safe($conn, $_POST['album_name']);
    $desc = mysqli_real_escape_with_safe($conn, $_POST['album_desc']); 
    $date = mysqli_real_escape_with_safe($conn, $_POST['album_date']);
    
    $query = "UPDATE gallery_albums SET album_name = '$name', album_desc = '$desc', album_date = '$date' WHERE id = $album_id";
    if (mysqli_query($conn, $query)) {
        $_SESSION['gallery_msg'] = 'album_updated';
    }
    echo "<script>window.location.href='admin.php?view=gallery';</script>";
    exit();
}

// ৬. অ্যালবামে ছবি আপলোড করা
if (isset($_POST['upload_images'])) {
    $album_id = intval($_POST['album_id']);
    $files = $_FILES['images'];

    foreach ($files['name'] as $key => $name) {
        if ($files['error'][$key] == 0) {
            $ext = pathinfo($name, PATHINFO_EXTENSION);
            $new_name = "img_" . time() . "_" . $key . "." . $ext;
            $target = $upload_base . $new_name;

            if (move_uploaded_file($files['tmp_name'][$key], $target)) {
                $query = "INSERT INTO gallery_images (album_id, image_path) VALUES ('$album_id', '$target')";
                mysqli_query($conn, $query);
                
                mysqli_query($conn, "UPDATE gallery_albums SET cover_image = '$target' WHERE id = '$album_id' AND (cover_image IS NULL OR cover_image = '')");
            }
        }
    }
    $_SESSION['gallery_msg'] = 'images_uploaded';
    echo "<script>window.location.href='admin.php?view=gallery&album_id=$album_id';</script>";
    exit();
}

// ৭. ছবি ডিলিট করা
if (isset($_GET['delete_image'])) {
    $img_id = intval($_GET['delete_image']);
    $res = mysqli_query($conn, "SELECT image_path, album_id FROM gallery_images WHERE id = $img_id");
    $row = mysqli_fetch_assoc($res);
    if ($row) {
        if (file_exists($row['image_path'])) unlink($row['image_path']);
        mysqli_query($conn, "DELETE FROM gallery_images WHERE id = $img_id");
        $redirect_id = $row['album_id'];
        echo "<script>window.location.href='admin.php?view=gallery&album_id=$redirect_id';</script>";
    } else {
        echo "<script>window.location.href='admin.php?view=gallery';</script>";
    }
    exit();
}

// ৮. অ্যালবাম ডিলিট করা
if (isset($_GET['delete_album'])) {
    $album_id = intval($_GET['delete_album']);
    $res = mysqli_query($conn, "SELECT image_path FROM gallery_images WHERE album_id = $album_id");
    while ($row = mysqli_fetch_assoc($res)) {
        if (file_exists($row['image_path'])) unlink($row['image_path']);
    }
    mysqli_query($conn, "DELETE FROM gallery_albums WHERE id = $album_id");
    echo "<script>window.location.href='admin.php?view=gallery';</script>";
    exit();
}

$current_album_id = isset($_GET['album_id']) ? intval($_GET['album_id']) : null;
$albums = mysqli_query($conn, "SELECT * FROM gallery_albums ORDER BY album_date DESC");

$current_album_details = null;
$album_images = [];
if ($current_album_id) {
    $res = mysqli_query($conn, "SELECT * FROM gallery_albums WHERE id = $current_album_id");
    $current_album_details = mysqli_fetch_assoc($res);
    $album_images = mysqli_query($conn, "SELECT * FROM gallery_images WHERE album_id = $current_album_id");
}

$alert = "";
if (isset($_SESSION['gallery_msg'])) {
    $msg = $_SESSION['gallery_msg'];
    if ($msg == 'album_created') $alert = "<div class='alert success'>নতুন অ্যালবাম তৈরি হয়েছে!</div>";
    if ($msg == 'album_updated') $alert = "<div class='alert success'>অ্যালবাম আপডেট করা হয়েছে!</div>";
    if ($msg == 'images_uploaded') $alert = "<div class='alert success'>ছবিগুলো সফলভাবে আপলোড হয়েছে!</div>";
    unset($_SESSION['gallery_msg']);
}
?>

<style>
    :root {
        --primary-color: #00aeef;
        --secondary-color: #57a03a;
        --dark-bg: #1a1a1a;
        --white: #ffffff;
        --light-bg: #f8f9fa;
        --card-bg: #ffffff;
        --danger: #ef4444;
    }
    .gallery-admin { padding: 20px; min-height: 100vh; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    .header-box { background: var(--white); padding: 5px 10px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; border-left: 5px solid var(--primary-color); }
    .btn-main { background: var(--primary-color); color: white; padding: 10px 20px; border: none; border-radius: 8px; cursor: pointer; text-decoration: none; font-weight: 600; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s; }
    .btn-main:hover { opacity: 0.9; transform: translateY(-1px); }
    .btn-secondary { background: var(--secondary-color); }
    .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 5px solid transparent; }
    .success { background: #dcfce7; color: #166534; border-color: var(--secondary-color); }
    .album-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 25px; }
    .album-card { background: var(--white); border-radius: 15px; overflow: hidden; border: 1px solid #e2e8f0; transition: 0.3s; position: relative; }
    .album-card:hover { transform: translateY(-8px); box-shadow: 0 15px 30px rgba(0,0,0,0.1); }
    .album-cover { height: 200px; background: #e2e8f0; position: relative; }
    .album-cover img { width: 100%; height: 100%; object-fit: cover; }
    .album-info { padding: 18px; text-align: center; }
    .album-name { font-weight: bold; font-size: 18px; color: var(--dark-gray); margin-bottom: 5px; }
    .album-date { font-size: 14px; color: #64748b; margin-bottom: 15px; }
    .album-actions { padding: 12px; border-top: 1px solid #f1f5f9; background: #fafafa; display: flex; justify-content: space-around; }
    .action-btn { font-size: 13px; text-decoration: none; display: flex; align-items: center; gap: 5px; font-weight: 500; }
    .edit-link { color: var(--primary-color); }
    .delete-link { color: var(--danger); }
    .image-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 15px; margin-top: 20px; }
    .image-item { position: relative; height: 160px; border-radius: 10px; overflow: hidden; border: 2px solid var(--white); box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
    .image-item img { width: 100%; height: 100%; object-fit: cover; }
    .image-delete { position: absolute; top: 8px; right: 8px; background: var(--danger); color: white; border: none; width: 25px; height: 25px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; font-size: 12px; }
    .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); z-index: 1000; align-items: center; justify-content: center; backdrop-filter: blur(4px); }
    .modal-content { background: white; padding: 30px; border-radius: 15px; width: 450px; position: relative; animation: slideIn 0.3s ease; }
    @keyframes slideIn { from { transform: translateY(-20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    .form-group { margin-bottom: 15px; }
    .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; }
    .form-control { width: 100%; padding: 12px; border: 1.5px solid #ddd; border-radius: 8px; font-size: 14px; }
    .form-control:focus { border-color: var(--primary-color); outline: none; }
</style>

<div class="gallery-admin">
    <?php echo $alert; ?>

    <?php if (!$current_album_id): ?>
        <div class="header-box">
            <h2 style="margin:0; color:var(--dark-gray);">📸 ফটো গ্যালারি (অ্যালবামসমূহ)</h2>
            <button onclick="document.getElementById('newAlbumModal').style.display='flex'" class="btn-main"><i class="fas fa-plus-circle"></i> নতুন অ্যালবাম</button>
        </div>

        <div class="album-grid">
            <?php while($row = mysqli_fetch_assoc($albums)): ?>
                <?php 
                    // এরর এড়াতে ভ্যালুগুলো নিরাপদ করা
                    $safe_name = addslashes($row['album_name'] ?? ""); 
                    $safe_desc = addslashes($row['album_desc'] ?? "");
                ?>
                <div class="album-card">
                    <a href="admin.php?view=gallery&album_id=<?php echo $row['id']; ?>" style="text-decoration:none;">
                        <div class="album-cover">
                            <?php if($row['cover_image']): ?>
                                <img src="<?php echo $row['cover_image']; ?>">
                            <?php else: ?>
                                <div style="display:flex; height:100%; align-items:center; justify-content:center; color:#cbd5e1;"><i class="fas fa-images fa-4x"></i></div>
                            <?php endif; ?>
                        </div>
                        <div class="album-info">
                            <div class="album-name"><?php echo $row['album_name']; ?></div>
                            <div class="album-date"><i class="far fa-calendar-alt"></i> <?php echo date('d M, Y', strtotime($row['album_date'])); ?></div>
                        </div>
                    </a>
                    <div class="album-actions">
                        <a href="javascript:void(0)" onclick="openEditModal(<?php echo $row['id']; ?>, '<?php echo $safe_name; ?>', '<?php echo $safe_desc; ?>', '<?php echo $row['album_date']; ?>')" class="action-btn edit-link">
                            <i class="fas fa-edit"></i> এডিট
                        </a>
                        <a href="admin.php?view=gallery&delete_album=<?php echo $row['id']; ?>" onclick="return confirm('পুরো অ্যালবাম এবং সব ছবি মুছে ফেলা হবে! নিশ্চিত তো?')" class="action-btn delete-link">
                            <i class="fas fa-trash"></i> ডিলিট
                        </a>
                    </div>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <div class="header-box">
            <div>
                <a href="admin.php?view=gallery" style="text-decoration:none; color:var(--primary-color); font-weight:bold; display:inline-flex; align-items:center; gap:5px;"><i class="fas fa-arrow-left"></i> সকল অ্যালবাম</a>
                <h2 style="margin:10px 0 5px 0;"><?php echo $current_album_details['album_name']; ?></h2>
                <p style="color:#64748b; margin:0 0 5px 0;"><i class="far fa-calendar-check"></i> <?php echo date('d F, Y', strtotime($current_album_details['album_date'])); ?></p>
                <?php if($current_album_details['album_desc']): ?>
                    <p style="color:#444; margin:0; font-size:14px; font-style:italic;"><strong>মন্তব্য:</strong> <?php echo $current_album_details['album_desc']; ?></p>
                <?php endif; ?>
            </div>
            <button onclick="document.getElementById('uploadModal').style.display='flex'" class="btn-main btn-secondary"><i class="fas fa-upload"></i> ছবি আপলোড</button>
        </div>

        <div class="image-grid">
            <?php while($img = mysqli_fetch_assoc($album_images)): ?>
                <div class="image-item">
                    <img src="<?php echo $img['image_path']; ?>" loading="lazy">
                    <a href="admin.php?view=gallery&delete_image=<?php echo $img['id']; ?>" class="image-delete" onclick="return confirm('এই ছবিটি মুছে ফেলবেন?')"><i class="fas fa-times"></i></a>
                </div>
            <?php endwhile; ?>
        </div>
    <?php endif; ?>
</div>

<!-- Modal structures -->
<div id="newAlbumModal" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0; border-bottom:2px solid var(--primary-color); padding-bottom:10px;">নতুন অ্যালবাম</h3>
        <form method="POST">
            <div class="form-group">
                <label>অনুষ্ঠানের নাম:</label>
                <input type="text" name="album_name" class="form-control" placeholder="যেমন: বার্ষিক ক্রীড়া ২০২৪" required>
            </div>
            <div class="form-group">
                <label>মন্তব্য:</label>
                <textarea name="album_desc" class="form-control" placeholder="অনুষ্ঠান সম্পর্কে কিছু লিখুন..." rows="3"></textarea>
            </div>
            <div class="form-group">
                <label>তারিখ:</label>
                <input type="date" name="album_date" class="form-control" required>
            </div>
            <div style="margin-top:25px; text-align:right; display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="this.closest('.modal').style.display='none'" style="padding:10px; border:none; background:#eee; border-radius:8px; cursor:pointer;">বাতিল</button>
                <button type="submit" name="create_album" class="btn-main">সংরক্ষণ করুন</button>
            </div>
        </form>
    </div>
</div>

<div id="editAlbumModal" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0; border-bottom:2px solid var(--secondary-color); padding-bottom:10px;">অ্যালবাম এডিট করুন</h3>
        <form method="POST">
            <input type="hidden" name="album_id" id="edit_album_id">
            <div class="form-group">
                <label>অনুষ্ঠানের নাম:</label>
                <input type="text" name="album_name" id="edit_album_name" class="form-control" required>
            </div>
            <div class="form-group">
                <label>মন্তব্য:</label>
                <textarea name="album_desc" id="edit_album_desc" class="form-control" rows="3"></textarea>
            </div>
            <div class="form-group">
                <label>তারিখ:</label>
                <input type="date" name="album_date" id="edit_album_date" class="form-control" required>
            </div>
            <div style="margin-top:25px; text-align:right; display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="this.closest('.modal').style.display='none'" style="padding:10px; border:none; background:#eee; border-radius:8px; cursor:pointer;">বাতিল</button>
                <button type="submit" name="update_album" class="btn-main btn-secondary">আপডেট করুন</button>
            </div>
        </form>
    </div>
</div>

<div id="uploadModal" class="modal">
    <div class="modal-content">
        <h3 style="margin-top:0; border-bottom:2px solid var(--secondary-color); padding-bottom:10px;">ছবি যোগ করুন</h3>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="album_id" value="<?php echo $current_album_id; ?>">
            <div class="form-group">
                <label>ছবি সিলেক্ট করুন (একাধিক):</label>
                <input type="file" name="images[]" multiple accept="image/*" class="form-control" required>
            </div>
            <div style="margin-top:25px; text-align:right; display:flex; justify-content:flex-end; gap:10px;">
                <button type="button" onclick="this.closest('.modal').style.display='none'" style="padding:10px; border:none; background:#eee; border-radius:8px; cursor:pointer;">বাতিল</button>
                <button type="submit" name="upload_images" class="btn-main btn-secondary">আপলোড শুরু</button>
            </div>
        </form>
    </div>
</div>

<script>
function openEditModal(id, name, desc, date) {
    document.getElementById('edit_album_id').value = id;
    document.getElementById('edit_album_name').value = name;
    document.getElementById('edit_album_desc').value = desc;
    document.getElementById('edit_album_date').value = date;
    document.getElementById('editAlbumModal').style.display = 'flex';
}
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}
</script>