<?php
/**
 * slider_logic.php - স্লাইডার ম্যানেজমেন্ট সিস্টেম
 */

// স্লাইডার টেবিল তৈরি (না থাকলে)
mysqli_query($conn, "CREATE TABLE IF NOT EXISTS sliders (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    image_url TEXT NOT NULL,
    btn_text VARCHAR(50),
    btn_link VARCHAR(255),
    order_no INT DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

// ডাটাবেস আপডেট: source_type কলামটি আছে কিনা চেক করে যোগ করা (এরর ফিক্স)
$check_column = mysqli_query($conn, "SHOW COLUMNS FROM sliders LIKE 'source_type'");
if (mysqli_num_rows($check_column) == 0) {
    mysqli_query($conn, "ALTER TABLE sliders ADD source_type ENUM('local', 'url') DEFAULT 'url' AFTER image_url");
}

// স্লাইডার ডিলিট লজিক
if (isset($_GET['delete_slider'])) {
    $del_id = (int)$_GET['delete_slider'];
    
    $res = mysqli_query($conn, "SELECT image_url, source_type FROM sliders WHERE id = $del_id");
    $data = mysqli_fetch_assoc($res);
    if ($data && isset($data['source_type']) && $data['source_type'] == 'local' && file_exists($data['image_url'])) {
        unlink($data['image_url']);
    }

    mysqli_query($conn, "DELETE FROM sliders WHERE id = $del_id");
    echo "<script>window.location.href='admin.php?view=sliders';</script>";
}

// স্লাইডার সেভ লজিক
if (isset($_POST['save_slider'])) {
    $title = mysqli_real_escape_string($conn, $_POST['title']);
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $btn_text = mysqli_real_escape_string($conn, $_POST['btn_text']);
    $btn_link = mysqli_real_escape_string($conn, $_POST['btn_link']);
    $order_no = (int)$_POST['order_no'];
    $slider_id = $_POST['slider_id'] ?? '';
    
    $upload_type = $_POST['upload_type'] ?? 'url';
    $image_url = "";
    $source_type = "url";

    if ($upload_type == 'file' && !empty($_FILES["slider_file"]["name"])) {
        $target_dir = "uploads/sliders/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
        
        $file_name = time() . '_' . basename($_FILES["slider_file"]["name"]);
        $target_file = $target_dir . $file_name;
        
        if (move_uploaded_file($_FILES["slider_file"]["tmp_name"], $target_file)) {
            $image_url = $target_file;
            $source_type = "local";
        }
    } else {
        $image_url = mysqli_real_escape_string($conn, $_POST['image_url'] ?? '');
        $source_type = "url";
    }

    if (empty($image_url) && !empty($slider_id)) {
        $existing = mysqli_fetch_assoc(mysqli_query($conn, "SELECT image_url, source_type FROM sliders WHERE id=$slider_id"));
        $image_url = $existing['image_url'];
        $source_type = $existing['source_type'];
    }

    if (!empty($slider_id)) {
        $query = "UPDATE sliders SET title='$title', description='$description', image_url='$image_url', source_type='$source_type', btn_text='$btn_text', btn_link='$btn_link', order_no='$order_no' WHERE id=$slider_id";
    } else {
        $query = "INSERT INTO sliders (title, description, image_url, source_type, btn_text, btn_link, order_no) VALUES ('$title', '$description', '$image_url', '$source_type', '$btn_text', '$btn_link', '$order_no')";
    }

    if (mysqli_query($conn, $query)) {
        echo "<script>window.location.href='admin.php?view=sliders';</script>";
        exit();
    } else {
        die("Query Failed: " . mysqli_error($conn));
    }
}

$sliders_res = mysqli_query($conn, "SELECT * FROM sliders ORDER BY order_no ASC");
?>

<div class="section-card" style="background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3 style="margin: 0; color: #333;"><i class="fas fa-images" style="color: #4e73df;"></i> হোম স্লাইডার ম্যানেজমেন্ট</h3>
        <button onclick="openSliderModal()" class="btn btn-primary" style="background: #4e73df; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer;">
            <i class="fas fa-plus-circle"></i> নতুন স্লাইড
        </button>
    </div>

    <div style="overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr style="background: #f8f9fc; border-bottom: 2px solid #e3e6f0; text-align: left;">
                    <th style="padding: 15px;">ইমেজ</th>
                    <th style="padding: 15px;">শিরোনাম</th>
                    <th style="padding: 15px;">অর্ডার</th>
                    <th style="padding: 15px; text-align: center;">অ্যাকশন</th>
                </tr>
            </thead>
            <tbody>
                <?php if (mysqli_num_rows($sliders_res) > 0): 
                    while ($slide = mysqli_fetch_assoc($sliders_res)): ?>
                <tr style="border-bottom: 1px solid #eee;">
                    <td style="padding: 15px;">
                        <img src="<?php echo htmlspecialchars($slide['image_url']); ?>" style="width: 100px; height: 50px; object-fit: cover; border-radius: 4px;">
                    </td>
                    <td style="padding: 15px;"><?php echo htmlspecialchars($slide['title']); ?></td>
                    <td style="padding: 15px;"><?php echo $slide['order_no']; ?></td>
                    <td style="padding: 15px; text-align: center;">
                        <button onclick='editSlider(<?php echo json_encode($slide); ?>)' style="border:none; color:#4e73df; cursor:pointer; background:none; font-size: 18px;"><i class="fas fa-edit"></i></button>
                        <a href="admin.php?view=sliders&delete_slider=<?php echo $slide['id']; ?>" style="color:#e74a3b; margin-left:15px; font-size: 18px;" onclick="return confirm('স্লাইডটি মুছে ফেলতে চান?')"><i class="fas fa-trash"></i></a>
                    </td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="4" style="padding: 20px; text-align: center;">কোনো স্লাইডার পাওয়া যায়নি</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="sliderModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:9999; justify-content:center; align-items:center; backdrop-filter: blur(4px);">
    <div style="background:white; padding:30px; border-radius:15px; width:90%; max-width: 600px; box-shadow: 0 10px 30px rgba(0,0,0,0.2);">
        <h4 id="slider_modal_title" style="margin-top:0; border-bottom: 1px solid #eee; padding-bottom: 15px;">নতুন স্লাইড যোগ করুন</h4>
        <form id="sliderForm" method="POST" action="admin.php?view=sliders" enctype="multipart/form-data">
            <input type="hidden" name="slider_id" id="slider_id">
            
            <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">স্লাইড টাইটেল:</label>
                <input type="text" name="title" id="slide_title" required style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
            </div>

            <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">ডেসক্রিপশন:</label>
                <textarea name="description" id="slide_desc" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; height: 80px;"></textarea>
            </div>

            <div style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">ইমেজ সোর্স:</label>
                <select name="upload_type" id="upload_type" onchange="toggleInput()" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px; background: white;">
                    <option value="url">ইমেজ URL ব্যবহার করুন</option>
                    <option value="file">কম্পিউটার থেকে আপলোড করুন</option>
                </select>
            </div>

            <div id="url_input_div" style="margin-bottom:15px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">ইমেজ URL:</label>
                <input type="url" name="image_url" id="slide_image" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;" placeholder="https://example.com/image.jpg">
            </div>

            <div id="file_input_div" style="margin-bottom:15px; display:none;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">ফাইল সিলেক্ট করুন:</label>
                <input type="file" name="slider_file" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:6px; background: white;">
            </div>

            <div style="display: flex; gap: 15px; margin-bottom:15px;">
                <div style="flex:1;">
                    <label style="display:block; margin-bottom:5px; font-weight:600;">বাটন টেক্সট:</label>
                    <input type="text" name="btn_text" id="slide_btn_text" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
                </div>
                <div style="flex:1;">
                    <label style="display:block; margin-bottom:5px; font-weight:600;">বাটন লিঙ্ক:</label>
                    <input type="text" name="btn_link" id="slide_btn_link" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
                </div>
            </div>

            <div style="margin-bottom:20px;">
                <label style="display:block; margin-bottom:5px; font-weight:600;">ডিসপ্লে অর্ডার (ক্রম):</label>
                <input type="number" name="order_no" id="slide_order" value="0" style="width:100%; padding:10px; border:1px solid #ddd; border-radius:6px;">
            </div>

            <div style="text-align: right; border-top: 1px solid #eee; padding-top: 20px;">
                <button type="button" onclick="document.getElementById('sliderModal').style.display='none'" style="padding: 10px 25px; background: #f1f1f1; border:none; border-radius:6px; cursor:pointer; font-weight:600;">বাতিল</button>
                <button type="submit" name="save_slider" style="padding: 10px 25px; background: #4e73df; color:white; border:none; border-radius:6px; cursor:pointer; font-weight:600; margin-left: 10px;">সংরক্ষণ করুন</button>
            </div>
        </form>
    </div>
</div>

<script>
function toggleInput() {
    var type = document.getElementById('upload_type').value;
    var fileDiv = document.getElementById('file_input_div');
    var urlDiv = document.getElementById('url_input_div');
    
    if (type === 'file') {
        fileDiv.style.display = 'block';
        urlDiv.style.display = 'none';
        document.getElementById('slide_image').required = false;
    } else {
        fileDiv.style.display = 'none';
        urlDiv.style.display = 'block';
        document.getElementById('slide_image').required = (document.getElementById('slider_id').value === '');
    }
}

function openSliderModal() {
    document.getElementById('sliderForm').reset();
    document.getElementById('slider_id').value = '';
    document.getElementById('slider_modal_title').innerText = 'নতুন স্লাইড যোগ করুন';
    document.getElementById('sliderModal').style.display = 'flex';
    document.getElementById('upload_type').value = 'url';
    toggleInput();
}

function editSlider(data) {
    document.getElementById('slider_id').value = data.id;
    document.getElementById('slide_title').value = data.title;
    document.getElementById('slide_desc').value = data.description;
    
    if(data.source_type === 'local') {
        document.getElementById('upload_type').value = 'file';
    } else {
        document.getElementById('upload_type').value = 'url';
        document.getElementById('slide_image').value = data.image_url;
    }
    
    toggleInput();
    
    document.getElementById('slide_btn_text').value = data.btn_text;
    document.getElementById('slide_btn_link').value = data.btn_link;
    document.getElementById('slide_order').value = data.order_no;
    document.getElementById('slider_modal_title').innerText = 'স্লাইড এডিট করুন';
    document.getElementById('sliderModal').style.display = 'flex';
}
</script>