<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit;
}

$host = "localhost";
$user = "root";
$pass = "";
$db   = "sppg_db";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    echo json_encode([
        "success" => false,
        "message" => "Koneksi database gagal",
        "data" => null
    ]);
    exit;
}

$id = $_POST["id"] ?? "";

if ($id === "") {
    echo json_encode([
        "success" => false,
        "message" => "ID SPPG wajib dikirim",
        "data" => null
    ]);
    exit;
}

if (!isset($_FILES["foto"])) {
    echo json_encode([
        "success" => false,
        "message" => "File foto belum dikirim",
        "data" => null
    ]);
    exit;
}

$file = $_FILES["foto"];

$allowedTypes = [
    "image/jpeg",
    "image/jpg",
    "image/png",
    "image/webp"
];

if (!in_array($file["type"], $allowedTypes)) {
    echo json_encode([
        "success" => false,
        "message" => "Format foto harus JPG, PNG, atau WEBP",
        "data" => null
    ]);
    exit;
}

$maxSize = 3 * 1024 * 1024;

if ($file["size"] > $maxSize) {
    echo json_encode([
        "success" => false,
        "message" => "Ukuran foto maksimal 3MB",
        "data" => null
    ]);
    exit;
}

$uploadDir = __DIR__ . "/../uploads/sppg/";

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

$extension = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
$fileName = "sppg_" . time() . "_" . rand(1000, 9999) . "." . $extension;
$targetPath = $uploadDir . $fileName;

if (!move_uploaded_file($file["tmp_name"], $targetPath)) {
    echo json_encode([
        "success" => false,
        "message" => "Gagal mengupload foto",
        "data" => null
    ]);
    exit;
}

$dbPath = "uploads/sppg/" . $fileName;

$stmt = $conn->prepare("UPDATE sppg SET foto = ? WHERE id = ?");
$stmt->bind_param("si", $dbPath, $id);

if (!$stmt->execute()) {
    echo json_encode([
        "success" => false,
        "message" => "Foto berhasil diupload, tetapi gagal disimpan ke database",
        "data" => null
    ]);
    exit;
}

echo json_encode([
    "success" => true,
    "message" => "Foto berhasil diupload",
    "data" => [
        "foto" => $dbPath,
        "url" => "http://localhost/backend/" . $dbPath
    ]
]);

$conn->close();