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

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

/* =============================
   DELETE SINGLE PHOTO
=============================*/
if(isset($_GET['delete'])){
    $id = intval($_GET['delete']);

    $stmt = $conn->prepare("SELECT * FROM photos WHERE id=?");
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $photo = $stmt->get_result()->fetch_assoc();

    if($photo){
        $filePath = "../uploads/".$photo['token']."/".$photo['file_name'];
        if(file_exists($filePath)){
            unlink($filePath);
        }
        $conn->query("DELETE FROM photos WHERE id=".$id);
    }

    header("Location: photos.php");
    exit;
}

/* =============================
   BULK DELETE
=============================*/
if(isset($_POST['bulk_delete']) && !empty($_POST['ids'])){
    foreach($_POST['ids'] as $id){
        $id = intval($id);

        $stmt = $conn->prepare("SELECT * FROM photos WHERE id=?");
        $stmt->bind_param("i",$id);
        $stmt->execute();
        $photo = $stmt->get_result()->fetch_assoc();

        if($photo){
            $filePath = "../uploads/".$photo['token']."/".$photo['file_name'];
            if(file_exists($filePath)){
                unlink($filePath);
            }
            $conn->query("DELETE FROM photos WHERE id=".$id);
        }
    }

    header("Location: photos.php");
    exit;
}

/* =============================
   FILTER + SEARCH
=============================*/
$where = "1";

if(!empty($_GET['token'])){
    $token = $conn->real_escape_string($_GET['token']);
    $where .= " AND token='$token'";
}

if(!empty($_GET['from']) && !empty($_GET['to'])){
    $from = $_GET['from']." 00:00:00";
    $to   = $_GET['to']." 23:59:59";
    $where .= " AND captured_at BETWEEN '$from' AND '$to'";
}

/* =============================
   FETCH LATEST FIRST
=============================*/
$query = "
    SELECT * FROM photos
    WHERE $where
    ORDER BY captured_at DESC
";

$result = $conn->query($query);

/* =============================
   GROUP BY TOKEN
=============================*/
$photos = [];
while($row = $result->fetch_assoc()){
    $photos[$row['token']][] = $row;
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Photo Management</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,#1d4350,#a43931);
}
.card{
    border-radius:20px;
}
.photo-img{
    width:150px;
    border-radius:10px;
    cursor:pointer;
}
</style>
</head>
<body>

<?php include "navbar.php"; ?> <br>

<div class="container-fluid">

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

<h3 class="mb-4 text-center">📸 Photo Management</h3>

<!-- SEARCH -->
<form method="GET" class="row g-3 mb-4">
<div class="col-md-3">
<input type="text" name="token" class="form-control" placeholder="Search by Token">
</div>

<div class="col-md-3">
<input type="date" name="from" class="form-control">
</div>

<div class="col-md-3">
<input type="date" name="to" class="form-control">
</div>

<div class="col-md-3">
<button class="btn btn-primary w-100">Filter</button>
</div>
</form>

<!-- BULK DELETE FORM -->
<form method="POST">

<div class="mb-3">
<button type="submit" name="bulk_delete" class="btn btn-danger">
🗑 Delete Selected
</button>
</div>

<?php foreach($photos as $token => $items): ?>

<div class="card mb-4 shadow-sm">

<div class="card-header bg-dark text-white d-flex justify-content-between">
    <strong>Token: <?php echo $token; ?></strong>

    <a href="download_zip.php?token=<?php echo $token; ?>" 
       class="btn btn-sm btn-success">
       📦 Download ZIP
    </a>
</div>

<div class="card-body">

<div class="row">

<?php foreach($items as $row): 
$imagePath = "../uploads/".$row['token']."/".$row['file_name'];
?>

<div class="col-md-2 mb-3 text-center">

<!-- CHECKBOX -->
<input type="checkbox" name="ids[]" value="<?php echo $row['id']; ?>">

<!-- IMAGE -->
<img src="<?php echo $imagePath; ?>" 
     class="photo-img mb-2"
     onclick="previewImage('<?php echo $imagePath; ?>')">

<div>
<small><?php echo $row['captured_at']; ?></small>
</div>

<!-- BUTTONS ROW -->
<div class="d-flex justify-content-center gap-1 mt-2">

<a href="download_image.php?file=<?php echo urlencode($row['file_name']); ?>&token=<?php echo urlencode($row['token']); ?>" 
class="btn btn-sm btn-primary">
⬇
</a>

<button type="button" 
class="btn btn-sm btn-info"
onclick="previewImage('<?php echo $imagePath; ?>')">
👁
</button>

<a href="?delete=<?php echo $row['id']; ?>" 
class="btn btn-sm btn-danger"
onclick="return confirm('Delete this photo?');">
🗑
</a>

</div>

</div>

<?php endforeach; ?>

</div>

</div>
</div>

<?php endforeach; ?>

</form>

</div>
</div>

<!-- PREVIEW MODAL -->
<div class="modal fade" id="previewModal">
  <div class="modal-dialog modal-dialog-centered modal-lg">
    <div class="modal-content">
      <div class="modal-body text-center">
        <img id="previewImg" src="" style="max-width:100%;">
      </div>
    </div>
  </div>
</div>

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

<script>
function previewImage(src){
    document.getElementById("previewImg").src = src;
    new bootstrap.Modal(document.getElementById('previewModal')).show();
}
</script>

</body>
</html>