<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");

include '../config/koneksi.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => 'error', 'message' => 'Method tidak valid']);
    exit;
}

$no_kartu = $_POST['no_kartu'] ?? '';
if (empty($no_kartu) || !isset($_FILES['foto'])) {
    echo json_encode(['status' => 'error', 'message' => 'Data tidak lengkap']);
    exit;
}

$file = $_FILES['foto'];
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$allowed = ['jpg', 'jpeg', 'png', 'webp'];

if (!in_array($ext, $allowed)) {
    echo json_encode(['status' => 'error', 'message' => 'Format file tidak didukung']);
    exit;
}

$uploadDir = '../uploads/profil/';
if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

$filename = 'profil_' . preg_replace('/[^a-zA-Z0-9]/', '', $no_kartu) . '_' . time() . '.' . $ext;
$targetPath = $uploadDir . $filename;

if (!move_uploaded_file($file['tmp_name'], $targetPath)) {
    echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan file']);
    exit;
}

$urlPath = 'uploads/profil/' . $filename;
$stmt = $conn->prepare("UPDATE karyawan SET pic = ? WHERE no_kartu = ?");
$stmt->bind_param("ss", $urlPath, $no_kartu);

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'url' => $urlPath]);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Gagal update database']);
}

$stmt->close();
$conn->close();
?>
