<?php
$page_title = "স্লাইডার ম্যানেজমেন্ট";
require_once 'includes/auth_check.php';
$message = '';

// Handle Image Upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['slider_image'])) {
    if ($_FILES['slider_image']['error'] == 0) {
        
        // Define two types of paths
        $upload_dir = "../uploads/sliders/"; // Path for moving the file (relative to this admin script)
        $db_path_dir = "uploads/sliders/";    // Path to store in the database (relative to the project root)

        $file_extension = strtolower(pathinfo($_FILES["slider_image"]["name"], PATHINFO_EXTENSION));
        $filename = "slide_" . time() . "." . $file_extension;

        $target_file_path = $upload_dir . $filename;
        $db_file_path = $db_path_dir . $filename;

        // Check if file is a valid image and within size limits
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
        if (in_array($file_extension, $allowed_types) && $_FILES["slider_image"]["size"] <= 5000000) { // Max 5MB
            
            if (move_uploaded_file($_FILES["slider_image"]["tmp_name"], $target_file_path)) {
                $link_url = $_POST['link_url'];
                $sort_order = (int)$_POST['sort_order'];
                
                // Insert the clean path (without ../) into the database
                $stmt = $conn->prepare("INSERT INTO sliders (image_url, link_url, sort_order) VALUES (?, ?, ?)");
                $stmt->bind_param("ssi", $db_file_path, $link_url, $sort_order);
                $stmt->execute();
                $message = '<div class="alert alert-success">স্লাইড সফলভাবে যোগ হয়েছে।</div>';
            } else {
                $message = '<div class="alert alert-danger">ফাইলটি আপলোড করা যায়নি। ফোল্ডার পারমিশন চেক করুন।</div>';
            }
        } else {
             $message = '<div class="alert alert-danger">ছবিটি অবশ্যই JPG, PNG, GIF ফরম্যাটের এবং 5MB-এর কম হতে হবে।</div>';
        }
    } else {
        $message = '<div class="alert alert-danger">ছবি আপলোড করতে সমস্যা হয়েছে।</div>';
    }
}

// Handle Delete
if (isset($_GET['delete_id'])) {
    $delete_id = (int)$_GET['delete_id'];
    $res = $conn->query("SELECT image_url FROM sliders WHERE id = $delete_id");
    if ($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        // Use the root-relative path for deletion
        if (file_exists('../' . $row['image_url'])) {
            unlink('../' . $row['image_url']);
        }
    }
    $conn->query("DELETE FROM sliders WHERE id = $delete_id");
    header("Location: sliders.php"); exit;
}

$sliders = $conn->query("SELECT * FROM sliders ORDER BY sort_order ASC");
include 'includes/header.php';
?>
<div class="container-fluid">
    <h2 class="mb-4">স্লাইডার ম্যানেজমেন্ট</h2>
    <?php echo $message; ?>
    <div class="card mb-4"><div class="card-header"><h4>নতুন স্লাইড যোগ করুন</h4></div><div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <div class="col-md-4"><label class="form-label">স্লাইড ইমেজ (Max 5MB)</label><input type="file" name="slider_image" class="form-control" required></div>
                <div class="col-md-4"><label class="form-label">লিংক URL (ঐচ্ছিক)</label><input type="text" name="link_url" class="form-control" placeholder="https://example.com"></div>
                <div class="col-md-2"><label class="form-label">সর্ট অর্ডার</label><input type="number" name="sort_order" class="form-control" value="0"></div>
                <div class="col-md-2 d-flex align-items-end"><button type="submit" class="btn btn-primary w-100">আপলোড</button></div>
            </div>
        </form>
    </div></div>
    <div class="card"><div class="card-header"><h4>বর্তমান স্লাইডসমূহ</h4></div><div class="card-body"><div class="table-responsive">
    <table class="table table-bordered">
        <thead><tr><th>ছবি</th><th>লিংক</th><th>সর্ট অর্ডার</th><th>একশন</th></tr></thead>
        <tbody>
            <?php while($slide = $sliders->fetch_assoc()): ?>
            <tr>
                <td><img src="../<?php echo htmlspecialchars($slide['image_url']); ?>" height="50"></td>
                <td><?php echo htmlspecialchars($slide['link_url']); ?></td>
                <td><?php echo $slide['sort_order']; ?></td>
                <td><a href="?delete_id=<?php echo $slide['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('আপনি কি নিশ্চিত?')"><i class="fas fa-trash"></i></a></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
    </div></div></div>
</div>
<?php include 'includes/footer.php'; $conn->close(); ?>