<?php
// Koneksi ke database
$servername = "localhost"; // Ganti jika perlu
$username = "root"; // Ganti jika perlu
$password = ""; // Ganti jika perlu
$dbname = "bprkredit"; // Nama database yang telah dibuat

// Membuat koneksi
$conn = new mysqli($servername, $username, $password, $dbname);

// Cek koneksi
if ($conn->connect_error) {
    die("Koneksi gagal: " . $conn->connect_error);
}

// Mengambil data dari form
$nama = $_POST['nama'];
$ktp = $_POST['ktp'];
$alamat = $_POST['alamat'];
$kodepos = $_POST['kodepos'];
$telp = $_POST['telp'];
$nominal = $_POST['nominal'];

// Proses upload file
$upload_dir = 'uploads/'; // Pastikan folder ini ada dan dapat ditulis
$upload_file = $upload_dir . basename($_FILES['upload']['name']);
move_uploaded_file($_FILES['upload']['tmp_name'], $upload_file);

// Menyimpan data ke database
$sql = "INSERT INTO pengajuan (nama, ktp, alamat, kodepos, telp, nominal, upload, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

// Menyimpan status sebagai 'Menunggu'
$status = 'Menunggu';

// Bind parameter
$stmt->bind_param("ssssssss", $nama, $ktp, $alamat, $kodepos, $telp, $nominal, $upload_file, $status);

if ($stmt->execute()) {
    // If successful, output a script to show an alert and redirect
    echo "<script>
            alert('Pengajuan berhasil disimpan!');
            window.location.href = 'index.php';
          </script>";
    exit(); // Ensure no further code is executed after the redirect
} else {
    echo "Error: " . $stmt->error;
}

// Menutup koneksi
$stmt->close();
$conn->close();
?>