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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id       = (int)($_POST['id'] ?? 0);
    $title    = sanitize($_POST['title'] ?? '');
    $subtitle = sanitize($_POST['subtitle'] ?? '');
    $link     = sanitize($_POST['link'] ?? '');
    $position = sanitize($_POST['position'] ?? 'home_hero');
    $sort     = (int)($_POST['sort_order'] ?? 0);
    $status   = (int)($_POST['status'] ?? 1);

    $imagePath = $id ? ($db->prepare("SELECT image FROM banners WHERE id=?")->execute([$id]) ? null : null) : null;
    if ($id) { $s=$db->prepare("SELECT image FROM banners WHERE id=?");$s->execute([$id]);$row=$s->fetch();$imagePath=$row['image']??null; }

    if (!empty($_FILES['image']['name'])) {
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext,['jpg','jpeg','png','gif','webp'])) {
            $dir = __DIR__ . '/../assets/uploads/banners/';
            if (!is_dir($dir)) mkdir($dir,0755,true);
            $fname = time().'_banner.'.$ext;
            if (move_uploaded_file($_FILES['image']['tmp_name'],$dir.$fname)) $imagePath=$fname;
        }
    }
    if ($id) {
        $db->prepare("UPDATE banners SET title=?,subtitle=?,image=?,link=?,position=?,sort_order=?,status=? WHERE id=?")->execute([$title,$subtitle,$imagePath,$link,$position,$sort,$status,$id]);
        setAdminFlash('success','Banner updated.');
    } else {
        $db->prepare("INSERT INTO banners (title,subtitle,image,link,position,sort_order,status) VALUES (?,?,?,?,?,?,?)")->execute([$title,$subtitle,$imagePath,$link,$position,$sort,$status]);
        setAdminFlash('success','Banner added.');
    }
    header('Location: /admin/banners.php'); exit;
}
if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM banners WHERE id=?")->execute([(int)$_GET['delete']]);
    setAdminFlash('success','Banner deleted.'); header('Location: /admin/banners.php'); exit;
}
if (isset($_GET['toggle'])) {
    $db->prepare("UPDATE banners SET status=1-status WHERE id=?")->execute([(int)$_GET['toggle']]);
    header('Location: /admin/banners.php'); exit;
}

$editB = null;
if (isset($_GET['edit'])) { $s=$db->prepare("SELECT * FROM banners WHERE id=?");$s->execute([(int)$_GET['edit']]);$editB=$s->fetch(); }

$banners  = $db->query("SELECT * FROM banners ORDER BY sort_order, id DESC")->fetchAll();
$positions = ['home_hero'=>'Home Hero','home_middle'=>'Home Middle','lawyers_top'=>'Lawyers Page Top','blog_sidebar'=>'Blog Sidebar'];

adminHead('Banner Management');
adminSidebar('banners');
?>
<div class="adm-main">
<?php adminTopbar('Banner Management'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<div class="row g-4">
    <!-- Form -->
    <div class="col-lg-4">
        <div class="adm-card" style="overflow:visible;">
            <div class="adm-card-head"><h6><?= $editB ? 'Edit Banner' : 'Add New Banner' ?></h6></div>
            <div style="padding:22px;">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editB): ?><input type="hidden" name="id" value="<?= $editB['id'] ?>"><?php endif; ?>
                    <div style="margin-bottom:13px;">
                        <label class="lbl">Title</label>
                        <input type="text" name="title" class="form-ctrl" value="<?= htmlspecialchars($editB['title'] ?? '') ?>" placeholder="Banner heading">
                    </div>
                    <div style="margin-bottom:13px;">
                        <label class="lbl">Subtitle / Description</label>
                        <textarea name="subtitle" class="form-ctrl" rows="2"><?= htmlspecialchars($editB['subtitle'] ?? '') ?></textarea>
                    </div>
                    <div style="margin-bottom:13px;">
                        <label class="lbl">Banner Image</label>
                        <?php if (!empty($editB['image'])): ?>
                        <div style="margin-bottom:8px;"><img src="/meevakeel/assets/uploads/banners/<?= $editB['image'] ?>" style="width:100%;max-height:100px;object-fit:cover;border-radius:8px;border:1px solid var(--border);" onerror="this.style.display='none'"></div>
                        <?php endif; ?>
                        <input type="file" name="image" class="form-ctrl" style="padding:7px;" accept="image/*">
                        <div style="font-size:.72rem;color:#718096;margin-top:4px;">JPG, PNG, GIF. Recommended: 1200×400px</div>
                    </div>
                    <div style="margin-bottom:13px;">
                        <label class="lbl">Link URL</label>
                        <input type="text" name="link" class="form-ctrl" value="<?= htmlspecialchars($editB['link'] ?? '') ?>" placeholder="/lawyers.php or https://...">
                    </div>
                    <div style="margin-bottom:13px;">
                        <label class="lbl">Position</label>
                        <select name="position" class="form-ctrl">
                            <?php foreach ($positions as $val=>$lbl): ?>
                            <option value="<?= $val ?>" <?= ($editB['position']??'home_hero')===$val?'selected':'' ?>><?= $lbl ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row g-2 mb-4">
                        <div class="col-6">
                            <label class="lbl">Sort Order</label>
                            <input type="number" name="sort_order" class="form-ctrl" value="<?= $editB['sort_order'] ?? 0 ?>" min="0">
                        </div>
                        <div class="col-6">
                            <label class="lbl">Status</label>
                            <select name="status" class="form-ctrl">
                                <option value="1" <?= ($editB['status']??1)==1?'selected':'' ?>>Active</option>
                                <option value="0" <?= ($editB['status']??1)==0?'selected':'' ?>>Inactive</option>
                            </select>
                        </div>
                    </div>
                    <button type="submit" class="btn-gold w-100" style="width:100%;padding:11px;"><?= $editB ? 'Update' : 'Add' ?> Banner</button>
                    <?php if ($editB): ?><a href="/admin/banners.php" style="display:block;text-align:center;margin-top:10px;font-size:.82rem;color:#718096;">Cancel</a><?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- List -->
    <div class="col-lg-8">
        <div class="adm-card">
            <div class="adm-card-head"><h6>All Banners (<?= count($banners) ?>)</h6></div>
            <?php if (empty($banners)): ?>
            <div style="text-align:center;padding:50px;color:#718096;">No banners yet. Add your first banner.</div>
            <?php else: ?>
            <div style="padding:16px;display:grid;gap:14px;">
            <?php foreach ($banners as $b): ?>
            <div style="background:var(--off-white);border-radius:12px;padding:16px;border:1px solid var(--border);display:flex;gap:16px;align-items:center;flex-wrap:wrap;">
                <!-- Thumbnail -->
                <div style="width:120px;height:70px;min-width:120px;border-radius:8px;overflow:hidden;background:#e2e8f0;display:flex;align-items:center;justify-content:center;">
                    <?php if ($b['image']): ?>
                    <img src="/meevakeel/assets/uploads/banners/<?= $b['image'] ?>" style="width:100%;height:100%;object-fit:cover;" onerror="this.outerHTML='<div style=\'color:#718096;font-size:.7rem;text-align:center;padding:10px;\'>No preview</div>'">
                    <?php else: ?>
                    <div style="font-size:.72rem;color:#718096;text-align:center;padding:8px;"><i class="fas fa-image fa-lg mb-1" style="display:block;"></i>No image</div>
                    <?php endif; ?>
                </div>
                <!-- Info -->
                <div style="flex:1;min-width:160px;">
                    <div style="font-weight:700;font-size:.88rem;color:var(--primary);"><?= htmlspecialchars($b['title'] ?: 'Untitled Banner') ?></div>
                    <div style="font-size:.75rem;color:#718096;margin-top:3px;"><?= $positions[$b['position']] ?? $b['position'] ?> · Order: <?= $b['sort_order'] ?></div>
                    <?php if ($b['link']): ?><div style="font-size:.72rem;color:var(--primary);margin-top:3px;">→ <?= htmlspecialchars($b['link']) ?></div><?php endif; ?>
                </div>
                <!-- Status + actions -->
                <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap;">
                    <a href="?toggle=<?= $b['id'] ?>" style="font-size:.72rem;padding:4px 10px;border-radius:50px;font-weight:700;text-decoration:none;background:<?= $b['status']?'rgba(40,167,69,.1)':'rgba(220,53,69,.08)' ?>;color:<?= $b['status']?'#1a7a34':'#c0392b' ?>;"><?= $b['status']?'Active':'Inactive' ?></a>
                    <a href="?edit=<?= $b['id'] ?>" class="btn-sm-edit">Edit</a>
                    <a href="?delete=<?= $b['id'] ?>" class="btn-sm-del confirm-del">Del</a>
                </div>
            </div>
            <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>
</div></div>
<?php adminFoot(); ?>