<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php');
    exit();
}

// Handle image upload
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['upload_images'])) {
    $laptop_id = $_POST['laptop_id'];
    
    $upload_dir = '../assets/images/laptops/';
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    // Get current max sort order
    $stmt = $pdo->prepare("SELECT MAX(sort_order) as max_order FROM laptop_images WHERE laptop_id = ?");
    $stmt->execute([$laptop_id]);
    $max_order = $stmt->fetch()['max_order'] ?? 0;
    $sort_order = $max_order + 1;
    
    if (isset($_FILES['new_images']) && !empty($_FILES['new_images']['name'][0])) {
        foreach ($_FILES['new_images']['tmp_name'] as $key => $tmp_name) {
            if ($_FILES['new_images']['error'][$key] == 0) {
                $file = [
                    'name' => $_FILES['new_images']['name'][$key],
                    'tmp_name' => $tmp_name,
                    'type' => $_FILES['new_images']['type'][$key],
                    'error' => $_FILES['new_images']['error'][$key],
                    'size' => $_FILES['new_images']['size'][$key]
                ];
                
                $filename = $laptop_id . '_image_' . time() . '_' . $key . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
                $filepath = $upload_dir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    $image_url = 'assets/images/laptops/' . $filename;
                    
                    $stmt = $pdo->prepare("INSERT INTO laptop_images (laptop_id, image_url, is_primary, sort_order) VALUES (?, ?, 0, ?)");
                    $stmt->execute([$laptop_id, $image_url, $sort_order]);
                    $sort_order++;
                }
            }
        }
        $_SESSION['success'] = "Images uploaded successfully!";
    }
    
    header('Location: laptops.php');
    exit();
}

// Handle set primary image
if (isset($_GET['set_primary'])) {
    $image_id = $_GET['set_primary'];
    $laptop_id = $_GET['laptop_id'];
    
    try {
        $pdo->beginTransaction();
        
        // Remove primary flag from all images of this laptop
        $stmt = $pdo->prepare("UPDATE laptop_images SET is_primary = 0 WHERE laptop_id = ?");
        $stmt->execute([$laptop_id]);
        
        // Set new primary image
        $stmt = $pdo->prepare("UPDATE laptop_images SET is_primary = 1 WHERE id = ?");
        $stmt->execute([$image_id]);
        
        $pdo->commit();
        $_SESSION['success'] = "Primary image updated!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Error updating primary image";
    }
    
    header('Location: laptops.php');
    exit();
}

// Handle delete image
if (isset($_GET['delete_image'])) {
    $image_id = $_GET['delete_image'];
    
    try {
        // Get image path
        $stmt = $pdo->prepare("SELECT image_url FROM laptop_images WHERE id = ?");
        $stmt->execute([$image_id]);
        $image = $stmt->fetch();
        
        if ($image) {
            // Delete file
            $file_path = '../' . $image['image_url'];
            if (file_exists($file_path)) {
                unlink($file_path);
            }
            
            // Delete from database
            $stmt = $pdo->prepare("DELETE FROM laptop_images WHERE id = ?");
            $stmt->execute([$image_id]);
            
            $_SESSION['success'] = "Image deleted successfully!";
        }
    } catch (Exception $e) {
        $_SESSION['error'] = "Error deleting image";
    }
    
    header('Location: laptops.php');
    exit();
}

// Display manage images interface
if ($_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['id'])) {
    $laptop_id = $_GET['id'];
    
    $stmt = $pdo->prepare("SELECT brand, model FROM laptops WHERE id = ?");
    $stmt->execute([$laptop_id]);
    $laptop = $stmt->fetch();
    
    $stmt = $pdo->prepare("SELECT * FROM laptop_images WHERE laptop_id = ? ORDER BY is_primary DESC, sort_order");
    $stmt->execute([$laptop_id]);
    $images = $stmt->fetchAll();
    ?>
    
    <div class="modal-body">
        <h5><?php echo htmlspecialchars($laptop['brand'] . ' ' . $laptop['model']); ?> - Image Gallery</h5>
        
        <form action="manage_images.php" method="POST" enctype="multipart/form-data" class="mt-3">
            <input type="hidden" name="laptop_id" value="<?php echo $laptop_id; ?>">
            <input type="hidden" name="upload_images" value="1">
            
            <div class="mb-3">
                <label class="form-label">Add New Images</label>
                <input type="file" name="new_images[]" class="form-control" accept="image/*" multiple>
                <small class="text-muted">You can select multiple images to add to gallery</small>
            </div>
            
            <button type="submit" class="btn btn-primary btn-sm">Upload Images</button>
        </form>
        
        <hr>
        
        <h6>Current Images</h6>
        <div class="row mt-3">
            <?php foreach($images as $image): ?>
                <div class="col-md-3 mb-3">
                    <div class="card">
                        <img src="../<?php echo $image['image_url']; ?>" class="card-img-top" style="height: 150px; object-fit: cover;" alt="Laptop image">
                        <div class="card-body text-center p-2">
                            <?php if($image['is_primary']): ?>
                                <span class="badge bg-primary mb-2">Primary Image</span>
                            <?php else: ?>
                                <a href="manage_images.php?set_primary=<?php echo $image['id']; ?>&laptop_id=<?php echo $laptop_id; ?>" 
                                   class="btn btn-sm btn-outline-primary mb-1" 
                                   onclick="return confirm('Set this as primary image?')">
                                    Set as Primary
                                </a>
                            <?php endif; ?>
                            
                            <a href="manage_images.php?delete_image=<?php echo $image['id']; ?>" 
                               class="btn btn-sm btn-danger" 
                               onclick="return confirm('Delete this image?')">
                                Delete
                            </a>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            
            <?php if(empty($images)): ?>
                <div class="col-12">
                    <div class="alert alert-info">No images found. Upload some images for this laptop.</div>
                </div>
            <?php endif; ?>
        </div>
    </div>
    <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    </div>
    
    <?php
    exit();
}
?>