<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['idkaskit'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/fungsi.php';

$id = $_SESSION['idkaskit'];

if (!isset($_FILES['foto']) || $_FILES['foto']['error'] !== UPLOAD_ERR_OK) {
    echo json_encode(['success' => false, 'message' => 'File tidak valid']);
    exit;
}

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

if (!in_array($ext, $allowed)) {
    echo json_encode(['success' => false, 'message' => 'Format harus JPG, PNG, atau WebP']);
    exit;
}

if ($file['size'] > 2 * 1024 * 1024) {
    echo json_encode(['success' => false, 'message' => 'Ukuran maksimal 2MB']);
    exit;
}

$upload_dir = __DIR__ . '/../img/';

// Get old photo to delete later
$old = mysqli_fetch_array(mysqli_query($koneksi, "SELECT foto FROM tb_user WHERE id='$id'"));
$old_foto = $old ? $old['foto'] : '';

// Save new photo
$new_name = 'user-' . $id . '-' . time() . '.' . $ext;
if (move_uploaded_file($file['tmp_name'], $upload_dir . $new_name)) {
    // Delete old photo
    if ($old_foto && file_exists($upload_dir . $old_foto)) {
        unlink($upload_dir . $old_foto);
    }
    mysqli_query($koneksi, "UPDATE tb_user SET foto='$new_name' WHERE id='$id'");
    echo json_encode(['success' => true, 'foto' => $new_name, 'path' => '../img/' . $new_name]);
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal menyimpan file']);
}
