<?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 slider_read, slider_edit, 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['slider_read'] ?? '')) === 'yes';
        $can_edit = strtolower(trim($row['slider_edit'] ?? '')) === 'yes';
        $can_delete = strtolower(trim($row['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_url = trim($_POST['image_url'] ?? '');
        $activity_link = trim($_POST['activity_link'] ?? '');
        $date = date('Y-m-d H:i:s');
        
        if ($image_url !== '') {
            $sql = "INSERT INTO imagesliders (image_url, activity_link, created_at) VALUES (?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sss", $image_url, $activity_link, $date);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($action === 'edit' && $can_edit) {
        $id = (int)($_POST['id'] ?? 0);
        $image_url = trim($_POST['image_url'] ?? '');
        $activity_link = trim($_POST['activity_link'] ?? '');
        
        if ($id > 0 && $image_url !== '') {
            $sql = "UPDATE imagesliders SET image_url = ?, activity_link = ? WHERE id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ssi", $image_url, $activity_link, $id);
            $stmt->execute();
            $stmt->close();
        }
    } elseif ($action === 'delete' && $can_delete) {
        $id = (int)($_POST['id'] ?? 0);
        
        if ($id > 0) {
            $sql = "DELETE FROM imagesliders 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 imagesliders 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>Manage Image Sliders</title>
    <style>
        :root {
            --bg: #f4f7fb;
            --card: #ffffff;
            --text: #102033;
            --muted: #5f6f82;
            --line: #dbe5f0;
            --accent: #2563eb;
            --accent2: #7c3aed;
            --danger: #ef4444;
            --shadow: 0 10px 40px rgba(16, 32, 51, .06);
            --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: 26px;
            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;
        }
        input[type="text"] {
            width: 100%;
            border: 1px solid var(--line);
            background: #fff;
            color: var(--text);
            border-radius: 12px;
            padding: 12px 14px;
            font-size: 14px;
            outline: none;
            transition: .2s ease;
        }
        input:focus {
            border-color: rgba(37,99,235,.65);
            box-shadow: 0 0 0 4px rgba(37,99,235,.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(37,99,235,.20); }
        .btn-danger {
            background: var(--danger);
            padding: 8px 12px;
            font-size: 12px;
        }
        .btn-danger:hover { box-shadow: 0 8px 20px rgba(239,68,68,.20); }
        .btn-edit {
            background: #f59e0b;
            padding: 8px 12px;
            font-size: 12px;
        }
        .btn-edit:hover { box-shadow: 0 8px 20px rgba(245,158,11,.20); }
        .btn-cancel {
            background: var(--muted);
            display: none;
        }
        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;
        }
        td { color: var(--text); }
        .img-preview {
            width: 80px;
            height: 50px;
            border-radius: 8px;
            object-fit: cover;
            border: 1px solid var(--line);
            background: #f8fafc;
        }
        .actions {
            display: flex;
            gap: 8px;
        }
        .empty {
            text-align: center;
            padding: 40px;
            color: var(--muted);
        }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <h1>Manage Image Sliders</h1>
    </div>

    <?php if ($can_edit): ?>
    <div class="card" id="form-card">
        <h3 style="margin-bottom:20px; font-size:18px;" id="form-title">Add New 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 URL</label>
                    <input type="text" name="image_url" id="input-url" required>
                </div>
                <div class="field">
                    <label>Activity Link</label>
                    <input type="text" name="activity_link" id="input-link">
                </div>
            </div>
            
            <div style="display:flex; gap:10px; margin-top:10px;">
                <button type="submit" class="btn" id="btn-submit">Save Slider</button>
                <button type="button" class="btn btn-cancel" id="btn-cancel" onclick="resetForm()">Cancel Edit</button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <div class="card">
        <?php if (count($sliders) > 0): ?>
        <div style="overflow-x:auto;">
            <table>
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Activity Link</th>
                        <th>Created At</th>
                        <?php if ($can_edit || $can_delete): ?>
                        <th>Actions</th>
                        <?php endif; ?>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($sliders as $row): ?>
                    <tr>
                        <td>
                            <img src="<?= htmlspecialchars($row['image_url']) ?>" alt="Slider" class="img-preview" onerror="this.src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9IiNlMmU4ZjAiLz48L3N2Zz4='">
                        </td>
                        <td><?= htmlspecialchars($row['activity_link'] ?? 'N/A') ?></td>
                        <td style="color:var(--muted); font-size:13px;"><?= htmlspecialchars($row['created_at']) ?></td>
                        
                        <?php if ($can_edit || $can_delete): ?>
                        <td>
                            <div class="actions">
                                <?php if ($can_edit): ?>
                                <button class="btn btn-edit" onclick="editData(<?= $row['id'] ?>, '<?= htmlspecialchars(addslashes($row['image_url'])) ?>', '<?= htmlspecialchars(addslashes($row['activity_link'] ?? '')) ?>')">Edit</button>
                                <?php endif; ?>
                                
                                <?php if ($can_delete): ?>
                                <form method="post" onsubmit="return confirm('Are you sure you want to delete this 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">No sliders found.</div>
        <?php endif; ?>
    </div>
</div>

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

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

</body>
</html>