<?php
session_start();

ini_set('display_errors', 1);
error_reporting(E_ALL);

// Kalau request bukan POST, kasih respon JSON error
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "error",
        "message" => "Hanya menerima permintaan POST."
    ]);
    exit;
}

// Pastikan ada parameter create (dari ajax)
if (!isset($_POST['create'])) {
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "error",
        "message" => "Form tidak sesuai."
    ]);
    exit;
}

// Pastikan file ada dan tidak error
if (!isset($_FILES['cfoto']) || $_FILES['cfoto']['error'] !== UPLOAD_ERR_OK) {
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "error",
        "message" => "Tidak ada file yang diupload atau terjadi kesalahan."
    ]);
    exit;
}

$target_dir = "uploads/";
if (!is_dir($target_dir)) {
    mkdir($target_dir, 0777, true);
}

// Ambil ekstensi file dan buat nama baru agar unik
$ext = pathinfo($_FILES["cfoto"]["name"], PATHINFO_EXTENSION);
$file_name = "Foto_" . time() . "." . strtolower($ext);
$target_file = $target_dir . $file_name;

// Pindahkan file dari temporary ke folder uploads/
if (move_uploaded_file($_FILES["cfoto"]["tmp_name"], $target_file)) {
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "success",
        "message" => "Upload berhasil.",
        "file_path" => $target_file
    ]);
    exit;
} else {
    header('Content-Type: application/json');
    echo json_encode([
        "status" => "error",
        "message" => "Gagal mengunggah file."
    ]);
    exit;
}
