<?php
$pageTitle = 'Upload Photos';
require_once dirname(__DIR__) . '/includes/header.php';

$errors = []; $uploaded = 0;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category = trim($_POST['category'] ?? 'general');
    $title    = trim($_POST['title'] ?? '');
    $sort     = (int)($_POST['sort_order'] ?? 0);

    // Handle multiple file uploads
    $files = $_FILES['photos'] ?? [];
    if (!empty($files['name'][0])) {
        foreach ($files['name'] as $i => $fname) {
            if ($files['error'][$i] !== 0) continue;
            $tmp = $files['tmp_name'][$i];
            $ext = strtolower(pathinfo($fname, PATHINFO_EXTENSION));
            if (!in_array($ext, ['jpg','jpeg','png','gif','webp'])) { $errors[] = "$fname: not an image"; continue; }
            $dir = SITE_ROOT.'/assets/uploads/gallery/';
            if (!is_dir($dir)) mkdir($dir, 0755, true);
            $newname = 'gal_'.uniqid().'.'.$ext;
            if (move_uploaded_file($tmp, $dir.$newname)) {
                $imgPath = 'assets/uploads/gallery/'.$newname;
                $t = $title ?: pathinfo($fname, PATHINFO_FILENAME);
                $st = db()->prepare("INSERT INTO gallery (title,image,category,sort_order) VALUES (?,?,?,?)");
                $st->bind_param('sssi', $t, $imgPath, $category, $sort);
                $st->execute();
                $uploaded++;
            }
        }
    }
    // Single URL
    $url = trim($_POST['image_url'] ?? '');
    if ($url) {
        $t = $title ?: 'Photo';
        $st = db()->prepare("INSERT INTO gallery (title,image,category,sort_order) VALUES (?,?,?,?)");
        $st->bind_param('sssi', $t, $url, $category, $sort);
        $st->execute();
        $uploaded++;
    }
    if ($uploaded > 0) {
        flash("$uploaded photo(s) uploaded successfully!", 'success');
        redirect(ADMIN_URL.'/pages/gallery.php');
    } elseif (empty($errors)) {
        $errors[] = 'Please select at least one image or enter an image URL.';
    }
}
?>
<div class="page-header">
    <a href="gallery.php" class="btn btn-secondary btn-sm"><i class="fas fa-arrow-left"></i></a>
    <h1>Upload Photos</h1>
</div>
<div class="card">
    <div class="card-header"><i class="fas fa-upload" style="color:var(--brand)"></i><h2>Upload to Gallery</h2></div>
    <div class="card-body">
        <?php foreach($errors as $e): ?><div class="flash flash-error"><i class="fas fa-exclamation-circle"></i><?=e($e)?></div><?php endforeach; ?>
        <form method="POST" enctype="multipart/form-data">
            <!-- Drop zone -->
            <div id="dropZone" style="border:2px dashed var(--border);border-radius:12px;padding:48px;text-align:center;cursor:pointer;margin-bottom:20px;transition:all .2s;background:#fafafa"
                onclick="document.getElementById('photoInput').click()"
                ondragover="this.style.borderColor='var(--brand)';this.style.background='#eff6ff';event.preventDefault()"
                ondragleave="this.style.borderColor='var(--border)';this.style.background='#fafafa'"
                ondrop="handleDrop(event)">
                <i class="fas fa-cloud-upload-alt" style="font-size:40px;color:var(--muted);opacity:.5;display:block;margin-bottom:12px"></i>
                <p style="font-weight:600;color:var(--text)">Click to browse or drag & drop images here</p>
                <p style="font-size:13px;color:var(--muted);margin-top:4px">Supports JPG, PNG, GIF, WebP — multiple files allowed</p>
                <input type="file" id="photoInput" name="photos[]" multiple accept="image/*" style="display:none" onchange="previewFiles(this.files)">
            </div>
            <!-- Preview -->
            <div id="previewGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(100px,1fr));gap:10px;margin-bottom:20px"></div>
            <!-- OR URL -->
            <div style="text-align:center;margin-bottom:16px;color:var(--muted);font-size:13px;position:relative">
                <span style="background:#fff;padding:0 12px;position:relative;z-index:1">or enter image URL</span>
                <div style="position:absolute;top:50%;left:0;right:0;height:1px;background:var(--border);z-index:0"></div>
            </div>
            <div class="form-group">
                <input type="url" name="image_url" class="form-control" placeholder="https://example.com/photo.jpg">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label class="form-label">Title / Caption</label>
                    <input type="text" name="title" class="form-control" placeholder="Leave blank to use filename">
                </div>
                <div class="form-group">
                    <label class="form-label">Category</label>
                    <input type="text" name="category" class="form-control" placeholder="e.g. office, events, students" value="general">
                </div>
            </div>
            <div class="form-group" style="max-width:200px">
                <label class="form-label">Sort Order</label>
                <input type="number" name="sort_order" class="form-control" value="0" min="0">
            </div>
            <div style="display:flex;gap:10px">
                <button type="submit" class="btn btn-primary"><i class="fas fa-upload"></i> Upload Photos</button>
                <a href="gallery.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>
<script>
function previewFiles(files) {
    const grid = document.getElementById('previewGrid');
    grid.innerHTML = '';
    Array.from(files).forEach(f => {
        if (!f.type.startsWith('image/')) return;
        const r = new FileReader();
        r.onload = e => {
            const d = document.createElement('div');
            d.style.cssText = 'aspect-ratio:1;border-radius:8px;overflow:hidden;border:1px solid var(--border)';
            d.innerHTML = `<img src="${e.target.result}" style="width:100%;height:100%;object-fit:cover">`;
            grid.appendChild(d);
        };
        r.readAsDataURL(f);
    });
}
function handleDrop(e) {
    e.preventDefault();
    const dz = document.getElementById('dropZone');
    dz.style.borderColor = 'var(--border)';
    dz.style.background = '#fafafa';
    const inp = document.getElementById('photoInput');
    const dt = new DataTransfer();
    Array.from(e.dataTransfer.files).forEach(f => dt.items.add(f));
    inp.files = dt.files;
    previewFiles(inp.files);
}
</script>
<?php require_once dirname(__DIR__) . '/includes/footer.php'; ?>
