<?php
$db = getDB();
$message = '';
$tab = $_GET['tab'] ?? 'categories';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCsrfToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_category') {
        $id = (int)($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $slug = makeSlug($name);
        $description = trim($_POST['description'] ?? '');
        $coverImage = trim($_POST['cover_image'] ?? '');
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $active = isset($_POST['active']) ? true : false;
        
        if ($name) {
            try {
                if ($id) {
                    $stmt = $db->prepare("UPDATE gallery_categories SET name=?, slug=?, description=?, cover_image=?, sort_order=?, active=? WHERE id=?");
                    $stmt->execute([$name, $slug, $description, $coverImage, $sortOrder, $active, $id]);
                    $message = 'Category updated successfully.';
                    logAudit('update', 'gallery_categories', $id, "Updated gallery category: $name");
                } else {
                    $stmt = $db->prepare("INSERT INTO gallery_categories (name, slug, description, cover_image, sort_order, active) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$name, $slug, $description, $coverImage, $sortOrder, $active]);
                    $message = 'Category added successfully.';
                    logAudit('create', 'gallery_categories', null, "Added gallery category: $name");
                }
            } catch (PDOException $e) {
                if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                    $message = 'Error: A gallery category with that name already exists.';
                } else {
                    $message = 'Database error: ' . htmlspecialchars($e->getMessage());
                }
            }
        }
        $tab = 'categories';
    }
    
    if ($action === 'save_image') {
        $id = (int)($_POST['id'] ?? 0);
        $categoryId = (int)($_POST['category_id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $imageUrl = trim($_POST['image_url'] ?? '');
        $sortOrder = (int)($_POST['sort_order'] ?? 0);
        $active = isset($_POST['active']) ? true : false;
        
        if ($title && $imageUrl && $categoryId) {
            try {
                if ($id) {
                    $stmt = $db->prepare("UPDATE gallery_images SET category_id=?, title=?, description=?, image_url=?, sort_order=?, active=? WHERE id=?");
                    $stmt->execute([$categoryId, $title, $description, $imageUrl, $sortOrder, $active, $id]);
                    $message = 'Image updated successfully.';
                    logAudit('update', 'gallery_images', $id, "Updated gallery image: $title");
                } else {
                    $stmt = $db->prepare("INSERT INTO gallery_images (category_id, title, description, image_url, sort_order, active) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$categoryId, $title, $description, $imageUrl, $sortOrder, $active]);
                    $message = 'Image added successfully.';
                    logAudit('create', 'gallery_images', null, "Added gallery image: $title");
                }
            } catch (PDOException $e) {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
        $tab = 'images';
    }
    
    if ($action === 'delete_category') {
        $delId = (int)($_POST['delete_id'] ?? 0);
        if ($delId) {
            $db->prepare("DELETE FROM gallery_categories WHERE id = ?")->execute([$delId]);
            $message = 'Category and all its images deleted.';
            logAudit('delete', 'gallery_categories', $delId, "Deleted gallery category #$delId");
        }
        $tab = 'categories';
    }
    
    if ($action === 'bulk_upload') {
        $categoryId = (int)($_POST['bulk_category_id'] ?? 0);
        if ($categoryId && !empty($_FILES['bulk_images']['name'][0])) {
            $uploadDir = __DIR__ . '/../../public/uploads/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            $allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
            $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'];
            $maxSize = 5 * 1024 * 1024;
            $uploaded = 0;
            $failed = 0;
            $fileCount = count($_FILES['bulk_images']['name']);
            
            $maxSort = $db->prepare("SELECT COALESCE(MAX(sort_order), 0) as max_sort FROM gallery_images WHERE category_id = ?");
            $maxSort->execute([$categoryId]);
            $sortStart = (int)$maxSort->fetch()['max_sort'] + 1;
            
            for ($i = 0; $i < $fileCount; $i++) {
                if ($_FILES['bulk_images']['error'][$i] !== UPLOAD_ERR_OK) {
                    $failed++;
                    continue;
                }
                $tmpName = $_FILES['bulk_images']['tmp_name'][$i];
                $origName = $_FILES['bulk_images']['name'][$i];
                $fileSize = $_FILES['bulk_images']['size'][$i];
                $mimeType = mime_content_type($tmpName);
                $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
                
                if (!in_array($mimeType, $allowedMimes) || !in_array($ext, $allowedExts)) {
                    $failed++;
                    continue;
                }
                if ($fileSize > $maxSize) {
                    $failed++;
                    continue;
                }
                
                $newFilename = bin2hex(random_bytes(12)) . '.' . $ext;
                $destPath = $uploadDir . $newFilename;
                
                if (move_uploaded_file($tmpName, $destPath)) {
                    $imageUrl = '/uploads/' . $newFilename;
                    $title = pathinfo($origName, PATHINFO_FILENAME);
                    $title = str_replace(['-', '_'], ' ', $title);
                    $title = ucwords($title);
                    
                    $stmt = $db->prepare("INSERT INTO gallery_images (category_id, title, image_url, sort_order, active) VALUES (?, ?, ?, ?, TRUE)");
                    $stmt->execute([$categoryId, $title, $imageUrl, $sortStart + $i]);
                    $uploaded++;
                } else {
                    $failed++;
                }
            }
            
            $message = "$uploaded image(s) uploaded successfully.";
            if ($failed > 0) {
                $message .= " $failed file(s) failed (invalid type, too large, or error).";
            }
            logAudit('create', 'gallery_images', null, "Bulk uploaded $uploaded images to category #$categoryId");
        } else {
            $message = 'Please select a category and at least one image file.';
        }
        $tab = 'images';
    }
    
    if ($action === 'delete_image') {
        $delId = (int)($_POST['delete_id'] ?? 0);
        if ($delId) {
            $db->prepare("DELETE FROM gallery_images WHERE id = ?")->execute([$delId]);
            $message = 'Image deleted.';
            logAudit('delete', 'gallery_images', $delId, "Deleted gallery image #$delId");
        }
        $tab = 'images';
    }
}

$categories = $db->query("SELECT * FROM gallery_categories ORDER BY sort_order ASC")->fetchAll();
$allImages = $db->query("SELECT gi.*, gc.name as category_name FROM gallery_images gi LEFT JOIN gallery_categories gc ON gi.category_id = gc.id ORDER BY gi.sort_order ASC")->fetchAll();

$editCategory = null;
$editImage = null;
if (isset($_GET['edit_cat'])) {
    $stmt = $db->prepare("SELECT * FROM gallery_categories WHERE id = ?");
    $stmt->execute([$_GET['edit_cat']]);
    $editCategory = $stmt->fetch();
    $tab = 'categories';
}
if (isset($_GET['edit_img'])) {
    $stmt = $db->prepare("SELECT * FROM gallery_images WHERE id = ?");
    $stmt->execute([$_GET['edit_img']]);
    $editImage = $stmt->fetch();
    $tab = 'images';
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2><i class="fas fa-images"></i> Gallery Management</h2>
    <a href="/gallery" target="_blank"><i class="fas fa-external-link-alt"></i> View Gallery</a>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div style="display:flex; gap:10px; margin-bottom:20px;">
    <a href="/admin/gallery?tab=categories" class="btn-sm <?= $tab === 'categories' ? 'btn-sm-primary' : '' ?>" style="<?= $tab !== 'categories' ? 'border:2px solid #0d6efd;color:#0d6efd;background:#fff;' : '' ?>"><i class="fas fa-folder"></i> Categories (<?= count($categories) ?>)</a>
    <a href="/admin/gallery?tab=images" class="btn-sm <?= $tab === 'images' ? 'btn-sm-primary' : '' ?>" style="<?= $tab !== 'images' ? 'border:2px solid #0d6efd;color:#0d6efd;background:#fff;' : '' ?>"><i class="fas fa-image"></i> Images (<?= count($allImages) ?>)</a>
</div>

<?php if ($tab === 'categories'): ?>

<div style="display:grid; grid-template-columns: 1fr 1fr; gap:25px;">
    <div class="admin-card">
        <h3><i class="fas fa-<?= $editCategory ? 'edit' : 'plus-circle' ?>"></i> <?= $editCategory ? 'Edit Category' : 'Add New Category' ?></h3>
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="save_category">
            <?php if ($editCategory): ?>
            <input type="hidden" name="id" value="<?= $editCategory['id'] ?>">
            <?php endif; ?>
            
            <div class="form-group">
                <label>Category Name *</label>
                <input type="text" name="name" value="<?= htmlspecialchars($editCategory['name'] ?? '') ?>" required placeholder="e.g. Laboratory Equipment">
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" rows="3" placeholder="Brief description of this category"><?= htmlspecialchars($editCategory['description'] ?? '') ?></textarea>
            </div>
            <div class="form-group">
                <label>Cover Image URL</label>
                <input type="text" name="cover_image" id="cover_image_url" value="<?= htmlspecialchars($editCategory['cover_image'] ?? '') ?>" placeholder="https://...">
                <div style="margin-top:8px; display:flex; gap:8px; align-items:center;">
                    <input type="file" id="file_upload_cover" accept="image/*" style="font-size:13px;">
                    <button type="button" onclick="uploadFile('file_upload_cover', 'cover_image')" class="btn-sm btn-sm-success"><i class="fas fa-upload"></i> Upload</button>
                    <span id="upload_status_file_upload_cover" style="font-size:12px;color:#666;"></span>
                </div>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px;">
                <div class="form-group">
                    <label>Sort Order</label>
                    <input type="number" name="sort_order" value="<?= $editCategory['sort_order'] ?? 0 ?>">
                </div>
                <div class="form-group" style="display:flex; align-items:flex-end; padding-bottom:10px;">
                    <label style="margin-bottom:0;"><input type="checkbox" name="active" <?= ($editCategory['active'] ?? true) ? 'checked' : '' ?>> Active</label>
                </div>
            </div>
            <div style="display:flex; gap:10px;">
                <button type="submit" class="btn-sm btn-sm-primary"><i class="fas fa-save"></i> <?= $editCategory ? 'Update Category' : 'Add Category' ?></button>
                <?php if ($editCategory): ?>
                <a href="/admin/gallery?tab=categories" class="btn-sm btn-sm-danger"><i class="fas fa-times"></i> Cancel</a>
                <?php endif; ?>
            </div>
        </form>
    </div>
    
    <div class="admin-card">
        <h3><i class="fas fa-list"></i> Gallery Categories</h3>
        <?php if (empty($categories)): ?>
        <p style="color:#888; text-align:center; padding:30px;">No categories yet. Add your first category.</p>
        <?php else: ?>
        <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Cover</th>
                    <th>Name</th>
                    <th>Order</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($categories as $cat): ?>
                <tr>
                    <td><?php if ($cat['cover_image']): ?><img src="<?= htmlspecialchars($cat['cover_image']) ?>" class="admin-img-preview"><?php else: ?><span style="color:#ccc;"><i class="fas fa-image"></i></span><?php endif; ?></td>
                    <td><strong><?= htmlspecialchars($cat['name']) ?></strong><br><small style="color:#888;">/gallery/<?= htmlspecialchars($cat['slug']) ?></small></td>
                    <td><?= $cat['sort_order'] ?></td>
                    <td><span style="padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;background:<?= $cat['active'] ? '#d4edda' : '#f8d7da' ?>;color:<?= $cat['active'] ? '#155724' : '#842029' ?>;"><?= $cat['active'] ? 'Active' : 'Inactive' ?></span></td>
                    <td>
                        <div class="actions">
                            <a href="/admin/gallery?edit_cat=<?= $cat['id'] ?>" class="btn-sm btn-sm-primary" title="Edit"><i class="fas fa-edit"></i></a>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this category and all its images?')">
                                <?= csrfField() ?>
                                <input type="hidden" name="action" value="delete_category">
                                <input type="hidden" name="delete_id" value="<?= $cat['id'] ?>">
                                <button type="submit" class="btn-sm btn-sm-danger" title="Delete"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php else: ?>

<div class="admin-card" style="margin-bottom:25px;">
    <h3><i class="fas fa-cloud-upload-alt"></i> Bulk Upload Images</h3>
    <p style="color:#666; font-size:14px; margin-bottom:15px;">Select multiple images from your computer to upload them all at once to a category.</p>
    <?php if (empty($categories)): ?>
    <div class="alert alert-error"><i class="fas fa-exclamation-triangle"></i> Please <a href="/admin/gallery?tab=categories">create a category</a> first before uploading images.</div>
    <?php else: ?>
    <form method="POST" enctype="multipart/form-data" id="bulkUploadForm">
        <?= csrfField() ?>
        <input type="hidden" name="action" value="bulk_upload">
        <div style="display:grid; grid-template-columns: 1fr 2fr auto; gap:15px; align-items:end;">
            <div class="form-group" style="margin-bottom:0;">
                <label>Select Category *</label>
                <select name="bulk_category_id" required>
                    <option value="">-- Choose Category --</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group" style="margin-bottom:0;">
                <label>Browse Images * <small style="color:#888;">(JPG, PNG, GIF, WebP - Max 5MB each)</small></label>
                <input type="file" name="bulk_images[]" id="bulk_images_input" multiple accept="image/jpeg,image/png,image/gif,image/webp" required style="font-size:13px; padding:8px;">
            </div>
            <div style="padding-bottom:2px;">
                <button type="submit" class="btn-sm btn-sm-success" id="bulkUploadBtn" style="padding:10px 20px;"><i class="fas fa-upload"></i> Upload All</button>
            </div>
        </div>
        <div id="bulk_preview" style="display:none; margin-top:15px; padding:15px; background:#f8f9fa; border-radius:10px; border:1px solid #e9ecef;">
            <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px;">
                <strong style="font-size:14px;"><i class="fas fa-images"></i> <span id="bulk_count">0</span> image(s) selected</strong>
                <button type="button" onclick="clearBulkSelection()" class="btn-sm btn-sm-danger" style="font-size:11px; padding:4px 10px;"><i class="fas fa-times"></i> Clear</button>
            </div>
            <div id="bulk_thumbs" style="display:flex; flex-wrap:wrap; gap:10px;"></div>
        </div>
    </form>
    <script>
    document.getElementById('bulk_images_input').addEventListener('change', function() {
        var preview = document.getElementById('bulk_preview');
        var thumbs = document.getElementById('bulk_thumbs');
        var count = document.getElementById('bulk_count');
        thumbs.innerHTML = '';
        
        if (this.files.length > 0) {
            preview.style.display = 'block';
            count.textContent = this.files.length;
            
            for (var i = 0; i < this.files.length; i++) {
                var file = this.files[i];
                var reader = new FileReader();
                (function(f) {
                    reader.onload = function(e) {
                        var div = document.createElement('div');
                        div.style.cssText = 'position:relative; width:100px; height:75px; border-radius:8px; overflow:hidden; box-shadow:0 2px 8px rgba(0,0,0,0.1);';
                        div.innerHTML = '<img src="' + e.target.result + '" style="width:100%;height:100%;object-fit:cover;">' +
                            '<div style="position:absolute;bottom:0;left:0;right:0;padding:3px 5px;background:rgba(0,0,0,0.6);color:#fff;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + f.name + '</div>';
                        thumbs.appendChild(div);
                    };
                })(file);
                reader.readAsDataURL(file);
            }
        } else {
            preview.style.display = 'none';
        }
    });
    
    function clearBulkSelection() {
        document.getElementById('bulk_images_input').value = '';
        document.getElementById('bulk_preview').style.display = 'none';
        document.getElementById('bulk_thumbs').innerHTML = '';
    }
    
    document.getElementById('bulkUploadForm').addEventListener('submit', function() {
        var btn = document.getElementById('bulkUploadBtn');
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
    });
    </script>
    <?php endif; ?>
</div>

<div style="display:grid; grid-template-columns: 1fr 1fr; gap:25px;">
    <div class="admin-card">
        <h3><i class="fas fa-<?= $editImage ? 'edit' : 'plus-circle' ?>"></i> <?= $editImage ? 'Edit Image' : 'Add Single Image' ?></h3>
        <?php if (empty($categories)): ?>
        <div class="alert alert-error"><i class="fas fa-exclamation-triangle"></i> Please <a href="/admin/gallery?tab=categories">create a category</a> first before adding images.</div>
        <?php else: ?>
        <form method="POST">
            <?= csrfField() ?>
            <input type="hidden" name="action" value="save_image">
            <?php if ($editImage): ?>
            <input type="hidden" name="id" value="<?= $editImage['id'] ?>">
            <?php endif; ?>
            
            <div class="form-group">
                <label>Category *</label>
                <select name="category_id" required>
                    <option value="">-- Select Category --</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= ($editImage['category_id'] ?? '') == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Image Title *</label>
                <input type="text" name="title" value="<?= htmlspecialchars($editImage['title'] ?? '') ?>" required placeholder="e.g. PCR Machine Setup">
            </div>
            <div class="form-group">
                <label>Description</label>
                <textarea name="description" rows="3" placeholder="Brief description of the image"><?= htmlspecialchars($editImage['description'] ?? '') ?></textarea>
            </div>
            <div class="form-group">
                <label>Image URL *</label>
                <input type="text" name="image_url" id="gallery_image_url" value="<?= htmlspecialchars($editImage['image_url'] ?? '') ?>" required placeholder="https://...">
                <div style="margin-top:8px; display:flex; gap:8px; align-items:center;">
                    <input type="file" id="file_upload_gallery" accept="image/*" style="font-size:13px;">
                    <button type="button" onclick="uploadFile('file_upload_gallery', 'image_url')" class="btn-sm btn-sm-success"><i class="fas fa-upload"></i> Upload</button>
                    <span id="upload_status_file_upload_gallery" style="font-size:12px;color:#666;"></span>
                </div>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:15px;">
                <div class="form-group">
                    <label>Sort Order</label>
                    <input type="number" name="sort_order" value="<?= $editImage['sort_order'] ?? 0 ?>">
                </div>
                <div class="form-group" style="display:flex; align-items:flex-end; padding-bottom:10px;">
                    <label style="margin-bottom:0;"><input type="checkbox" name="active" <?= ($editImage['active'] ?? true) ? 'checked' : '' ?>> Active</label>
                </div>
            </div>
            <div style="display:flex; gap:10px;">
                <button type="submit" class="btn-sm btn-sm-primary"><i class="fas fa-save"></i> <?= $editImage ? 'Update Image' : 'Add Image' ?></button>
                <?php if ($editImage): ?>
                <a href="/admin/gallery?tab=images" class="btn-sm btn-sm-danger"><i class="fas fa-times"></i> Cancel</a>
                <?php endif; ?>
            </div>
        </form>
        <?php endif; ?>
    </div>
    
    <div class="admin-card">
        <h3><i class="fas fa-th"></i> Gallery Images</h3>
        <?php if (empty($allImages)): ?>
        <p style="color:#888; text-align:center; padding:30px;">No images yet. Add your first image.</p>
        <?php else: ?>
        <div style="overflow-x:auto;">
        <table>
            <thead>
                <tr>
                    <th>Preview</th>
                    <th>Title</th>
                    <th>Category</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($allImages as $img): ?>
                <tr>
                    <td><img src="<?= htmlspecialchars($img['image_url']) ?>" class="admin-img-preview" style="width:80px;height:55px;"></td>
                    <td><strong><?= htmlspecialchars($img['title']) ?></strong><br><small style="color:#888;"><?= date('M d, Y', strtotime($img['created_at'])) ?></small></td>
                    <td><span style="padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;background:#e3f2fd;color:#1565c0;"><?= htmlspecialchars($img['category_name'] ?? 'N/A') ?></span></td>
                    <td>
                        <div class="actions">
                            <a href="/admin/gallery?edit_img=<?= $img['id'] ?>" class="btn-sm btn-sm-primary" title="Edit"><i class="fas fa-edit"></i></a>
                            <form method="POST" style="display:inline;" onsubmit="return confirm('Delete this image?')">
                                <?= csrfField() ?>
                                <input type="hidden" name="action" value="delete_image">
                                <input type="hidden" name="delete_id" value="<?= $img['id'] ?>">
                                <button type="submit" class="btn-sm btn-sm-danger" title="Delete"><i class="fas fa-trash"></i></button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php endif; ?>

<?php include __DIR__ . '/admin_footer.php'; ?>
