<?php 
include ('includes/header.php');

// table name
$table_name = "ads";

// current file
$base_file = basename($_SERVER["SCRIPT_NAME"]);

// create table if not exists
$adb->exec("CREATE TABLE IF NOT EXISTS {$table_name}(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    title VARCHAR(100),
    url   TEXT
)");

// select all
$res = $adb->query("SELECT * FROM {$table_name}");

// update
@$resU = $adb->query("SELECT * FROM {$table_name} WHERE id='".intval($_GET['update'] ?? 0)."'");
@$rowU = $resU ? $resU->fetchArray() : null;

if (isset($_POST['submitU'])) {
    $id    = intval($_POST['id']);
    $title = SQLite3::escapeString($_POST['title']);
    $url   = SQLite3::escapeString($_POST['url']);

    $adb->exec("UPDATE {$table_name} SET title='{$title}', url='{$url}' WHERE id='{$id}'");
    $adb->close();
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}

// insert new
if (isset($_POST['submit'])) {
    $title = SQLite3::escapeString($_POST['title']);
    $url   = SQLite3::escapeString($_POST['url']);

    $adb->exec("INSERT INTO {$table_name}(title, url) VALUES('{$title}', '{$url}')");
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}

// delete
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $adb->exec("DELETE FROM {$table_name} WHERE id={$id}");
    echo "<script>window.location.href='ads.php';</script>";
    exit;
}
?>
<style>
/* layout + theme */
.banner-wrapper {
    max-width: 1100px;
    margin: 30px auto 60px;
}
.banner-card {
    background: #111827;
    border-radius: 14px;
    box-shadow: 0 22px 55px rgba(0,0,0,0.6);
    padding: 22px 24px 26px;
}
.banner-header {
    display:flex;
    justify-content:space-between;
    align-items:center;
    margin-bottom:14px;
}
.banner-header h1 {
    color:#e5e7eb;
    font-size:1.4rem;
    letter-spacing:.12em;
    text-transform:uppercase;
    font-weight:800;
}
.btn-create {
    background: #22c55e;
    border:none;
    color:#020617;
    font-weight:700;
    border-radius:999px;
    padding:8px 20px;
    font-size:.9rem;
}
.btn-create:hover { opacity:.9; }

/* table */
.table-dark-ads thead {
    background:#020617;
    color:#9ca3af;
    border-bottom:1px solid #1f2937;
}
.table-dark-ads tbody tr {
    background:#0b1120;
    color:#e5e7eb;
}
.table-dark-ads tbody tr:nth-child(even){
    background:#020617;
}
.table-dark-ads td, .table-dark-ads th {
    border-color:#1f2937;
    vertical-align:middle;
    font-size:.85rem;
}

/* action buttons */
.btn-edit {
    background:#2563eb;
    border:none;
    color:#f9fafb;
    padding:4px 10px;
    font-size:.8rem;
    border-radius:999px;
}
.btn-delete {
    background:#ef4444;
    border:none;
    color:#f9fafb;
    padding:4px 10px;
    font-size:.8rem;
    border-radius:999px;
}
.btn-edit:hover, .btn-delete:hover { opacity:.9; }

.action-buttons {
    display:flex;
    gap:8px;
    justify-content:center;
}

/* forms */
.card-banner-form {
    background:#111827;
    border-radius:14px;
    box-shadow:0 22px 55px rgba(0,0,0,0.6);
    color:#e5e7eb;
}
.card-banner-form .card-header {
    border-bottom:1px solid #1f2937;
}
.card-banner-form label {
    font-size:.8rem;
    text-transform:uppercase;
    letter-spacing:.08em;
    color:#9ca3af;
}
.card-banner-form .form-control {
    background:#020617;
    border:1px solid #374151;
    color:#e5e7eb;
}
.card-banner-form .form-control:focus {
    border-color:#22c55e;
    box-shadow:none;
}

/* modal */
#confirm-delete .modal-content {
    background:#020617;
    color:#e5e7eb;
}
#confirm-delete .modal-header h2 {
    color:#f9fafb;
}
</style>

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<h2>Confirm</h2>
			</div>
			<div class="modal-body">
				Do you really want to delete this banner?
			</div>
			<div class="modal-footer">
				<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
				<a class="btn btn-delete btn-ok">Delete</a>
			</div>
		</div>
	</div>
</div>

<?php
if (isset($_GET['create'])) {
?>
    <div class="banner-wrapper">
        <div class="card card-banner-form">
            <div class="card-header text-center">
                <h2>Add New Banner</h2>
            </div>
            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label>Name</label>
                        <input class="form-control" type="text" name="title" required>
                    </div>
                    <div class="form-group">
                        <label>Image URL (GIF, PNG, JPG, SVG, MP4, WEBM)</label>
                        <input class="form-control" type="text" name="url" required>
                    </div>
                    <button type="submit" name="submit" class="btn btn-create">Save</button>
                </form>
            </div>
        </div>
    </div>

<?php 
} elseif (isset($_GET['update']) && $rowU) { 
?>
    <div class="banner-wrapper">
        <div class="card card-banner-form">
            <div class="card-header text-center">
                <h2>Edit Banner</h2>
            </div>
            <div class="card-body">
                <form method="post">
                    <input type="hidden" class="form-control" name="id" value="<?=intval($_GET['update'])?>">
                    <div class="form-group">
                        <label>Name</label>
                        <input type="text" name="title" class="form-control" value="<?=htmlspecialchars($rowU['title'])?>" required>
                    </div>
                    <div class="form-group">
                        <label>Image URL (GIF, PNG, JPG, SVG, MP4, WEBM)</label>
                        <input type="text" class="form-control" name="url" value="<?=htmlspecialchars($rowU['url'])?>" required>
                    </div>
                    <button type="submit" name="submitU" class="btn btn-create">Save</button>
                </form>
            </div>
        </div>
    </div>

<?php
} else {
?>
    <div class="banner-wrapper">
        <div class="banner-card">
            <div class="banner-header">
                <h1>BANNERS</h1>
                <a id="button" href="./<?=$base_file?>?create" class="btn btn-create">Create New</a>
            </div>

            <div class="table-responsive">
                <table class="table table-dark-ads table-sm">
                    <thead>
                        <tr>
                            <th style="width:60px;">ID</th>
                            <th style="width:180px;">Name</th>
                            <th>Image URL</th>
                            <th style="width:130px;">Preview</th>
                            <th style="width:150px; text-align:center;">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php while ($row = $res->fetchArray()) { ?>
                        <tr>
                            <td><?=intval($row['id'])?></td>
                            <td <?php if (strpos($row['url'], '.mp4') !== false || strpos($row['url'], '.webm') !== false || strpos($row['url'], '.gif') !== false || strpos($row['url'], '.ogg') !== false) {echo 'style="color:#f97316;"';} ?>>
                                <?=htmlspecialchars($row['title'])?>
                            </td>
                            <td><?=htmlspecialchars($row['url'])?></td>
                            <td>
                                <?php if (strpos($row['url'], '.mp4') !== false || strpos($row['url'], '.webm') !== false || strpos($row['url'], '.ogg') !== false) { ?>
                                    <video src="<?=htmlspecialchars($row['url'])?>" controls width="110" autoplay muted loop></video>
                                <?php } elseif (strpos($row['url'], '.jpg') !== false || strpos($row['url'], '.jpeg') !== false || strpos($row['url'], '.png') !== false || strpos($row['url'], '.gif') !== false) { ?>
                                    <img src="<?=htmlspecialchars($row['url'])?>" width="110" />
                                <?php } ?>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a class="btn-edit btn btn-sm" href="<?=$base_file?>?update=<?=intval($row['id'])?>">
                                        <i class="fa fa-pencil-square-o"></i>
                                    </a>
                                    <a class="btn-delete btn btn-sm" href="#" data-href="<?=$base_file?>?delete=<?=intval($row['id'])?>" data-toggle="modal" data-target="#confirm-delete">
                                        <i class="fa fa-trash-o"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php } ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>
<?php } ?>

<?php include ('includes/footer.php');?>

<script type="text/javascript">
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>
</body>
</html>
