<?php
// admin/edit-banner.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

$id = intval($_GET['id'] ?? 0);
if (!$id) {
    header('Location: banners.php');
    exit;
}

// Get banner
$stmt = $pdo->prepare("SELECT * FROM banners WHERE id = ?");
$stmt->execute([$id]);
$banner = $stmt->fetch();

if (!$banner) {
    header('Location: banners.php');
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = sanitize($_POST['title'] ?? '');
    $description = sanitize($_POST['description'] ?? ''); // Add this
    $link = sanitize($_POST['link'] ?? '');
    $order = intval($_POST['order'] ?? 0);
    $status = isset($_POST['status']) ? 1 : 0;
    
    // Handle image upload
    $image = $banner['image'];
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/../assets/images/banners/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        // Validate image
        $allowed_types = ['image/jpeg', 'image/png', 'image/webp', 'image/gif', 'image/avif'];
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime_type = finfo_file($finfo, $_FILES['image']['tmp_name']);
        finfo_close($finfo);
        
        if (!in_array($mime_type, $allowed_types)) {
            $error = 'Only JPG, PNG, WEBP, GIF, and AVIF images are allowed';
        } else {
            $ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            $new_image = time() . '_' . uniqid() . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], $upload_dir . $new_image);
            
            // Delete old image
            if ($banner['image'] && file_exists($upload_dir . $banner['image'])) {
                unlink($upload_dir . $banner['image']);
            }
            $image = $new_image;
        }
    }
    
    if (empty($error)) {
        $stmt = $pdo->prepare("UPDATE banners SET title = ?, description = ?, image = ?, link = ?, `order` = ?, status = ? WHERE id = ?");
        $stmt->execute([$title, $description, $image, $link, $order, $status, $id]);
        $_SESSION['success_msg'] = 'Banner updated successfully!';
        header('Location: banners.php');
        exit;
    }
}

include 'header.php';
?>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-edit me-2"></i> Edit Banner</h2>
        <a href="banners.php" class="btn btn-secondary">
            <i class="fa-solid fa-arrow-left"></i> Back to Banners
        </a>
    </div>
    
    <?php if ($error): ?>
    <div class="alert alert-danger"><?php echo $error; ?></div>
    <?php endif; ?>
    
    <div class="admin-card">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Title</label>
                        <input type="text" name="title" class="form-control" value="<?php echo $banner['title']; ?>">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea name="description" class="form-control" rows="3"><?php echo $banner['description']; ?></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Link URL</label>
                        <input type="text" name="link" class="form-control" value="<?php echo $banner['link']; ?>">
                        <small class="text-muted">Leave empty for no link</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Order</label>
                        <input type="number" name="order" class="form-control" value="<?php echo $banner['order']; ?>">
                        <small class="text-muted">Lower number = higher priority</small>
                    </div>
                    
                    <div class="mb-3">
                        <div class="form-check">
                            <input type="checkbox" name="status" class="form-check-input" id="status" <?php echo $banner['status'] ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="status">Active</label>
                        </div>
                    </div>
                </div>
                
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Banner Image</label>
                        <?php if ($banner['image']): ?>
                        <div class="mb-2">
                            <img src="../assets/images/banners/<?php echo $banner['image']; ?>" 
                                 alt="<?php echo $banner['title']; ?>" 
                                 style="max-width:100%; max-height:200px; border-radius:8px; border:1px solid #e2e8f0;">
                        </div>
                        <?php endif; ?>
                        <input type="file" name="image" class="form-control" accept="image/*">
                        <small class="text-muted">Leave empty to keep current image</small>
                        <div id="imagePreview" class="mt-2"></div>
                    </div>
                </div>
            </div>
            
            <div class="mt-3">
                <button type="submit" class="btn btn-primary">
                    <i class="fa-solid fa-save"></i> Update Banner
                </button>
                <a href="banners.php" class="btn btn-secondary">Cancel</a>
            </div>
        </form>
    </div>
</div>

<script>
// Image preview
document.querySelector('input[name="image"]').addEventListener('change', function(e) {
    const preview = document.getElementById('imagePreview');
    const file = e.target.files[0];
    
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            preview.innerHTML = `<img src="${e.target.result}" style="max-width:100%; max-height:200px; border-radius:8px; border:1px solid #e2e8f0;">`;
        };
        reader.readAsDataURL(file);
    } else {
        preview.innerHTML = '';
    }
});
</script>

<?php include 'footer.php'; ?>