<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require __DIR__ . '/PHPMailer/src/Exception.php';
require __DIR__ . '/PHPMailer/src/PHPMailer.php';
require __DIR__ . '/PHPMailer/src/SMTP.php';


require __DIR__ . '/admin/koneksi.php';

if (isset($_POST['submit'])) {

    $nama   = mysqli_real_escape_string($conn, $_POST['name']);
    $phone  = mysqli_real_escape_string($conn, $_POST['phone']);
    $email  = mysqli_real_escape_string($conn, $_POST['email']);
    $pesan  = mysqli_real_escape_string($conn, $_POST['message']);

    $query = "INSERT INTO kontak (nama, no_hp, email, pesan, tanggal)
              VALUES ('$nama', '$phone', '$email', '$pesan', NOW())";

    if (mysqli_query($conn, $query)) {

        /* =========================
           KIRIM EMAIL KE ADMIN
        ========================= */
        $mail = new PHPMailer(true);

        try {
            $mail->isSMTP();
            $mail->Host       = 'smtp.gmail.com';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'olgazamelda@gmail.com'; // GANTI
            $mail->Password   = 'wwkn mbub udpi iogb'; // GANTI
            $mail->SMTPSecure = 'tls';
            $mail->Port       = 587;

            $mail->setFrom('olgazamelda@gmail.com', 'Website WTC');
            $mail->addAddress('olgazamelda@gmail.com');

            $mail->isHTML(true);
            $mail->Subject = 'Pesan Kontak Baru';
            $mail->Body    = "
                <h3>Pesan Baru dari Website</h3>
                <p><b>Nama:</b> $nama</p>
                <p><b>Email:</b> $email</p>
                <p><b>Phone:</b> $phone</p>
                <p><b>Pesan:</b><br>$pesan</p>
            ";

            $wa_admin = '6283113131372'; // GANTI nomor admin (pakai 62)

$pesan_wa = urlencode(
    "📩 PESAN BARU WEBSITE\n\n" .
    "👤 Nama: $nama\n" .
    "📧 Email: $email\n" .
    "📞 Phone: $phone\n\n" .
    "💬 Pesan:\n$pesan"
);

mysqli_query($conn, "
    INSERT INTO kontak (name, email, phone, message, status)
    VALUES ('$name', '$email', '$phone', '$message', 'unread')
");



if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    die("Email tidak valid");
}

            $mail->send();
        } catch (Exception $e) {
            // biarkan kosong agar user tidak melihat error email
        }

       echo "<script>
    alert('Terima kasih! Pesan berhasil dikirim.');
    window.location.href = 'index.php';
</script>";


    } else {
        die("Error MySQL: " . mysqli_error($conn));
    }
}
?>
