<?php
session_start();

include 'db.php';

// 🔒 Cek login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

$alertType = "";
$alertMessage = "";
$nama_baru = $alamat_baru = $no_hape_baru = $gbr_plg_baru = "";

// 🔌 Koneksi database
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// 📥 Ambil data pelanggan
$stmt = $conn->prepare("SELECT Nama, Alamat, Email, No_hape, Gbr_plg FROM pelanggan WHERE Email = ?");
$stmt->bind_param("s", $_SESSION['username']);
$stmt->execute();
$stmt->bind_result($nama_baru, $alamat_baru, $email_baru, $no_hape_baru, $gbr_plg_baru);
$stmt->fetch();
$stmt->close();

// 🧾 Update profil
if (isset($_POST['update_profile'])) {
    $nama   = trim($_POST['nama'] ?? '');
    $alamat = trim($_POST['alamat'] ?? '');
    $telp   = trim($_POST['telp'] ?? '');
    $nama_file = $gbr_plg_baru;

    // 📸 Upload foto baru
    if (!empty($_FILES["foto"]["tmp_name"])) {
        $target_dir = "gambar/";
        $nama_file = basename($_FILES["foto"]["name"]);
        $target_file = $target_dir . $nama_file;
        $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
        $uploadOk = 1;

        $check = getimagesize($_FILES["foto"]["tmp_name"]);
        if ($check === false) { $uploadOk = 0; $alertType="error"; $alertMessage="File bukan gambar."; }

        if (file_exists($target_file)) { $uploadOk = 0; $alertType="error"; $alertMessage="File sudah ada, ganti nama file."; }

        if ($_FILES["foto"]["size"] > 5000000) { $uploadOk = 0; $alertType="error"; $alertMessage="Ukuran file terlalu besar (maks 5MB)."; }

        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            $uploadOk = 0; $alertType="error"; $alertMessage="Hanya file JPG, JPEG, PNG & GIF yang diizinkan.";
        }

        if ($uploadOk == 1 && move_uploaded_file($_FILES["foto"]["tmp_name"], $target_file)) {
            if ($gbr_plg_baru && file_exists("gambar/" . $gbr_plg_baru)) unlink("gambar/" . $gbr_plg_baru);
            $alertType = "success"; 
            $alertMessage = "Foto baru berhasil diupload.";
        } else {
            $nama_file = $gbr_plg_baru;
        }
    }

    $stmt = $conn->prepare("UPDATE pelanggan SET Nama = ?, Alamat = ?, No_hape = ?, Gbr_plg = ? WHERE Email = ?");
    $stmt->bind_param("sssss", $nama, $alamat, $telp, $nama_file, $_SESSION['username']);
    if ($stmt->execute()) {
        $alertType = "success";
        $alertMessage = "Data pelanggan berhasil diperbarui!";
        $nama_baru = $nama;
        $alamat_baru = $alamat;
        $no_hape_baru = $telp;
        $gbr_plg_baru = $nama_file;
    } else {
        $alertType = "error";
        $alertMessage = "Error database: " . $stmt->error;
    }
    $stmt->close();
}

// 🔑 Ubah sandi
if (isset($_POST['update_password'])) {
    $sandi_lama = $_POST['sandi_lama'] ?? '';
    $sandi_baru = $_POST['sandi_baru'] ?? '';
    $konfirmasi = $_POST['konfirmasi'] ?? '';

    if ($sandi_baru === '' || $konfirmasi === '' || $sandi_lama === '') {
        $alertType="error"; $alertMessage="Semua kolom sandi wajib diisi.";
    } elseif ($sandi_baru !== $konfirmasi) {
        $alertType="error"; $alertMessage="Konfirmasi sandi tidak cocok.";
    } else {
        $cek = $conn->prepare("SELECT password FROM users WHERE username = ?");
        $cek->bind_param("s", $_SESSION['username']);
        $cek->execute();
        $cek->bind_result($hash_lama);
        $cek->fetch();
        $cek->close();

        if (!password_verify($sandi_lama, $hash_lama)) {
            $alertType="error"; $alertMessage="Sandi lama salah.";
        } else {
            $hash_baru = password_hash($sandi_baru, PASSWORD_DEFAULT);
            $upd = $conn->prepare("UPDATE users SET password = ? WHERE username = ?");
            $upd->bind_param("ss", $hash_baru, $_SESSION['username']);
            if ($upd->execute()) {
                $alertType="success"; $alertMessage="Sandi berhasil diperbarui!";
            } else {
                $alertType="error"; $alertMessage="Gagal mengubah sandi.";
            }
            $upd->close();
        }
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Edit Akun</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
body { background-color: #f5f7fa; font-family: Verdana, sans-serif; }
.card { border-radius: 15px; box-shadow: 0 5px 15px rgba(0,0,0,0.1); }
img.preview { border-radius: 10px; border: 1px solid #ccc; }
</style>
</head>
<body>

<div class="container mt-5">
  <div class="card p-4">
    <h2 class="text-center mb-3">Edit Akun</h2>
    <p class="text-center text-muted">(Email tidak bisa diubah. Jika ingin ubah email, silakan buat akun baru)</p>

    <!-- Form Edit Profil -->
    <form method="post" enctype="multipart/form-data" class="mt-3">
      <input type="hidden" name="update_profile" value="1">

      <div class="mb-3">
        <label class="form-label">Nama Lengkap</label>
        <input type="text" name="nama" class="form-control" value="<?= htmlspecialchars($nama_baru); ?>" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Alamat</label>
        <input type="text" name="alamat" class="form-control" value="<?= htmlspecialchars($alamat_baru); ?>" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Email</label>
        <input type="text" class="form-control" value="<?= htmlspecialchars($_SESSION['username']); ?>" readonly>
      </div>

      <div class="mb-3">
        <label class="form-label">No. Hape</label>
        <input type="text" name="telp" class="form-control" value="<?= htmlspecialchars($no_hape_baru); ?>" required>
      </div>

      <div class="mb-3 text-center">
        <label class="form-label d-block">Foto Sekarang</label>
        <img src="gambar/<?= htmlspecialchars($gbr_plg_baru ?: 'foto_profil_kosong.png'); ?>" width="120" class="preview mb-2" id="preview-img">
      </div>

      <div class="mb-3">
        <label class="form-label">Ganti Foto</label>
        <input type="file" name="foto" accept="image/*" class="form-control" onchange="previewImage(event)">
      </div>

      <div class="text-center mb-4">
        <button type="submit" class="btn btn-primary px-4">💾 Simpan Profil</button>
      </div>
    </form>

    <hr>

    <!-- Form Ubah Sandi -->
    <h4 class="text-center mt-4 mb-3">Ubah Sandi</h4>
    <form method="post">
      <input type="hidden" name="update_password" value="1">
      <div class="mb-3">
        <label class="form-label">Sandi Lama</label>
        <input type="password" name="sandi_lama" class="form-control" required>
      </div>

      <div class="mb-3">
        <label class="form-label">Sandi Baru</label>
        <input type="password" name="sandi_baru" class="form-control" required minlength="6">
      </div>

      <div class="mb-3">
        <label class="form-label">Konfirmasi Sandi Baru</label>
        <input type="password" name="konfirmasi" class="form-control" required minlength="6">
      </div>

      <div class="text-center">
        <button type="submit" class="btn btn-success px-4">🔒 Ubah Sandi</button>
        <a href="dashboard.php" class="btn btn-secondary px-4 ms-2">⬅️ Kembali</a>
      </div>
    </form>
  </div>
</div>

<script>
function previewImage(event) {
    const img = document.getElementById('preview-img');
    img.src = URL.createObjectURL(event.target.files[0]);
}

<?php if (!empty($alertMessage)): ?>
Swal.fire({
  icon: '<?= $alertType ?>',
  title: '<?= $alertType === "success" ? "Berhasil!" : "Peringatan!" ?>',
  html: '<?= addslashes($alertMessage) ?>',
  confirmButtonText: 'OK',
  confirmButtonColor: '<?= $alertType === "success" ? "#3085d6" : "#d33" ?>'
});
<?php endif; ?>
</script>

</body>
</html>
