<?php
session_start();
include '../db/koneksi.php';

header('Content-Type: application/json');

if (!isset($_SESSION['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Sesi login tidak ditemukan.']);
    exit;
}

$id_user = $_SESSION['id'];
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$password_confirm = trim($_POST['password_confirm']);

$errors = [];

if (empty($email)) {
    $errors['email'] = 'Email tidak boleh kosong.';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Format email tidak valid.';
}

if (!empty($password)) {
    if (strlen($password) < 6) {
        $errors['password'] = 'Password minimal 6 karakter.';
    } elseif ($password !== $password_confirm) {
        $errors['password_confirm'] = 'Konfirmasi password tidak cocok.';
    }
}

if (!empty($errors)) {
    echo json_encode(['status' => 'error', 'errors' => $errors]);
    exit;
}

if (!empty($password)) {
    $hashed = password_hash($password, PASSWORD_DEFAULT);
    $sql = "UPDATE tb_user SET email = ?, password = ? WHERE id = ?";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('ssi', $email, $hashed, $id_user);
} else {
    $sql = "UPDATE tb_user SET email = ? WHERE id = ?";
    $stmt = $koneksi->prepare($sql);
    $stmt->bind_param('si', $email, $id_user);
}

if ($stmt->execute()) {
    echo json_encode(['status' => 'success', 'message' => 'Profil berhasil diupdate']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui profil']);
}
?>
