<?php
/**
 * Manage Frontend Sliders/Banners (100% Mobile Responsive Fixed + Editable)
 */
require_once 'header.php';

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

// ১. স্লাইডার আপলোডের ফোল্ডার নিশ্চিত করা
$slider_dir = '../uploads/sliders/';
if (!is_dir($slider_dir)) {
    mkdir($slider_dir, 0777, true);
}

// (Safety) যদি ডাটাবেসে sliders টেবিল না থাকে, তবে অটোমেটিক তৈরি করে নিবে
try {
    $pdo->query("SELECT 1 FROM sliders LIMIT 1");
} catch (PDOException $e) {
    $pdo->exec("CREATE TABLE IF NOT EXISTS sliders (
        id INT AUTO_INCREMENT PRIMARY KEY, 
        image VARCHAR(255) NOT NULL, 
        link VARCHAR(255) NULL, 
        status ENUM('active', 'inactive') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
}

// Ensure status column exists (Self Healing)
try {
    $pdo->exec("ALTER TABLE sliders ADD COLUMN status ENUM('active', 'inactive') DEFAULT 'active'");
} catch (PDOException $e) {}

// ২. স্লাইডার যোগ করার লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_slider'])) {
    $link = trim($_POST['link'] ?? '');
    
    if (isset($_FILES['slider_image']) && $_FILES['slider_image']['error'] === 0) {
        $ext = strtolower(pathinfo($_FILES['slider_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (in_array($ext, $allowed)) {
            $img_name = 'slider_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['slider_image']['tmp_name'], $slider_dir . $img_name)) {
                $stmt = $pdo->prepare("INSERT INTO sliders (image, link, status) VALUES (?, ?, 'active')");
                $stmt->execute([$img_name, $link]);
                $success = "New banner added successfully!";
            } else {
                $error = "Failed to upload image.";
            }
        } else {
            $error = "Invalid image format. Please use JPG, PNG, or WEBP.";
        }
    } else {
        $error = "Please upload a banner image.";
    }
}

// স্লাইডার আপডেট করার লজিক
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_slider'])) {
    $id = (int)$_POST['slider_id'];
    $link = trim($_POST['edit_link'] ?? '');
    $status = $_POST['edit_status'] ?? 'active';

    // Fetch existing image
    $stmt = $pdo->prepare("SELECT image FROM sliders WHERE id = ?");
    $stmt->execute([$id]);
    $current_slider = $stmt->fetch();
    $img_name = $current_slider['image'];

    if (isset($_FILES['edit_slider_image']) && $_FILES['edit_slider_image']['error'] === 0) {
        $ext = strtolower(pathinfo($_FILES['edit_slider_image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg', 'jpeg', 'png', 'webp'];

        if (in_array($ext, $allowed)) {
            $new_img_name = 'slider_' . time() . '.' . $ext;
            if (move_uploaded_file($_FILES['edit_slider_image']['tmp_name'], $slider_dir . $new_img_name)) {
                if (file_exists($slider_dir . $img_name)) {
                    @unlink($slider_dir . $img_name);
                }
                $img_name = $new_img_name;
            } else {
                $error = "Failed to upload new image.";
            }
        } else {
            $error = "Invalid image format. Please use JPG, PNG, or WEBP.";
        }
    }

    if (empty($error)) {
        $stmt = $pdo->prepare("UPDATE sliders SET image = ?, link = ?, status = ? WHERE id = ?");
        $stmt->execute([$img_name, $link, $status, $id]);
        $success = "Banner updated successfully!";
    }
}

// ৩. স্লাইডার ডিলিট করার লজিক
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    
    $stmt = $pdo->prepare("SELECT image FROM sliders WHERE id = ?");
    $stmt->execute([$id]);
    $slider = $stmt->fetch();
    
    if ($slider && file_exists($slider_dir . $slider['image'])) {
        unlink($slider_dir . $slider['image']); 
    }

    $pdo->prepare("DELETE FROM sliders WHERE id = ?")->execute([$id]);
    $success = "Banner deleted successfully!";
}

// ৪. স্লাইডার লিস্ট ফেচ করা
$sliders = $pdo->query("SELECT * FROM sliders ORDER BY id DESC")->fetchAll();

// Edit State
$edit_mode = false;
$edit_data = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $pdo->prepare("SELECT * FROM sliders WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_data = $stmt->fetch();
    if ($edit_data) {
        $edit_mode = true;
    }
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16;
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    *, *::before, *::after {
        box-sizing: border-box;
    }

    body { 
        background: var(--bg-light); 
        color: var(--text-main); 
        font-family: 'Inter', sans-serif; 
        margin: 0; 
        padding: 0; 
        overflow-x: hidden; 
    }
    
    .settings-container { 
        width: 100%; 
        max-width: 1100px; 
        margin: 0 auto; 
        padding: 20px 15px; 
    }
    
    .page-title { 
        font-size: 1.5rem; 
        font-weight: 800; 
        margin: 0 0 20px 0; 
        color: var(--text-main); 
    }

    .grid-layout {
        display: grid; 
        grid-template-columns: 320px minmax(0, 1fr);
        gap: 20px; 
        align-items: start;
        width: 100%;
    }

    .admin-card { 
        background: var(--card-bg); 
        border-radius: 12px; 
        padding: 20px; 
        border: 1px solid var(--border); 
        margin-bottom: 20px; 
        box-shadow: none;
        width: 100%;
        overflow: hidden;
    }

    .card-title { 
        margin: 0 0 15px 0; 
        font-size: 1.1rem; 
        font-weight: 700; 
        color: var(--text-main); 
        border-bottom: 1px solid var(--border); 
        padding-bottom: 12px; 
    }

    .form-group { margin-bottom: 15px; width: 100%; }
    .form-label { display: block; font-size: 0.85rem; font-weight: 600; margin-bottom: 6px; color: var(--text-main); }
    .form-control { 
        width: 100%; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; 
        font-size: 0.9rem; transition: 0.2s; background: transparent;
    }
    .form-control:focus { border-color: var(--primary); outline: none; }
    
    .file-upload-box { 
        width: 100%; border: 2px dashed var(--border); padding: 20px; border-radius: 10px; 
        text-align: center; background: #fafafa; cursor: pointer; position: relative; transition: 0.3s; 
    }
    .file-upload-box:hover { border-color: var(--primary); background: #f4fce3; }
    .file-upload-box input[type="file"] { position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%; }
    
    .btn-submit { 
        background: var(--primary); color: white; padding: 12px; border: none; 
        border-radius: 8px; font-weight: 700; font-size: 0.95rem; cursor: pointer; width: 100%; transition: 0.3s; 
    }
    .btn-submit:hover { background: var(--primary-hover); }
    
    .btn-cancel {
        background: #f1f5f9; color: #475569; padding: 12px; border: none; 
        border-radius: 8px; font-weight: 600; font-size: 0.95rem; cursor: pointer; width: 100%; 
        transition: 0.3s; margin-top: 10px; display: block; text-align: center; text-decoration: none; 
    }
    .btn-cancel:hover { background: #e2e8f0; color: #1e293b; }

    /* Table Design */
    .table-responsive { 
        width: 100%; 
        overflow-x: auto; 
        -webkit-overflow-scrolling: touch; 
        display: block;
    }
    
    .data-table { 
        width: 100%; 
        border-collapse: collapse; 
        text-align: left; 
        min-width: 550px; 
    }
    
    .data-table th { padding: 12px 15px; font-size: 0.8rem; color: var(--text-muted); font-weight: 600; border-bottom: 1px solid var(--border); text-transform: uppercase; background: #fafafa; white-space: nowrap; }
    .data-table td { padding: 15px; border-bottom: 1px solid var(--border); font-size: 0.9rem; color: var(--text-main); vertical-align: middle; }
    .data-table tr:last-child td { border-bottom: none; }
    
    .banner-preview { width: 100px; height: 50px; border-radius: 6px; object-fit: cover; border: 1px solid var(--border); display: block; }
    
    .action-btns { display: flex; gap: 8px; justify-content: flex-end; }
    .btn-edit { color: #3b82f6; background: #eff6ff; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 0.8rem; font-weight: 600; transition: 0.2s; border: 1px solid transparent; white-space: nowrap; }
    .btn-edit:hover { background: #dbeafe; border-color: #bfdbfe; }
    .btn-delete { color: #ef4444; background: #fef2f2; padding: 6px 12px; border-radius: 6px; text-decoration: none; font-size: 0.8rem; font-weight: 600; transition: 0.2s; border: 1px solid transparent; white-space: nowrap; }
    .btn-delete:hover { background: #fee2e2; border-color: #fecaca; }

    .status-badge { padding: 4px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; white-space: nowrap; }
    .status-active { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }
    .status-inactive { background: #f1f5f9; color: #64748b; border: 1px solid #cbd5e1; }

    /* Toast */
    .toast-success { background: #10b981 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #059669 !important; padding: 10px 20px !important; }
    .toast-error { background: #ef4444 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #b91c1c !important; padding: 10px 20px !important; }

    @media (max-width: 850px) {
        .grid-layout { grid-template-columns: 1fr; }
        .admin-card { padding: 15px; }
    }
</style>

<div class="settings-container">
    <h1 class="page-title">Manage Banners</h1>

    <div class="grid-layout">
        
        <div>
            <?php if(!$edit_mode): ?>
            <div class="admin-card">
                <h3 class="card-title">Add New Banner</h3>
                <form action="" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="add_slider" value="1">
                    
                    <div class="form-group">
                        <label class="form-label">Banner Image *</label>
                        <div class="file-upload-box">
                            <div style="font-weight: 600; font-size: 0.85rem; color: var(--text-main);">Upload JPG/PNG/WEBP</div>
                            <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 4px;">Aspect Ratio: 16:9 or 21:9</div>
                            <input type="file" name="slider_image" accept=".png,.jpg,.jpeg,.webp" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Redirect Link (Optional)</label>
                        <input type="url" name="link" class="form-control" placeholder="https://example.com/...">
                    </div>
                    
                    <button type="submit" class="btn-submit">Publish Banner</button>
                </form>
            </div>
            <?php else: ?>
            <div class="admin-card" style="border-color: #bfdbfe; background: #f8fafc;">
                <h3 class="card-title" style="color: #1e3a8a;">Edit Banner</h3>
                <form action="sliders.php" method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="update_slider" value="1">
                    <input type="hidden" name="slider_id" value="<?php echo $edit_data['id']; ?>">
                    
                    <div style="margin-bottom: 15px; text-align: center;">
                        <img src="../uploads/sliders/<?php echo $edit_data['image']; ?>" style="max-width: 100%; height: auto; border-radius: 8px; border: 1px solid var(--border);">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Change Image (Leave empty to keep current)</label>
                        <div class="file-upload-box" style="padding: 15px;">
                            <div style="font-weight: 600; font-size: 0.8rem;">Upload New Image</div>
                            <input type="file" name="edit_slider_image" accept=".png,.jpg,.jpeg,.webp">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Redirect Link</label>
                        <input type="url" name="edit_link" class="form-control" value="<?php echo htmlspecialchars($edit_data['link']); ?>" placeholder="https://example.com/...">
                    </div>

                    <div class="form-group">
                        <label class="form-label">Status</label>
                        <select name="edit_status" class="form-control">
                            <option value="active" <?php echo $edit_data['status'] == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $edit_data['status'] == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    
                    <button type="submit" class="btn-submit">Update Banner</button>
                    <a href="sliders.php" class="btn-cancel">Cancel Edit</a>
                </form>
            </div>
            <?php endif; ?>
        </div>

        <div class="admin-card">
            <h3 class="card-title">Active & Inactive Banners</h3>
            
            <div class="table-responsive">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Preview</th>
                            <th>Target Link</th>
                            <th>Status</th>
                            <th style="text-align: right;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($sliders as $slide): ?>
                        <tr style="<?php echo $slide['id'] == ($edit_data['id'] ?? 0) ? 'background: #f0fdf4;' : ''; ?>">
                            <td>
                                <img src="../uploads/sliders/<?php echo $slide['image']; ?>" alt="Banner" class="banner-preview" onerror="this.src='https://via.placeholder.com/120x60';">
                            </td>
                            <td>
                                <?php if(!empty($slide['link'])): ?>
                                    <a href="<?php echo htmlspecialchars($slide['link']); ?>" target="_blank" style="color: #3b82f6; font-size: 0.8rem; font-weight: 600; text-decoration: none; word-break: break-all; display: inline-block; max-width: 150px;">
                                        View Link &nearr;
                                    </a>
                                <?php else: ?>
                                    <span style="color: var(--text-muted); font-size: 0.8rem;">No Link</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span class="status-badge status-<?php echo $slide['status']; ?>"><?php echo ucfirst($slide['status']); ?></span>
                            </td>
                            <td>
                                <div class="action-btns">
                                    <a href="?edit=<?php echo $slide['id']; ?>" class="btn-edit">Edit</a>
                                    <a href="?delete=<?php echo $slide['id']; ?>" onclick="return confirm('Delete this banner?')" class="btn-delete">Del</a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        
                        <?php if(count($sliders) == 0): ?>
                            <tr><td colspan="4" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">No banners uploaded yet.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>
</script>

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