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

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

$email = $_SESSION['username'];
$pesan = "";

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

// === Cek apakah pelanggan sudah pernah isi profil ===
$stmt = $conn->prepare("SELECT COUNT(*) FROM pelanggan WHERE Email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($sudah_ada);
$stmt->fetch();
$stmt->close();

if ($sudah_ada > 0) {
    // Jika sudah ada, tampilkan pesan dan hentikan
    echo "<html><body style='font-family:verdana;text-align:center;'>";
    echo "<br><br><font size=5 color=blue>✅ Akun Anda sudah terdaftar sebagai pelanggan.</font><br><br>";
    echo "<a href='dashboard.php'>Kembali ke Dashboard</a>";
    echo "</body></html>";
    exit;
}

// === Jika form disubmit ===
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $nama   = trim($_POST['nama'] ?? '');
    $alamat = trim($_POST['alamat'] ?? '');
    $telp   = trim($_POST['telp'] ?? '');

    // === Proses upload foto ===
    $target_dir = "gambar/";
    $nama_file = basename($_FILES["foto"]["name"]);
    $target_file = $target_dir . $nama_file;
    $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    $uploadOk = 1;

    if (!empty($_FILES["foto"]["tmp_name"])) {
        $check = getimagesize($_FILES["foto"]["tmp_name"]);
        if ($check === false) {
            $pesan .= "❌ File bukan gambar.<br>";
            $uploadOk = 0;
        }

        if (file_exists($target_file)) {
            $pesan .= "❌ File sudah ada di server.<br>";
            $uploadOk = 0;
        }

        if ($_FILES["foto"]["size"] > 5000000) {
            $pesan .= "❌ Ukuran file terlalu besar (maksimal 5MB).<br>";
            $uploadOk = 0;
        }

        if (!in_array($imageFileType, ["jpg", "jpeg", "png", "gif"])) {
            $pesan .= "❌ Hanya file JPG, JPEG, PNG & GIF yang diizinkan.<br>";
            $uploadOk = 0;
        }

        if ($uploadOk == 1) {
            if (move_uploaded_file($_FILES["foto"]["tmp_name"], $target_file)) {
                // Simpan data pelanggan baru
                $stmt = $conn->prepare("INSERT INTO pelanggan (Nama, Alamat, Email, No_hape, Gbr_plg) VALUES (?, ?, ?, ?, ?)");
                $stmt->bind_param("sssss", $nama, $alamat, $email, $telp, $nama_file);

                if ($stmt->execute()) {
                    $pesan .= "<span style='color:green;'>✅ Akun pelanggan berhasil dibuat!</span><br>";
                } else {
                    $pesan .= "❌ Gagal menyimpan data: " . htmlspecialchars($stmt->error) . "<br>";
                }

                $stmt->close();
            } else {
                $pesan .= "⚠️ Terjadi kesalahan saat mengupload file.<br>";
            }
        } else {
            $pesan .= "⚠️ Upload dibatalkan.<br>";
        }
    } else {
        $pesan .= "❌ Anda harus memilih foto.<br>";
    }
}

$conn->close();
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Buat Akun Pelanggan Baru</title>
<style>
body {
    font-family: Verdana, sans-serif;
    background-color: #f8f8f8;
    margin: 0;
    padding: 0;
}
.container {
    width: 600px;
    margin: 50px auto;
    background: #fff;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 0 10px #aaa;
}
h2 { color: #007bff; }
button {
    background: #007bff;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}
button:hover { background: #0056b3; }
</style>
</head>
<body>
<div class="container">
<center>
    <h2>Buat Akun Pelanggan Baru</h2>
    <p><small>Email sudah dibuat saat register, tidak bisa diubah.</small></p>
    <?php if (!empty($pesan)) echo "<div style='margin-bottom:15px;'>$pesan</div>"; ?>
</center>

<form enctype="multipart/form-data" method="post">
<table cellpadding="10" align="center">
<tr><td>Nama Lengkap</td><td><input type="text" name="nama" size="40" required></td></tr>
<tr><td>Alamat</td><td><input type="text" name="alamat" size="40" required></td></tr>
<tr><td>Email</td><td><b><?php echo htmlspecialchars($email); ?></b></td></tr>
<tr><td>No. Hape</td><td><input type="text" name="telp" size="40" required></td></tr>
<tr><td>Foto</td><td><input type="file" name="foto" accept="image/*" required></td></tr>
<tr><td></td><td><button type="submit">Simpan Akun</button></td></tr>
</table>
</form>
</div>
</body>
</html>
