<?php
require_once '../includes/config.php';
requireAdmin();
$db = getDB();

// Create table
try {
    $db->exec("CREATE TABLE IF NOT EXISTS banners (
        id INT AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(200) NOT NULL DEFAULT '',
        subtitle VARCHAR(300) DEFAULT '',
        image VARCHAR(255) DEFAULT NULL,
        bg_color VARCHAR(50) DEFAULT 'linear-gradient(135deg,#1a3c8f,#2856c8)',
        pills TEXT DEFAULT NULL,
        link_url VARCHAR(255) DEFAULT NULL,
        is_active TINYINT(1) DEFAULT 1,
        sort_order INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci");
    // Default banner
    if($db->query("SELECT COUNT(*) FROM banners")->fetchColumn()==0) {
        $db->exec("INSERT INTO banners (title,subtitle,pills,sort_order) VALUES
            ('Recharge All Bangladesh Operators!','Complete recharge in just 5 seconds','Grameenphone,Robi,Banglalink,Teletalk',1)");
    }
} catch(Exception $e) {}

$msg = null;
if (isset($_GET['ok'])) $msg = ['ok'=>true,'text'=>'✅ Saved successfully!'];
$uploadDir = '../assets/img/banners/';
@mkdir($uploadDir, 0755, true);

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

    if ($action === 'save') {
        $id       = intval($_POST['id'] ?? 0);
        $title    = sanitize($_POST['title'] ?? '');
        $subtitle = sanitize($_POST['subtitle'] ?? '');
        $bgColor  = sanitize($_POST['bg_color'] ?? 'linear-gradient(135deg,#1a3c8f,#2856c8)');
        $pills    = sanitize($_POST['pills'] ?? '');
        $link     = sanitize($_POST['link_url'] ?? '');
        $sort     = intval($_POST['sort_order'] ?? 0);
        $active   = intval($_POST['is_active'] ?? 1);
        $imgPath  = sanitize($_POST['existing_image'] ?? '');

        if (!empty($_FILES['image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg','jpeg','png','gif','webp'])) {
                $fn = 'banner_'.time().'.'.$ext;
                if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadDir.$fn))
                    $imgPath = 'assets/img/banners/'.$fn;
            }
        }

        if ($id) {
            $db->prepare("UPDATE banners SET title=?,subtitle=?,image=?,bg_color=?,pills=?,link_url=?,sort_order=?,is_active=? WHERE id=?")
               ->execute([$title,$subtitle,$imgPath?:null,$bgColor,$pills,$link,$sort,$active,$id]);
            $msg = ['ok'=>true,'text'=>'Banner updated!'];
            header('Location: banners.php?ok=1'); exit;
        } else {
            $db->prepare("INSERT INTO banners (title,subtitle,image,bg_color,pills,link_url,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)")
               ->execute([$title,$subtitle,$imgPath?:null,$bgColor,$pills,$link,$sort,$active]);
            $msg = ['ok'=>true,'text'=>'Banner added!'];
            header('Location: banners.php?ok=1'); exit;
        }
    }

    if ($action === 'delete') {
        $id = intval($_POST['id']);
        $db->prepare("DELETE FROM banners WHERE id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Deleted!'];
        header('Location: banners.php?ok=1'); exit;
    }

    if ($action === 'toggle') {
        $id = intval($_POST['id']);
        $db->prepare("UPDATE banners SET is_active = 1 - is_active WHERE id=?")->execute([$id]);
        $msg = ['ok'=>true,'text'=>'Updated!'];
        header('Location: banners.php?ok=1'); exit;
    }
}

$banners = $db->query("SELECT * FROM banners ORDER BY sort_order,id")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Banners — Admin</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="../assets/css/admin.css">
<style>
.card{background:white;border-radius:14px;box-shadow:0 2px 8px rgba(0,0,0,0.06);margin-bottom:16px;overflow:hidden}
.card-h{padding:14px 18px;font-size:14px;font-weight:700;border-bottom:1px solid #f5f5f5;display:flex;align-items:center;justify-content:space-between}
.alert{padding:11px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px}
.alert-ok{background:#f0fff4;color:#276749;border:1px solid #c6f6d5}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7}
.btn{padding:8px 14px;border:none;border-radius:9px;font-size:12px;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:5px;text-decoration:none;transition:0.15s}
.btn-primary{background:var(--primary);color:white}
.btn-sm{padding:6px 10px;font-size:12px;border-radius:8px;border:none;font-weight:700;cursor:pointer;display:inline-flex;align-items:center;gap:4px}

/* Banner preview */
.banner-preview{border-radius:14px;padding:18px;position:relative;overflow:hidden;margin-bottom:10px;min-height:90px}
.banner-preview::after{content:'';position:absolute;right:-20px;top:-20px;width:100px;height:100px;background:rgba(255,255,255,0.07);border-radius:50%}
.bp-title{color:white;font-size:15px;font-weight:700;margin-bottom:4px;position:relative;z-index:1}
.bp-sub{color:rgba(255,255,255,0.75);font-size:12px;margin-bottom:10px;position:relative;z-index:1}
.bp-pills{display:flex;gap:6px;flex-wrap:wrap;position:relative;z-index:1}
.bp-pill{background:rgba(255,255,255,0.18);color:white;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:600}
.bp-img{position:absolute;right:0;top:0;height:100%;width:45%;object-fit:cover;opacity:0.3;z-index:0}

/* Banner list */
.banner-row{display:flex;align-items:center;gap:14px;padding:14px 18px;border-bottom:1px solid #f5f5f5}
.banner-row:last-child{border:none}
.banner-thumb{width:80px;height:48px;border-radius:10px;overflow:hidden;flex-shrink:0;position:relative}
.banner-info{flex:1;min-width:0}

/* Modal */
.modal-bg{visibility:hidden;opacity:0;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:99999;display:flex;align-items:center;justify-content:center;padding:16px;transition:opacity 0.2s;pointer-events:none}
.modal-box{background:white;border-radius:18px;width:100%;max-width:520px;padding:24px;max-height:92vh;overflow-y:auto;transform:scale(0.95);transition:transform 0.2s}
.modal-bg.show{visibility:visible;opacity:1;pointer-events:auto}
.modal-bg.show .modal-box{transform:scale(1)}
.modal-title{font-size:16px;font-weight:800;color:#1a1a2e;margin-bottom:18px;display:flex;align-items:center;justify-content:space-between}
.close-btn{background:#f5f5f5;border:none;width:30px;height:30px;border-radius:50%;font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center}
.modal-footer{display:flex;gap:8px;justify-content:flex-end;margin-top:16px;padding-top:14px;border-top:1px solid #f0f0f0}
.fg{margin-bottom:12px}
.fg label{display:block;font-size:11px;font-weight:700;color:#666;text-transform:uppercase;margin-bottom:5px}
.fg input,.fg select,.fg textarea{width:100%;padding:10px 12px;border:2px solid #e8ecf4;border-radius:10px;font-size:13px;outline:none;font-family:inherit}
.fg input:focus,.fg select:focus,.fg textarea:focus{border-color:var(--primary)}
.fg small{font-size:11px;color:#aaa;display:block;margin-top:4px}
.frow2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.sep{font-size:11px;font-weight:800;color:#888;text-transform:uppercase;border-bottom:1px solid #f0f0f0;padding-bottom:6px;margin:14px 0 10px}
.upload-box{border:2px dashed #e8ecf4;border-radius:12px;padding:14px;text-align:center;position:relative;cursor:pointer;transition:0.2s}
.upload-box:hover{border-color:var(--primary);background:#f0f4ff}
.upload-box input{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
/* Color presets */
.color-presets{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:8px}
.cp{width:32px;height:32px;border-radius:8px;cursor:pointer;border:3px solid transparent;transition:0.15s}
.cp:hover,.cp.active{border-color:#1a1a2e;transform:scale(1.1)}
</style>
</head>
<body>
<?php include '../includes/admin_sidebar.php'; ?>
<div class="main">
<div class="topbar">
    <div class="topbar-left">
        <button class="menu-toggle" onclick="openSidebar()"><i class="fas fa-bars"></i></button>
        <span class="topbar-title">🖼️ Banners</span>
    </div>
    <div class="topbar-right">
        <button class="btn btn-primary" onclick="openAdd()"><i class="fas fa-plus"></i> Add Banner</button>
    </div>
</div>
<div class="content">

<?php if($msg): ?><div class="alert <?= $msg['ok']?'alert-ok':'alert-err' ?>"><?= $msg['ok']?'✅':'❌' ?> <?= htmlspecialchars($msg['text']) ?></div><?php endif; ?>

<div class="card">
    <div class="card-h"><span>📋 All Banners <small style="color:#aaa;font-weight:400">(<?= count($banners) ?> total — shown as slideshow)</small></span></div>
    <?php if(empty($banners)): ?>
    <div style="text-align:center;padding:30px;color:#ccc">No banners yet</div>
    <?php else: foreach($banners as $b):
        $pills = array_filter(array_map('trim', explode(',', $b['pills']??'')));
    ?>
    <div class="banner-row">
        <!-- Preview -->
        <div class="banner-thumb">
            <div class="banner-preview" style="background:<?= htmlspecialchars($b['bg_color']) ?>;border-radius:10px;padding:8px;height:100%;margin:0">
                <?php if($b['image']): ?>
                <img src="<?= SITE_URL ?>/<?= htmlspecialchars($b['image']) ?>" style="position:absolute;right:0;top:0;height:100%;width:50%;object-fit:cover;opacity:0.4;border-radius:0 10px 10px 0">
                <?php endif; ?>
                <div style="font-size:9px;color:white;font-weight:700;position:relative;z-index:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap"><?= htmlspecialchars($b['title']) ?></div>
            </div>
        </div>
        <!-- Info -->
        <div class="banner-info">
            <div style="font-size:13px;font-weight:700;color:#1a1a2e;margin-bottom:2px"><?= htmlspecialchars($b['title']) ?></div>
            <?php if($b['subtitle']): ?><div style="font-size:11px;color:#aaa;margin-bottom:4px"><?= htmlspecialchars($b['subtitle']) ?></div><?php endif; ?>
            <div style="display:flex;gap:4px;flex-wrap:wrap">
                <?php foreach($pills as $pill): ?><span style="font-size:10px;background:#f0f4ff;color:var(--primary);padding:2px 7px;border-radius:10px;font-weight:600"><?= htmlspecialchars($pill) ?></span><?php endforeach; ?>
                <?php if($b['image']): ?><span style="font-size:10px;background:#f0fff4;color:#276749;padding:2px 7px;border-radius:10px;font-weight:600">📷 Image</span><?php endif; ?>
            </div>
        </div>
        <!-- Sort -->
        <div style="font-size:11px;color:#aaa;text-align:center;flex-shrink:0">
            <div style="font-weight:700;font-size:13px">#<?= $b['sort_order'] ?></div>
            <div>Sort</div>
        </div>
        <!-- Status -->
        <form method="POST" style="flex-shrink:0">
            <input type="hidden" name="action" value="toggle">
            <input type="hidden" name="id" value="<?= $b['id'] ?>">
            <button type="submit" style="padding:5px 12px;border:none;border-radius:20px;font-size:11px;font-weight:700;cursor:pointer;background:<?= $b['is_active']?'#f0fff4':'#f5f5f5' ?>;color:<?= $b['is_active']?'#276749':'#aaa' ?>">
                <?= $b['is_active']?'✅ Active':'❌ Off' ?>
            </button>
        </form>
        <!-- Actions -->
        <div style="display:flex;gap:6px;flex-shrink:0">
            <button class="btn-sm" style="background:#ebf8ff;color:var(--primary)" onclick='openEdit(<?= htmlspecialchars(json_encode($b),ENT_QUOTES) ?>)'><i class="fas fa-edit"></i></button>
            <form method="POST" onsubmit="return confirm('Delete banner?')" style="display:inline">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= $b['id'] ?>">
                <button type="submit" class="btn-sm" style="background:#fff5f5;color:#e53e3e"><i class="fas fa-trash"></i></button>
            </form>
        </div>
    </div>
    <?php endforeach; endif; ?>
</div>

<!-- Preview section -->
<div class="card">
    <div class="card-h">👁️ Preview</div>
    <div style="padding:16px;max-width:480px">
    <?php foreach($banners as $b): if(!$b['is_active']) continue;
        $pills = array_filter(array_map('trim', explode(',', $b['pills']??'')));
    ?>
    <div class="banner-preview" style="background:<?= htmlspecialchars($b['bg_color']) ?>;margin-bottom:10px">
        <?php if($b['image']): ?>
        <img src="<?= SITE_URL ?>/<?= htmlspecialchars($b['image']) ?>" class="bp-img">
        <?php endif; ?>
        <?php if($b['title']): ?><div class="bp-title"><?= htmlspecialchars($b['title']) ?></div><?php endif; ?>
        <?php if($b['subtitle']): ?><div class="bp-sub"><?= htmlspecialchars($b['subtitle']) ?></div><?php endif; ?>
        <?php if($pills): ?>
        <div class="bp-pills"><?php foreach($pills as $p): ?><span class="bp-pill"><?= htmlspecialchars($p) ?></span><?php endforeach; ?></div>
        <?php endif; ?>
    </div>
    <?php endforeach; ?>
    </div>
</div>

</div></div>

<!-- Add/Edit Modal -->
<div class="modal-bg" id="bannerModal">
<div class="modal-box">
    <div class="modal-title"><span id="modalTitle">Add Banner</span><button class="close-btn" onclick="closeModal()">✕</button></div>
    <form method="POST" enctype="multipart/form-data" id="bannerForm">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" id="fId" value="">
        <input type="hidden" name="existing_image" id="fExImg" value="">

        <div class="sep">📝 Content</div>
        <div class="fg">
            <label>Title</label>
            <input name="title" id="fTitle" placeholder="Recharge All Bangladesh Operators!">
        </div>
        <div class="fg">
            <label>Subtitle</label>
            <input name="subtitle" id="fSubtitle" placeholder="Complete recharge in just 5 seconds">
        </div>
        <div class="fg">
            <label>Pills / Tags <small style="text-transform:none;font-weight:400">(comma separated)</small></label>
            <input name="pills" id="fPills" placeholder="Grameenphone,Robi,Banglalink,Teletalk">
            <small>Comma দিয়ে আলাদা করুন</small>
        </div>
        <div class="fg">
            <label>Link URL <small style="text-transform:none;font-weight:400">(optional)</small></label>
            <input name="link_url" id="fLink" placeholder="topup.php">
        </div>

        <div class="sep">🎨 Background</div>
        <div class="fg">
            <label>Background Color / Gradient</label>
            <!-- Color presets -->
            <div class="color-presets" id="colorPresets">
                <?php
                $presets = [
                    'linear-gradient(135deg,#1a3c8f,#2856c8)' => '#1a3c8f',
                    'linear-gradient(135deg,#276749,#38a169)' => '#276749',
                    'linear-gradient(135deg,#744210,#d69e2e)' => '#744210',
                    'linear-gradient(135deg,#702459,#b83280)' => '#702459',
                    'linear-gradient(135deg,#2c7a7b,#319795)' => '#2c7a7b',
                    'linear-gradient(135deg,#e53e3e,#fc8181)' => '#e53e3e',
                    'linear-gradient(135deg,#553c9a,#805ad5)' => '#553c9a',
                    'linear-gradient(135deg,#0d1f4e,#1a3c8f)' => '#0d1f4e',
                ];
                foreach($presets as $gradient=>$solid): ?>
                <div class="cp" style="background:<?= $gradient ?>" data-gradient="<?= htmlspecialchars($gradient,ENT_QUOTES) ?>" onclick="setColor(this)" title="<?= $gradient ?>"></div>
                <?php endforeach; ?>
            </div>
            <input name="bg_color" id="fBgColor" value="linear-gradient(135deg,#1a3c8f,#2856c8)" placeholder="linear-gradient(135deg,#1a3c8f,#2856c8)">
            <small>Gradient বা solid color — যেকোনো CSS value</small>
        </div>

        <div class="sep">📷 Image (Optional)</div>
        <div class="fg">
            <div class="upload-box" id="uploadBox">
                <input type="file" name="image" accept="image/*" onchange="previewImg(this)">
                <div id="uploadContent">
                    <i class="fas fa-image" style="font-size:24px;color:#ddd;display:block;margin-bottom:6px"></i>
                    <div style="font-size:12px;color:#aaa">Click to upload image</div>
                    <div style="font-size:11px;color:#ccc;margin-top:3px">JPG, PNG, WebP — image will appear on the right side</div>
                </div>
            </div>
            <div id="imgPreviewWrap" style="display:none;margin-top:8px;position:relative">
                <img id="imgPreview" style="width:100%;border-radius:10px;max-height:120px;object-fit:cover">
                <button type="button" onclick="clearImg()" style="position:absolute;top:6px;right:6px;background:rgba(0,0,0,0.5);border:none;color:white;width:26px;height:26px;border-radius:50%;cursor:pointer;font-size:12px">✕</button>
            </div>
        </div>

        <div class="sep">⚙️ Settings</div>
        <div class="frow2">
            <div class="fg">
                <label>Sort Order</label>
                <input type="number" name="sort_order" id="fSort" value="0">
                <small>Low number = first</small>
            </div>
            <div class="fg">
                <label>Status</label>
                <select name="is_active" id="fActive">
                    <option value="1">✅ Active</option>
                    <option value="0">❌ Inactive</option>
                </select>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn" style="background:#f5f5f5;color:#555" onclick="closeModal()">Cancel</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Save Banner</button>
        </div>
    </form>
</div>
</div>

<script>
function openAdd() {
    document.getElementById('modalTitle').textContent = 'Add Banner';
    document.getElementById('bannerForm').reset();
    document.getElementById('fId').value = '';
    document.getElementById('fExImg').value = '';
    document.getElementById('fBgColor').value = 'linear-gradient(135deg,#1a3c8f,#2856c8)';
    document.getElementById('imgPreviewWrap').style.display = 'none';
    document.getElementById('uploadContent').style.display = 'block';
    document.querySelectorAll('.cp').forEach(c=>c.classList.remove('active'));
    document.querySelector('.cp').classList.add('active');
    openModal();
}
function openEdit(b) {
    document.getElementById('modalTitle').textContent = 'Edit Banner';
    document.getElementById('fId').value = b.id;
    document.getElementById('fTitle').value = b.title || '';
    document.getElementById('fSubtitle').value = b.subtitle || '';
    document.getElementById('fPills').value = b.pills || '';
    document.getElementById('fLink').value = b.link_url || '';
    document.getElementById('fBgColor').value = b.bg_color || 'linear-gradient(135deg,#1a3c8f,#2856c8)';
    document.getElementById('fSort').value = b.sort_order || 0;
    document.getElementById('fActive').value = b.is_active;
    document.getElementById('fExImg').value = b.image || '';
    // Image preview
    if (b.image) {
        document.getElementById('imgPreview').src = '<?= SITE_URL ?>/' + b.image;
        document.getElementById('imgPreviewWrap').style.display = 'block';
        document.getElementById('uploadContent').style.display = 'none';
    } else {
        document.getElementById('imgPreviewWrap').style.display = 'none';
        document.getElementById('uploadContent').style.display = 'block';
    }
    // Highlight matching preset
    document.querySelectorAll('.cp').forEach(c => {
        c.classList.toggle('active', c.dataset.gradient === b.bg_color);
    });
    openModal();
}
function openModal() { document.getElementById('bannerModal').classList.add('show'); }
function closeModal() { document.getElementById('bannerModal').classList.remove('show'); }
document.getElementById('bannerModal').addEventListener('click', e => { if(e.target===document.getElementById('bannerModal')) closeModal(); });

function setColor(el) {
    document.querySelectorAll('.cp').forEach(c=>c.classList.remove('active'));
    el.classList.add('active');
    document.getElementById('fBgColor').value = el.dataset.gradient;
}
function previewImg(input) {
    if (!input.files || !input.files[0]) return;
    const reader = new FileReader();
    reader.onload = e => {
        document.getElementById('imgPreview').src = e.target.result;
        document.getElementById('imgPreviewWrap').style.display = 'block';
        document.getElementById('uploadContent').style.display = 'none';
    };
    reader.readAsDataURL(input.files[0]);
}
function clearImg() {
    document.getElementById('imgPreviewWrap').style.display = 'none';
    document.getElementById('uploadContent').style.display = 'block';
    document.getElementById('fExImg').value = '';
    document.querySelector('input[name=image]').value = '';
}
</script>
</body>
</html>
