<?php
include "db.php";

$data = json_decode(file_get_contents("php://input"), true);

$image = $data['image'] ?? '';
$token = $data['token'] ?? '';
$lat   = $data['latitude'] ?? '';
$lng   = $data['longitude'] ?? '';

$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("Invalid Token");
}

$image = str_replace('data:image/jpeg;base64,', '', $image);
$imageData = base64_decode($image);

$uploadPath="uploads/".$token;
if(!file_exists($uploadPath)){
    mkdir($uploadPath,0777,true);
}

$fileName=time().".jpg";
file_put_contents($uploadPath."/".$fileName,$imageData);

$stmt=$conn->prepare("INSERT INTO photos (token,file_name,latitude,longitude) VALUES (?,?,?,?)");
$stmt->bind_param("ssss",$token,$fileName,$lat,$lng);
$stmt->execute();

echo "Success";
?>