<?php
require_once "config.php";

session_start();

date_default_timezone_set("Asia/Dhaka");

if (!isset($conn) || !($conn instanceof mysqli)) {
    die("Database connection not available.");
}
$conn->set_charset("utf8mb4");

if (empty($_SESSION['auth_logged_in'])) {
    header("Location: login.php");
    exit;
}

$can_read = false;
$can_edit = false;
$can_delete = false;

$username = $_SESSION['auth_username'];
$role = $_SESSION['auth_role'];

if ($role === 'admin') {
    $can_read = true;
    $can_edit = true;
    $can_delete = true;
} elseif ($role === 'permission') {
    $sql = "SELECT dialog_slider_read, dialog_slider_edit, dialog_slider_delete FROM `Zabbar_Admin_Permission` WHERE username = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $res = $stmt->get_result();
    
    if ($row = $res->fetch_assoc()) {
        $can_read = strtolower(trim($row['dialog_slider_read'] ?? '')) === 'yes';
        $can_edit = strtolower(trim($row['dialog_slider_edit'] ?? '')) === 'yes';
        $can_delete = strtolower(trim($row['dialog_slider_delete'] ?? '')) === 'yes';
    }
    $stmt->close();
}

if (!$can_read && !$can_edit && !$can_delete) {
    die("<!DOCTYPE html><html><head><title>Access Denied</title></head><body style='font-family:system-ui;text-align:center;padding:50px;color:#991b1b;background:#fef2f2;'><h2>Access Denied</h2><p>You do not have permission to view this page.</p></body></html>");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add' && $can_edit) {
        $image = trim($_POST['image'] ?? '');
        $click_link = trim($_POST['click_link'] ?? '');
        
        if ($image !== '') {
            $sql = "INSERT INTO slider (image, click_link) VALUES (?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $image, $click_link);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($action === 'edit' && $can_edit) {
        $id = (int)($_POST['id'] ?? 0);
        $image = trim($_POST['image'] ?? '');
        $click_link = trim($_POST['click_link'] ?? '');
        
        if ($id > 0 && $image !== '') {
            $sql = "UPDATE slider SET image = ?, click_link = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssi", $image, $click_link, $id);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($action === 'delete' && $can_delete) {
        $id = (int)($_POST['id'] ?? 0);
        
        if ($id > 0) {
            $sql = "DELETE FROM slider WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
        }
    }
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

$sliders = [];
if ($can_read || $can_edit || $can_delete) {
    $res = $conn->query("SELECT * FROM slider ORDER BY id DESC");
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $sliders[] = $row;
        }
    }
}
require_once "header.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dialog Slider Management</title>
    <style>
        :root {
            --bg: #f8fafc;
            --card: #ffffff;
            --text: #0f172a;
            --muted: #64748b;
            --line: #e2e8f0;
            --accent: #3b82f6;
            --accent2: #8b5cf6;
            --danger: #ef4444;
            --warning: #f59e0b;
            --shadow: 0 10px 40px -10px rgba(15, 23, 42, .08);
            --radius: 20px;
        }
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            min-height: 100vh;
            font-family: system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif;
            background: var(--bg);
            color: var(--text);
            padding: 30px 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            display: flex;
            flex-direction: column;
            gap: 24px;
        }
        .header h1 {
            font-size: 28px;
            font-weight: 800;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }
        .card {
            background: var(--card);
            border: 1px solid var(--line);
            border-radius: var(--radius);
            box-shadow: var(--shadow);
            padding: 24px;
        }
        .field {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 16px;
            flex: 1;
        }
        .field label {
            font-size: 13px;
            font-weight: 700;
            color: #334155;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        input[type="text"] {
            width: 100%;
            border: 1px solid var(--line);
            background: #f8fafc;
            color: var(--text);
            border-radius: 12px;
            padding: 14px 16px;
            font-size: 14px;
            outline: none;
            transition: .2s ease;
        }
        input:focus {
            background: #fff;
            border-color: rgba(59,130,246,.65);
            box-shadow: 0 0 0 4px rgba(59,130,246,.10);
        }
        .form-row {
            display: flex;
            gap: 16px;
            align-items: flex-start;
            flex-wrap: wrap;
        }
        .btn {
            border: none;
            border-radius: 12px;
            padding: 12px 20px;
            font-size: 14px;
            font-weight: 700;
            color: #fff;
            cursor: pointer;
            background: linear-gradient(135deg, var(--accent), var(--accent2));
            transition: .2s ease;
        }
        .btn:hover { transform: translateY(-2px); box-shadow: 0 8px 20px rgba(59,130,246,.25); }
        .btn-danger { background: var(--danger); padding: 8px 14px; font-size: 13px; }
        .btn-danger:hover { box-shadow: 0 8px 20px rgba(239,68,68,.25); }
        .btn-edit { background: var(--warning); padding: 8px 14px; font-size: 13px; }
        .btn-edit:hover { box-shadow: 0 8px 20px rgba(245,158,11,.25); }
        .btn-cancel { background: var(--muted); display: none; }
        .btn-cancel:hover { box-shadow: 0 8px 20px rgba(100,116,139,.25); }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        th, td {
            text-align: left;
            padding: 16px;
            border-bottom: 1px solid var(--line);
            font-size: 14px;
        }
        th {
            font-weight: 700;
            color: var(--muted);
            text-transform: uppercase;
            font-size: 12px;
            letter-spacing: 0.5px;
            background: #f8fafc;
        }
        th:first-child { border-top-left-radius: 12px; }
        th:last-child { border-top-right-radius: 12px; }
        td { color: var(--text); vertical-align: middle; }
        .img-preview {
            width: 100px;
            height: 56px;
            border-radius: 8px;
            object-fit: cover;
            border: 1px solid var(--line);
            background: #fff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        .actions {
            display: flex;
            gap: 8px;
        }
        .empty {
            text-align: center;
            padding: 60px 20px;
            color: var(--muted);
            font-size: 15px;
            background: #f8fafc;
            border-radius: 16px;
            border: 1px dashed var(--line);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>Dialog Slider Management</h1>
    </div>

    <?php if ($can_edit): ?>
    <div class="card" id="form-card">
        <h3 style="margin-bottom:20px; font-size:18px; font-weight:700;" id="form-title">Add Dialog Slider</h3>
        <form method="post" id="slider-form">
            <input type="hidden" name="action" id="form-action" value="add">
            <input type="hidden" name="id" id="form-id" value="">
            
            <div class="form-row">
                <div class="field">
                    <label>Image Source (URL)</label>
                    <input type="text" name="image" id="input-image" placeholder="https://example.com/image.png" required>
                </div>
                <div class="field">
                    <label>Click Action (Link)</label>
                    <input type="text" name="click_link" id="input-link" placeholder="Optional link when clicked">
                </div>
            </div>
            
            <div style="display:flex; gap:10px; margin-top:10px;">
                <button type="submit" class="btn" id="btn-submit">Publish Slider</button>
                <button type="button" class="btn btn-cancel" id="btn-cancel" onclick="resetForm()">Cancel</button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <div class="card" style="padding:0; overflow:hidden;">
        <?php if (count($sliders) > 0): ?>
        <div style="overflow-x:auto;">
            <table>
                <thead>
                    <tr>
                        <th style="padding-left:24px;">Banner Image</th>
                        <th>Target Link</th>
                        <?php if ($can_edit || $can_delete): ?>
                        <th style="padding-right:24px; width:180px;">Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($sliders as $row): ?>
                    <tr>
                        <td style="padding-left:24px;">
                            <img src="<?= htmlspecialchars($row['image']) ?>" alt="Dialog Slider" class="img-preview" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNlMmU4ZjAiLz48L3N2Zz4='">
                        </td>
                        <td>
                            <?php if (!empty($row['click_link'])): ?>
                                <a href="<?= htmlspecialchars($row['click_link']) ?>" target="_blank" style="color:var(--accent); text-decoration:none; font-weight:500;">
                                    <?= htmlspecialchars($row['click_link']) ?>
                                </a>
                            <?php else: ?>
                                <span style="color:var(--muted); font-style:italic;">No link assigned</span>
                            <?php endif; ?>
                        </td>
                        
                        <?php if ($can_edit || $can_delete): ?>
                        <td style="padding-right:24px;">
                            <div class="actions">
                                <?php if ($can_edit): ?>
                                <button class="btn btn-edit" onclick="editData(<?= $row['id'] ?>, '<?= htmlspecialchars(addslashes($row['image'])) ?>', '<?= htmlspecialchars(addslashes($row['click_link'] ?? '')) ?>')">Edit</button>
                                <?php endif; ?>
                                
                                <?php if ($can_delete): ?>
                                <form method="post" onsubmit="return confirm('Are you absolutely sure you want to remove this dialog slider?');" style="margin:0;">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                    <button type="submit" class="btn btn-danger">Delete</button>
                                </form>
                                <?php endif; ?>
                            </div>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php else: ?>
        <div class="empty">
            <div style="font-size:32px; margin-bottom:12px;">🖼️</div>
            No dialog sliders have been added yet.
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if ($can_edit): ?>
<script>
function editData(id, image, link) {
    document.getElementById('form-title').innerText = 'Update Dialog Slider';
    document.getElementById('form-action').value = 'edit';
    document.getElementById('form-id').value = id;
    document.getElementById('input-image').value = image;
    document.getElementById('input-link').value = link;
    document.getElementById('btn-submit').innerText = 'Save Changes';
    document.getElementById('btn-cancel').style.display = 'block';
    document.getElementById('form-card').scrollIntoView({ behavior: 'smooth', block: 'center' });
    document.getElementById('input-image').focus();
}

function resetForm() {
    document.getElementById('form-title').innerText = 'Add Dialog Slider';
    document.getElementById('form-action').value = 'add';
    document.getElementById('form-id').value = '';
    document.getElementById('input-image').value = '';
    document.getElementById('input-link').value = '';
    document.getElementById('btn-submit').innerText = 'Publish Slider';
    document.getElementById('btn-cancel').style.display = 'none';
}
</script>
<?php endif; ?>

</body>
</html>