<?php
session_start();
include "../db.php";

if(!isset($_SESSION['admin'])){
    header("Location: login.php");
    exit;
}

/* =============================
   DEACTIVATE LINK
=============================*/
if(isset($_GET['deactivate'])){
    $id = intval($_GET['deactivate']);
    $stmt = $conn->prepare("UPDATE capture_links SET is_active=0 WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    header("Location: manage_links.php");
    exit;
}

/* =============================
   FETCH LINKS
=============================*/
$result = $conn->query("
    SELECT * FROM capture_links 
    ORDER BY id DESC
");
?>

<!DOCTYPE html>
<html>
<head>
<title>Manage Capture Links</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body{
    background: linear-gradient(135deg,#1e3c72,#2a5298);
    min-height:100vh;
    /*padding:40px;*/
}
.card{
    border-radius:15px;
}
</style>
</head>
<body>
<?php include "navbar.php"; ?> <br>
<div class="container-fluid">

<div class="card shadow-lg p-4">

<h3 class="mb-4 text-center">📋 Manage Capture Links</h3>

<div class="table-responsive">

<table class="table table-bordered table-striped align-middle">

<thead class="table-dark">
<tr>
<th>ID</th>
<th>Token</th>
<th>Expiry</th>
<th>Status</th>
<th>Copy</th>
<th>Action</th>
</tr>
</thead>

<tbody>

<?php while($row = $result->fetch_assoc()):

$now = date("Y-m-d H:i:s");

$isExpired = ($row['expires_at'] < $now);
$isActive  = ($row['is_active'] == 1 && !$isExpired);

$link = "https://img.urlnowshort.com/capture.php?token=".$row['token'];

?>

<tr>

<td><?php echo $row['id']; ?></td>

<td style="font-size:12px;"><?php echo $row['token']; ?></td>

<td><?php echo $row['expires_at']; ?></td>

<td>
<?php if($isActive){ ?>
    <span class="badge bg-success">Active</span>
<?php } elseif($isExpired){ ?>
    <span class="badge bg-warning text-dark">Expired</span>
<?php } else { ?>
    <span class="badge bg-danger">Deactivated</span>
<?php } ?>
</td>

<td>
<button class="btn btn-sm btn-primary" onclick="copyLink('<?php echo $link; ?>')">
Copy
</button>
</td>

<td>
<?php if($isActive){ ?>
<a href="?deactivate=<?php echo $row['id']; ?>" 
   class="btn btn-sm btn-danger"
   onclick="return confirm('Deactivate this link?');">
Deactivate
</a>
<?php } else { ?>
<span class="text-muted">—</span>
<?php } ?>
</td>

</tr>

<?php endwhile; ?>

</tbody>
</table>

</div>

</div>

</div>

<script>
function copyLink(link){
    navigator.clipboard.writeText(link)
    .then(()=> alert("Link copied!"))
    .catch(()=> alert("Copy failed"));
}
</script>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>