<?php
header('Content-Type: application/json');
include '../koneksi.php';
error_reporting(0);

$id_user = $_POST['id_user'] ?? '';
$foto_raw = $_POST['foto'] ?? '';

if (empty($id_user) || empty($foto_raw)) {
    echo json_encode(["status" => false, "message" => "Data tidak lengkap"]);
    exit;
}

// Perbaiki karakter base64
$foto_clean = str_replace(' ', '+', $foto_raw);
$nama_file = "USR_" . $id_user . "_" . time() . ".jpg";
$folder_path = "../images/img_user/";

if (!file_exists($folder_path)) { mkdir($folder_path, 0777, true); }

if (file_put_contents($folder_path . $nama_file, base64_decode($foto_clean))) {
    // Update nama file foto di database
    $sql = "UPDATE users SET foto_user = '$nama_file' WHERE id_user = '$id_user'";
    if (mysqli_query($koneksi, $sql)) {
        echo json_encode([
            "status" => true, 
            "message" => "Foto berhasil diperbarui",
            "data" => ["foto_user" => $nama_file]
        ]);
    } else {
        echo json_encode(["status" => false, "message" => "Gagal update database"]);
    }
} else {
    echo json_encode(["status" => false, "message" => "Gagal simpan file"]);
}
?>