Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm/pcib.in/admin/sliders.php

<?php
require_once "../config/database.php";
// If needed, check for the includes files and include them if they exist
if (file_exists("../includes/functions.php")) {
require_once "../includes/functions.php";
}
if (file_exists("../includes/session.php")) {
require_once "../includes/session.php";
} else {
    session_start();
}

// Check if admin is logged in
if (!isset($_SESSION['admin_id']) && !isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Handle success and error messages
$success_message = isset($_GET['success']) ? $_GET['success'] : null;
$error = isset($error) ? $error : null;

// Process form submissions
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Add or update slider
    if (isset($_POST['action']) && ($_POST['action'] == 'add' || $_POST['action'] == 'update')) {
        $id = isset($_POST['id']) ? $_POST['id'] : null;
        $title = trim($_POST['title']);
        $subtitle = trim($_POST['subtitle']);
        $description = trim($_POST['description']);
        $button_text = trim($_POST['button_text']);
        $button_url = trim($_POST['button_url']);
        $content_type = $_POST['content_type'];
        $overlay_color = trim($_POST['overlay_color']);
        $text_color = trim($_POST['text_color']);
        $animation = trim($_POST['animation']);
        $status = $_POST['status'];
        $sort_order = (int)$_POST['sort_order'];
        
        // Validate required fields
        if (empty($title)) {
            $error = "Title is required";
        } else {
            // Handle file upload for image/video
            $media_url = '';
            $upload_success = false;
            
            // If editing and no new file uploaded, keep existing media
            if ($_POST['action'] == 'update' && empty($_FILES['media_file']['name'])) {
                $media_url = $_POST['existing_media'];
                $upload_success = true;
            } else if (!empty($_FILES['media_file']['name'])) {
                // Check file type
                $allowed_types = $content_type == 'video' 
                    ? ['video/mp4', 'video/webm', 'video/ogg'] 
                    : ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                
                $file_type = $_FILES['media_file']['type'];
                $file_size = $_FILES['media_file']['size'];
                $tmp_name = $_FILES['media_file']['tmp_name'];
                
                if (!in_array($file_type, $allowed_types)) {
                    $error = "Invalid file type. Please upload " . ($content_type == 'video' ? "MP4, WebM, or OGG video" : "JPEG, PNG, GIF, or WebP image");
                } else if ($file_size > 100000000) { // 15MB max
                    $error = "File is too large. Maximum size is 15MB.";
                } else {
                    // Create directory if it doesn't exist
                    $upload_dir = "../assets/img/slider/";
                    if (!is_dir($upload_dir)) {
                        if (!mkdir($upload_dir, 0755, true)) {
                            $error = "Failed to create upload directory. Please check permissions.";
                        }
                    }
                    
                    if (!isset($error)) {
                    // Generate unique filename
                    $file_ext = pathinfo($_FILES['media_file']['name'], PATHINFO_EXTENSION);
                    $filename = 'slider_' . time() . '_' . mt_rand(1000, 9999) . '.' . $file_ext;
                    $destination = $upload_dir . $filename;
                    
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $media_url = 'assets/img/slider/' . $filename;
                        $upload_success = true;
                    } else {
                            $error = "Failed to upload file. Please check file permissions.";
                        }
                    }
                }
            } else {
                $error = "Please upload a " . ($content_type == 'video' ? "video" : "image") . " file.";
            }
            
            if ($upload_success) {
                // Prepare SQL statement
                if ($_POST['action'] == 'add') {
                    $sql = "INSERT INTO sliders (title, subtitle, description, button_text, button_url, content_type, media_url, overlay_color, text_color, animation, status, sort_order, date_created) 
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("sssssssssssi", 
                        $title, $subtitle, $description, $button_text, $button_url, 
                        $content_type, $media_url, $overlay_color, $text_color, 
                        $animation, $status, $sort_order);
                } else {
                    $sql = "UPDATE sliders SET 
                            title = ?, subtitle = ?, description = ?, 
                            button_text = ?, button_url = ?, content_type = ?, 
                            media_url = ?, overlay_color = ?, text_color = ?, 
                            animation = ?, status = ?, sort_order = ?, 
                            date_updated = NOW() 
                            WHERE id = ?";
                    $stmt = $conn->prepare($sql);
                    $stmt->bind_param("sssssssssssii", 
                        $title, $subtitle, $description, $button_text, $button_url, 
                        $content_type, $media_url, $overlay_color, $text_color, 
                        $animation, $status, $sort_order, $id);
                }
                
                if ($stmt->execute()) {
                    $success_message = $_POST['action'] == 'add' ? "Slider added successfully!" : "Slider updated successfully!";
                    // Redirect to prevent form resubmission
                    header("Location: sliders.php?success=" . urlencode($success_message));
                    exit();
                } else {
                    $error = "Database error: " . $conn->error;
                }
                
                $stmt->close();
            }
        }
    }
    
    // Delete slider
    if (isset($_POST['action']) && $_POST['action'] == 'delete' && isset($_POST['id'])) {
        $id = (int)$_POST['id'];
        
        // Get media URL before deleting
        $sql = "SELECT media_url FROM sliders WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $media_url = $row['media_url'];
            
            // Delete the record
            $sql = "DELETE FROM sliders WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $id);
            
            if ($stmt->execute()) {
                // Delete the file if it exists
                $file_path = "../" . $media_url;
                if (file_exists($file_path)) {
                    unlink($file_path);
                }
                
                $success_message = "Slider deleted successfully!";
                header("Location: sliders.php?success=" . urlencode($success_message));
                exit();
            } else {
                $error = "Failed to delete slider: " . $conn->error;
            }
        } else {
            $error = "Slider not found.";
        }
        
        $stmt->close();
    }
    
    // Update slider order
    if (isset($_POST['action']) && $_POST['action'] == 'update_order' && isset($_POST['order'])) {
        $order = json_decode($_POST['order'], true);
        
        if (is_array($order) && !empty($order)) {
            $success = true;
            
            foreach ($order as $position => $id) {
                $sql = "UPDATE sliders SET sort_order = ? WHERE id = ?";
                $stmt = $conn->prepare($sql);
                $stmt->bind_param("ii", $position, $id);
                
                if (!$stmt->execute()) {
                    $success = false;
                    break;
                }
            }
            
            if ($success) {
                echo json_encode(['success' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => "Failed to update order"]);
            }
            exit();
        }
    }
}

// Get slider for editing
$edit_slider = null;
if (isset($_GET['edit']) && !empty($_GET['edit'])) {
    $id = (int)$_GET['edit'];
    
    // Check if the sliders table exists first
    $table_check = $conn->query("SHOW TABLES LIKE 'sliders'");
    if ($table_check && $table_check->num_rows > 0) {
    $sql = "SELECT * FROM sliders WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows == 1) {
        $edit_slider = $result->fetch_assoc();
    }
    
    $stmt->close();
    } else {
        // Table doesn't exist, set error message
        $error = "The sliders table doesn't exist yet. Please <a href='create_sliders_table_manual.php'>click here</a> to create it first.";
    }
}

// Get all sliders for display
$sliders = [];

// Check if the sliders table exists first
$table_check = $conn->query("SHOW TABLES LIKE 'sliders'");
if ($table_check && $table_check->num_rows > 0) {
    $sql = "SELECT * FROM sliders ORDER BY sort_order ASC";
    $result = $conn->query($sql);

if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $sliders[] = $row;
    }
    }
} else {
    // Table doesn't exist, set error message
    $error = "The sliders table doesn't exist yet. Please <a href='create_sliders_table_manual.php'>click here</a> to create it first.";
}

// Page title
$page_title = "Manage Hero Sliders";
include "../admin/includes/header.php";
?>

<style>
/* Slider Management Styles */
.slider-preview-container {
    width: 160px;
    height: 90px;
    overflow: hidden;
    border-radius: 8px;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
    background-color: #f8f9fa;
}

.slider-preview {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.handle {
    cursor: grab;
    color: #adb5bd;
}

.handle:hover {
    color: #6c757d;
}

.table-sliders td {
    vertical-align: middle;
}

.description-cell {
    max-width: 250px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.color-preview {
    display: inline-block;
    width: 20px;
    height: 20px;
    border-radius: 3px;
    vertical-align: middle;
    margin-right: 5px;
    border: 1px solid rgba(0,0,0,0.1);
}

.slider-form-container {
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0,0,0,0.1);
    background-color: #fff;
}

.preview-image-container {
    max-height: 200px;
    overflow: hidden;
    border-radius: 8px;
    margin-bottom: 15px;
}

.preview-image {
    width: 100%;
    height: auto;
}

/* Animation for table rows */
tbody tr {
    transition: all 0.3s ease;
}

tbody tr:hover {
    background-color: rgba(78, 115, 223, 0.05);
}
</style>

<!-- Breadcrumb -->
<nav aria-label="breadcrumb" class="mb-4">
    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
        <li class="breadcrumb-item"><a href="#settingsSubmenu" data-bs-toggle="collapse">Settings</a></li>
        <li class="breadcrumb-item active">Manage Hero Sliders</li>
                    </ol>
</nav>

<!-- Page Title and Action Buttons -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h1 class="h3 mb-0 text-gray-800">Hero Slider Management</h1>
    <a href="#addSliderForm" class="btn btn-primary">
        <i class="fas fa-plus me-1"></i> Add New Slider
    </a>
</div>

<!-- Alerts for success and error messages -->
<?php if ($success_message): ?>
    <div class="alert alert-success alert-dismissible fade show mb-4" role="alert">
        <?php echo $success_message; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert">
        <?php echo $error; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<!-- Main Content -->
<div class="row">
    <!-- Sliders List -->
    <div class="col-lg-7 mb-4">
        <div class="card shadow-sm">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Hero Sliders</h5>
                <div>
                    <small class="text-muted"><i class="fas fa-info-circle me-1"></i> Drag to reorder</small>
                </div>
            </div>
            <div class="card-body p-0">
                <?php if (empty($sliders)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-images fa-3x text-muted mb-3"></i>
                        <h5>No sliders found</h5>
                        <p class="text-muted">Add your first slider using the form</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0 table-sliders">
                            <thead>
                                <tr>
                                    <th width="50px"></th>
                                    <th width="120px">Preview</th>
                                    <th>Title</th>
                                    <th>Status</th>
                                    <th>Type</th>
                                    <th width="100px">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="sliders-list">
                                <?php foreach ($sliders as $slider): ?>
                                    <tr data-id="<?php echo $slider['id']; ?>">
                                        <td class="text-center">
                                            <i class="fas fa-grip-vertical handle"></i>
                                            <span class="d-none order-num"><?php echo $slider['sort_order']; ?></span>
                                        </td>
                                        <td>
                                            <div class="slider-preview-container">
                                                <?php if ($slider['content_type'] == 'image'): ?>
                                                    <img src="../<?php echo htmlspecialchars($slider['media_url']); ?>" 
                                                        alt="<?php echo htmlspecialchars($slider['title']); ?>" 
                                                        class="slider-preview">
                                                <?php else: ?>
                                                    <div class="d-flex align-items-center justify-content-center h-100 bg-light">
                                                        <i class="fas fa-video fa-2x text-muted"></i>
                                                    </div>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="fw-bold"><?php echo htmlspecialchars($slider['title']); ?></div>
                                            <?php if (!empty($slider['subtitle'])): ?>
                                                <small class="text-muted"><?php echo htmlspecialchars($slider['subtitle']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="badge <?php echo $slider['status'] == 'active' ? 'bg-success' : 'bg-secondary'; ?>">
                                                <?php echo ucfirst($slider['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-info">
                                                <i class="fas <?php echo $slider['content_type'] == 'video' ? 'fa-video' : 'fa-image'; ?> me-1"></i>
                                                <?php echo ucfirst($slider['content_type']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="sliders.php?edit=<?php echo $slider['id']; ?>" class="btn btn-primary" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <button type="button" class="btn btn-danger delete-slider" 
                                                    data-id="<?php echo $slider['id']; ?>" 
                                                    data-title="<?php echo htmlspecialchars($slider['title']); ?>" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Slider Form -->
    <div class="col-lg-5 mb-4">
        <div class="card shadow-sm" id="addSliderForm">
                        <div class="card-header">
                <h5 class="mb-0"><?php echo $edit_slider ? 'Edit Slider' : 'Add New Slider'; ?></h5>
                        </div>
            <div class="card-body">
                        <form action="sliders.php" method="post" enctype="multipart/form-data">
                            <input type="hidden" name="action" value="<?php echo $edit_slider ? 'update' : 'add'; ?>">
                            <?php if ($edit_slider): ?>
                                <input type="hidden" name="id" value="<?php echo $edit_slider['id']; ?>">
                                <input type="hidden" name="existing_media" value="<?php echo $edit_slider['media_url']; ?>">
                            <?php endif; ?>
                            
                    <div class="row">
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label for="title" class="form-label">Title <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="title" name="title" required 
                                           value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['title']) : ''; ?>">
                                </div>
                        </div>
                        <div class="col-md-12">
                            <div class="mb-3">
                                <label for="subtitle" class="form-label">Subtitle</label>
                                    <input type="text" class="form-control" id="subtitle" name="subtitle" 
                                           value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['subtitle']) : ''; ?>">
                            </div>
                        </div>
                                </div>
                                
                    <div class="mb-3">
                        <label for="description" class="form-label">Description</label>
                                    <textarea class="form-control" id="description" name="description" rows="3"><?php echo $edit_slider ? htmlspecialchars($edit_slider['description']) : ''; ?></textarea>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="button_text" class="form-label">Button Text</label>
                                            <input type="text" class="form-control" id="button_text" name="button_text" 
                                                   value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['button_text']) : ''; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="button_url" class="form-label">Button URL</label>
                                            <input type="text" class="form-control" id="button_url" name="button_url" 
                                                   value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['button_url']) : ''; ?>">
                                        </div>
                                    </div>
                                </div>
                                
                    <div class="mb-3">
                        <label class="form-label d-block">Content Type</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" id="type_image" name="content_type" value="image" 
                                               <?php echo !$edit_slider || $edit_slider['content_type'] == 'image' ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="type_image">Image</label>
                                    </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" id="type_video" name="content_type" value="video" 
                                               <?php echo $edit_slider && $edit_slider['content_type'] == 'video' ? 'checked' : ''; ?>>
                            <label class="form-check-label" for="type_video">Video</label>
                                    </div>
                                </div>
                                
                    <div class="mb-3">
                        <label for="media_file" class="form-label">Upload <?php echo $edit_slider && $edit_slider['content_type'] == 'video' ? 'Video' : 'Image'; ?></label>
                        <input type="file" class="form-control" id="media_file" name="media_file" 
                                                   <?php echo !$edit_slider ? 'required' : ''; ?>>
                                    <?php if ($edit_slider): ?>
                            <small class="form-text text-muted">Leave empty to keep current file</small>
                                            <?php if ($edit_slider['content_type'] == 'image'): ?>
                                <div class="preview-image-container mt-2">
                                    <img src="../<?php echo htmlspecialchars($edit_slider['media_url']); ?>" 
                                         alt="Current image" class="preview-image">
                                </div>
                                            <?php else: ?>
                                <div class="mt-2">
                                    <span class="badge bg-info">
                                        <i class="fas fa-video me-1"></i> Current video file
                                    </span>
                                        </div>
                            <?php endif; ?>
                                    <?php endif; ?>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="overlay_color" class="form-label">Overlay Color</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <span class="color-preview" id="overlay-color-preview" style="background-color: <?php echo $edit_slider ? htmlspecialchars($edit_slider['overlay_color']) : 'rgba(0, 0, 0, 0.4)'; ?>"></span>
                                    </span>
                                            <input type="text" class="form-control colorpicker" id="overlay_color" name="overlay_color" 
                                                   value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['overlay_color']) : 'rgba(0, 0, 0, 0.4)'; ?>">
                                </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="text_color" class="form-label">Text Color</label>
                                <div class="input-group">
                                    <span class="input-group-text">
                                        <span class="color-preview" id="text-color-preview" style="background-color: <?php echo $edit_slider ? htmlspecialchars($edit_slider['text_color']) : '#ffffff'; ?>"></span>
                                    </span>
                                            <input type="text" class="form-control colorpicker" id="text_color" name="text_color" 
                                                   value="<?php echo $edit_slider ? htmlspecialchars($edit_slider['text_color']) : '#ffffff'; ?>">
                                </div>
                                        </div>
                                    </div>
                                </div>
                                
                    <div class="mb-3">
                        <label for="animation" class="form-label">Animation Effect</label>
                        <select class="form-select" id="animation" name="animation">
                                        <option value="fade" <?php echo $edit_slider && $edit_slider['animation'] == 'fade' ? 'selected' : ''; ?>>Fade</option>
                                        <option value="zoom" <?php echo $edit_slider && $edit_slider['animation'] == 'zoom' ? 'selected' : ''; ?>>Zoom</option>
                                        <option value="slide" <?php echo $edit_slider && $edit_slider['animation'] == 'slide' ? 'selected' : ''; ?>>Slide</option>
                                    </select>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="status" class="form-label">Status</label>
                                <select class="form-select" id="status" name="status">
                                                <option value="active" <?php echo $edit_slider && $edit_slider['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                                                <option value="inactive" <?php echo $edit_slider && $edit_slider['status'] == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                            <div class="mb-3">
                                <label for="sort_order" class="form-label">Sort Order</label>
                                            <input type="number" class="form-control" id="sort_order" name="sort_order" min="0" 
                                                   value="<?php echo $edit_slider ? $edit_slider['sort_order'] : count($sliders); ?>">
                                    </div>
                                </div>
                            </div>
                            
                    <div class="d-flex justify-content-between mt-4">
                                <button type="submit" class="btn btn-primary">
                            <i class="fas <?php echo $edit_slider ? 'fa-save' : 'fa-plus'; ?> me-1"></i>
                                    <?php echo $edit_slider ? 'Update Slider' : 'Add Slider'; ?>
                                </button>
                                <?php if ($edit_slider): ?>
                            <a href="sliders.php" class="btn btn-secondary">
                                <i class="fas fa-times me-1"></i> Cancel
                            </a>
                                <?php endif; ?>
                            </div>
                        </form>
                </div>
            </div>
        </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirm Delete</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                    <h5>Are you sure you want to delete this slider?</h5>
                    <p class="mb-0">Slider: <span id="slider-title" class="fw-bold"></span></p>
                </div>
                <p class="text-danger text-center">This action cannot be undone!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i> Cancel
                </button>
                <form id="delete-form" action="sliders.php" method="post">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" id="delete-id">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-1"></i> Delete Permanently
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<?php include "../admin/includes/footer.php"; ?>

<script>
$(function () {
    // File input visual enhancement
    if (typeof bsCustomFileInput !== 'undefined') {
    bsCustomFileInput.init();
    }
    
    // Color picker initialization
    if ($.fn.colorpicker) {
        $('.colorpicker').colorpicker().on('colorpickerChange', function(e) {
            const previewId = $(this).attr('id') === 'overlay_color' ? 'overlay-color-preview' : 'text-color-preview';
            $('#' + previewId).css('background-color', e.color.toString());
        });
    }
    
    // Handle delete confirmation
    $('.delete-slider').on('click', function() {
        var id = $(this).data('id');
        var title = $(this).data('title');
        
        $('#delete-id').val(id);
        $('#slider-title').text(title);
        
        // Use Bootstrap 5 modal
        var deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
        deleteModal.show();
    });
    
    // Toggle content type
    $('input[name="content_type"]').on('change', function() {
        var type = $(this).val();
        var label = $('label[for="media_file"]');
        label.text('Upload ' + (type === 'video' ? 'Video' : 'Image'));
    });
    
    // Make table rows sortable
    if ($.fn.sortable && $('#sliders-list').length > 0) {
    $('#sliders-list').sortable({
        handle: '.handle',
            helper: function(e, tr) {
                var $originals = tr.children();
                var $helper = tr.clone();
                $helper.children().each(function(index) {
                    $(this).width($originals.eq(index).width());
                });
                return $helper;
            },
        update: function(event, ui) {
            var order = {};
            $('#sliders-list tr').each(function(index) {
                var id = $(this).data('id');
                order[index] = id;
                $(this).find('.order-num').text(index);
            });
                
                // Display spinner
                const loadingToast = $(`
                    <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 5000">
                        <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                            <div class="toast-header">
                                <div class="spinner-border spinner-border-sm me-2" role="status">
                                    <span class="visually-hidden">Loading...</span>
                                </div>
                                <strong class="me-auto">Updating order...</strong>
                            </div>
                        </div>
                    </div>
                `);
                $('body').append(loadingToast);
            
            // Save the new order via AJAX
            $.ajax({
                url: 'sliders.php',
                type: 'POST',
                data: {
                    action: 'update_order',
                    order: JSON.stringify(order)
                },
                success: function(response) {
                        try {
                    var data = JSON.parse(response);
                            
                            // Remove loading toast
                            loadingToast.remove();
                            
                    if (data.success) {
                                // Show success toast
                                const successToast = $(`
                                    <div class="position-fixed bottom-0 end-0 p-3" style="z-index: 5000">
                                        <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                                            <div class="toast-header bg-success text-white">
                                                <i class="fas fa-check-circle me-2"></i>
                                                <strong class="me-auto">Success</strong>
                                                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast" aria-label="Close"></button>
                                            </div>
                                            <div class="toast-body">
                                                Slider order updated successfully!
                                            </div>
                                        </div>
                                    </div>
                                `);
                                
                                $('body').append(successToast);
                                
                                // Remove toast after 3 seconds
                        setTimeout(function() {
                                    successToast.remove();
                        }, 3000);
                    } else {
                        alert('Error: ' + data.error);
                            }
                        } catch (e) {
                            console.error('Invalid JSON response:', response);
                            loadingToast.remove();
                    }
                },
                error: function() {
                        loadingToast.remove();
                    alert('An error occurred while updating slider order');
                }
            });
            }
        }).disableSelection();
    }
    
    // Smooth scroll to form when "Add New Slider" is clicked
    $('a[href="#addSliderForm"]').on('click', function(e) {
        e.preventDefault();
        $('html, body').animate({
            scrollTop: $($(this).attr('href')).offset().top - 100
        }, 500);
    });
    
    // Preview image upload
    $('#media_file').on('change', function() {
        const file = this.files[0];
        if (file && file.type.match('image.*')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                // Check if preview container exists, if not create it
                let previewContainer = $('.preview-image-container');
                if (previewContainer.length === 0) {
                    previewContainer = $('<div class="preview-image-container mt-2"></div>');
                    $('#media_file').after(previewContainer);
                }
                
                // Update or create preview image
                if (previewContainer.find('img.preview-image').length === 0) {
                    previewContainer.html('<img src="' + e.target.result + '" class="preview-image" />');
                } else {
                    previewContainer.find('img.preview-image').attr('src', e.target.result);
                }
            }
            reader.readAsDataURL(file);
        }
    });
});
</script>