<?php
include "db.php";

$token = $_GET['token'] ?? '';

if(empty($token)){
    die("Invalid Access");
}

$stmt = $conn->prepare("
    SELECT * FROM capture_links 
    WHERE token=? 
    AND is_active=1 
    AND expires_at > NOW()
");
$stmt->bind_param("s", $token);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows == 0){
    die("Link Expired or Invalid");
}
?>

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Capture System</title>

<style>

body{
font-family:Arial;
background:#f5f5f5;
text-align:center;
margin:0;
padding:20px;
}

video{
width:100%;
max-width:420px;
border-radius:10px;
}

button{
padding:10px 18px;
margin:5px;
border:none;
border-radius:6px;
cursor:pointer;
}

.capture{background:#28a745;color:white;}
.upload{background:#007bff;color:white;}
.switch{background:#ff9800;color:white;}

.gallery{
display:flex;
flex-wrap:wrap;
justify-content:center;
margin-top:20px;
}

.img-box{
position:relative;
margin:8px;
}

.img-box img{
width:120px;
border-radius:8px;
}

.delete{
position:absolute;
bottom:4px;
left:4px;
background:red;
color:white;
font-size:11px;
padding:4px 6px;
}

.progress{
width:100%;
max-width:400px;
margin:auto;
background:#ddd;
border-radius:10px;
overflow:hidden;
margin-top:15px;
}

.progress-bar{
height:18px;
background:#4caf50;
width:0%;
}

/*.map{*/
/*margin-top:15px;*/
/*}*/

</style>
</head>

<body>

<h2>Smart Capture System</h2>

<video id="video" autoplay playsinline></video>

<br>

<button class="capture" onclick="capturePhoto()">Capture</button>
<button class="switch" onclick="switchCamera()">Switch Camera</button>

<canvas id="canvas" style="display:none;"></canvas>

<h3>Captured Photos</h3>

<div id="gallery" class="gallery"></div>

<button class="upload" onclick="uploadPhotos()">Upload Photos</button>

<div class="progress">
<div id="progressBar" class="progress-bar"></div>
</div>

<!--<div class="map" id="map"></div>-->

<script>

let facing = "environment";
let capturedImages = [];
let latitude = "";
let longitude = "";
let currentStream = null;

/* ==========================
   GPS LOCATION
========================== */

function getLocation(){
return new Promise((resolve,reject)=>{

navigator.geolocation.getCurrentPosition(
pos=>{
latitude = pos.coords.latitude;
longitude = pos.coords.longitude;
resolve();
},
err=>{
alert("Location permission denied");
reject();
},
{
enableHighAccuracy:true,
timeout:10000
}
);

});
}

/* ==========================
   CAMERA START
========================== */

async function startCamera(){

try{

if(currentStream){
currentStream.getTracks().forEach(track => track.stop());
}

const stream = await navigator.mediaDevices.getUserMedia({
video:{facingMode:facing},
audio:false
});

currentStream = stream;

const video = document.getElementById("video");
video.srcObject = stream;

await video.play();

}catch(e){
alert("Camera error: " + e.message);
}

}

window.onload = ()=>{
startCamera();
getLocation();
};

/* ==========================
   SWITCH CAMERA
========================== */

function switchCamera(){
facing = facing==="environment" ? "user" : "environment";
startCamera();
}

/* ==========================
   DRAW WITH REAL FIX
========================== */

function drawImage(ctx, video){

let vw = video.videoWidth;
let vh = video.videoHeight;

// Detect device orientation
let isPortrait = window.innerHeight > window.innerWidth;

if(isPortrait){
    // PORTRAIT MODE
    ctx.canvas.width = vh;
    ctx.canvas.height = vw;

    ctx.save();
    ctx.translate(vh/2, vw/2);
    ctx.rotate(90 * Math.PI / 180);
    ctx.drawImage(video, -vw/2, -vh/2, vw, vh);
    ctx.restore();

}else{
    // LANDSCAPE MODE
    ctx.canvas.width = vw;
    ctx.canvas.height = vh;

    ctx.drawImage(video, 0, 0, vw, vh);
}

}

/* ==========================
   CAPTURE PHOTO
========================== */

async function capturePhoto(){

await getLocation();

const video = document.getElementById("video");
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

drawImage(ctx, video);

/* ==========================
   WATERMARK (TOP LEFT)
========================== */

const now = new Date().toLocaleString();

const text1 = "Lat: " + latitude;
const text2 = "Lng: " + longitude;
const text3 = "Date: " + now;

const padding = 12;
const lineHeight = 24;

ctx.font = "bold 18px Arial";

const textWidth = Math.max(
ctx.measureText(text1).width,
ctx.measureText(text2).width,
ctx.measureText(text3).width
);

const boxWidth = textWidth + padding * 2;
const boxHeight = lineHeight * 3 + padding;

const startX = 20;
const startY = 20;

ctx.fillStyle = "rgba(0,0,0,0.6)";
ctx.fillRect(startX, startY, boxWidth, boxHeight);

ctx.fillStyle = "#ffffff";

ctx.fillText(text1, startX + padding, startY + lineHeight);
ctx.fillText(text2, startX + padding, startY + lineHeight * 2);
ctx.fillText(text3, startX + padding, startY + lineHeight * 3);

/* ========================== */

const img = canvas.toDataURL("image/jpeg", 0.9);

capturedImages.push(img);
renderGallery();

}

/* ==========================
   GALLERY
========================== */

function renderGallery(){

const gallery = document.getElementById("gallery");
gallery.innerHTML = "";

capturedImages.forEach((img,i)=>{

const div = document.createElement("div");
div.className = "img-box";

div.innerHTML = `
<img src="${img}">
<button class="delete" onclick="removeImage(${i})">Delete</button>
`;

gallery.appendChild(div);

});

}

/* ==========================
   DELETE
========================== */

function removeImage(i){
capturedImages.splice(i,1);
renderGallery();
}

/* ==========================
   UPLOAD
========================== */

async function uploadPhotos(){

if(capturedImages.length===0){
alert("No photos");
return;
}

let uploaded = 0;

for(const img of capturedImages){

try{

await fetch("upload.php",{
method:"POST",
headers:{'Content-Type':'application/json'},
body:JSON.stringify({
image:img,
token:"<?php echo $token;?>",
latitude:latitude,
longitude:longitude
})
});

uploaded++;
updateProgress(uploaded, capturedImages.length);

}catch(e){
queueOffline(img);
}

}

alert("Upload complete");

capturedImages = [];
renderGallery();

}

/* ==========================
   PROGRESS
========================== */

function updateProgress(done,total){
let percent = (done/total)*100;
document.getElementById("progressBar").style.width = percent + "%";
}

/* ==========================
   OFFLINE QUEUE
========================== */

function queueOffline(img){

let queue = JSON.parse(localStorage.getItem("offlinePhotos") || "[]");

queue.push({
image:img,
token:"<?php echo $token;?>",
lat:latitude,
lng:longitude
});

localStorage.setItem("offlinePhotos", JSON.stringify(queue));

}

/* ==========================
   AUTO RETRY
========================== */

window.addEventListener("online", async ()=>{

let queue = JSON.parse(localStorage.getItem("offlinePhotos") || "[]");

for(const item of queue){

await fetch("upload.php",{
method:"POST",
headers:{'Content-Type':'application/json'},
body:JSON.stringify(item)
});

}

localStorage.removeItem("offlinePhotos");

});

</script>

</body>
</html>