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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(["success" => false, "error" => "Not logged in"]);
    exit;
}

$user_id = $_SESSION['user_id'];

$title = trim($_POST['title'] ?? "");
$description = trim($_POST['description'] ?? "");
$nsfw = isset($_POST['nsfw']) ? 1 : 0;

if (!$title || !isset($_FILES['file'])) {
    echo json_encode(["success" => false, "error" => "Missing fields"]);
    exit;
}

$file = $_FILES['file'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

$type = "";
if (in_array($ext, ["jpg","jpeg","png","gif","webp"])) $type = "image";
if (in_array($ext, ["mp4","webm","mov"])) $type = "video";

if ($type === "") {
    echo json_encode(["success" => false, "error" => "Invalid file type"]);
    exit;
}

$filename = uniqid() . "." . $ext;

// PHYSICAL SERVER PATHS
$uploadDir = __DIR__ . "/../uploads/";
$thumbDir  = __DIR__ . "/../thumbs/";

if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);
if (!is_dir($thumbDir)) mkdir($thumbDir, 0777, true);

$path = $uploadDir . $filename;
move_uploaded_file($file['tmp_name'], $path);

// PUBLIC URL PATH
$publicPath  = "uploads/$filename";
$publicThumb = "thumbs/$filename.jpg";

/* ---------------------------------------------------------
   EXIF EXTRACTION
--------------------------------------------------------- */

$exif_json = null;
$camera_model = null;
$gps_lat = null;
$gps_lng = null;
$location_region = null;

if ($type === "image") {
    $exif = @exif_read_data($path, 'EXIF', true);

    if ($exif !== false) {
        $exif_json = json_encode($exif);

        if (!empty($exif['IFD0']['Model'])) {
            $camera_model = $exif['IFD0']['Model'];
        }

        // Helpers
        function gpsPartToFloat($part) {
            $parts = explode('/', $part);
            if (count($parts) == 2) {
                return floatval($parts[0]) / floatval($parts[1]);
            }
            return floatval($part);
        }

        function gpsToDecimal($coord, $hemisphere) {
            $degrees = gpsPartToFloat($coord[0]);
            $minutes = gpsPartToFloat($coord[1]);
            $seconds = gpsPartToFloat($coord[2]);

            $flip = ($hemisphere == 'W' || $hemisphere == 'S') ? -1 : 1;

            return $flip * ($degrees + ($minutes / 60) + ($seconds / 3600));
        }

        // GPS
        if (!empty($exif['GPS']['GPSLatitude']) && !empty($exif['GPS']['GPSLongitude'])) {
            $gps_lat = gpsToDecimal(
                $exif['GPS']['GPSLatitude'],
                $exif['GPS']['GPSLatitudeRef']
            );

            $gps_lng = gpsToDecimal(
                $exif['GPS']['GPSLongitude'],
                $exif['GPS']['GPSLongitudeRef']
            );

            // Simple region detection (placeholder)
            function getRegionFromGPS($lat, $lng) {
                if ($lat < -38 && $lng > 173) return "Taranaki";
                if ($lat < -40) return "South Island";
                return "North Island";
            }

            $location_region = getRegionFromGPS($gps_lat, $gps_lng);
        }
    }
}

/* ---------------------------------------------------------
   THUMBNAIL GENERATION (300x300 square, center-crop)
--------------------------------------------------------- */

$thumb_path = $thumbDir . $filename . ".jpg";

if ($type === "image") {

    function createSquareThumbnail($src, $dest, $size = 300) {
        $info = getimagesize($src);
        $mime = $info['mime'];

        switch ($mime) {
            case 'image/jpeg':
                $image = imagecreatefromjpeg($src);
                break;
            case 'image/png':
                $image = imagecreatefrompng($src);
                break;
            case 'image/gif':
                $image = imagecreatefromgif($src);
                break;
            case 'image/webp':
                $image = imagecreatefromwebp($src);
                break;
            default:
                return false;
        }

        $width  = imagesx($image);
        $height = imagesy($image);

        // Determine shortest side for square crop
        $shortSide = min($width, $height);

        // Center crop coordinates
        $srcX = ($width  - $shortSide) / 2;
        $srcY = ($height - $shortSide) / 2;

        // Create square crop
        $crop = imagecreatetruecolor($shortSide, $shortSide);
        imagecopyresampled(
            $crop, $image,
            0, 0,
            $srcX, $srcY,
            $shortSide, $shortSide,
            $shortSide, $shortSide
        );

        // Resize to final 300x300
        $thumb = imagecreatetruecolor($size, $size);
        imagecopyresampled(
            $thumb, $crop,
            0, 0,
            0, 0,
            $size, $size,
            $shortSide, $shortSide
        );

        // Save as JPG
        imagejpeg($thumb, $dest, 85);

        imagedestroy($image);
        imagedestroy($crop);
        imagedestroy($thumb);

        return true;
    }

    createSquareThumbnail($path, $thumb_path);
}

/* ---------------------------------------------------------
   INSERT INTO DATABASE
--------------------------------------------------------- */

$stmt = $pdo->prepare("
    INSERT INTO posts 
    (user_id, file_path, thumbnail_path, type, title, description, nsfw, exif_json, camera_model, gps_lat, gps_lng, location_region)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$stmt->execute([
    $user_id,
    $publicPath,
    $publicThumb,
    $type,
    $title,
    $description,
    $nsfw,
    $exif_json,
    $camera_model,
    $gps_lat,
    $gps_lng,
    $location_region
]);

$post_id = $pdo->lastInsertId();

/* ---------------------------------------------------------
   TAGS
--------------------------------------------------------- */

$tags = json_decode($_POST['tags'] ?? "[]", true);
if (is_array($tags)) {
    foreach ($tags as $t) {
        $t = trim($t);
        if ($t === "") continue;

        $tagStmt = $pdo->prepare("INSERT IGNORE INTO tags (name) VALUES (?)");
        $tagStmt->execute([$t]);

        $tagIdStmt = $pdo->prepare("SELECT id FROM tags WHERE name = ?");
        $tagIdStmt->execute([$t]);
        $tag_id = $tagIdStmt->fetchColumn();

        $linkStmt = $pdo->prepare("INSERT IGNORE INTO post_tags (post_id, tag_id) VALUES (?, ?)");
        $linkStmt->execute([$post_id, $tag_id]);
    }
}

echo json_encode(["success" => true, "post_id" => $post_id]);