<?php
ob_start();
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../../config/koneksi.php');
if (!function_exists('site_url')) {
    include('../../config/url_helper.php');
}

if (empty($_SESSION['user'])) {
    header('Location: ' . site_url('m'));
    exit;
}

$sql_0 = mysqli_query($conn, "SELECT * FROM `tb_seo` WHERE cuid = 1") or die(mysqli_error());
$s0 = mysqli_fetch_array($sql_0);
$urlweb = $s0['urlweb'];
$urlwebs = $s0['urlweb'];
$user = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE username = '" . mysqli_real_escape_string($conn, $_SESSION['user']) . "'") or die(mysqli_error());
$u = mysqli_fetch_array($user);

if ((int) $u['status_kyc'] === 1) {
    $form_display = false;
    $notification = 'KYC Anda sudah aktif. Kode referral dapat digunakan.';
} else {
    $form_display = true;
    $notification = '';
}
$users = $u['username'];
$id_user = $u['cuid'];
$userID = $u['cuid'];
$sql_banks = mysqli_query($conn,"SELECT * FROM `tb_bank` WHERE userID = '$userID'") or die(mysqli_error());
$sbs = mysqli_fetch_array($sql_banks);
include "../header.php";
?>
<div class="content my01">



<div class="container-fluid"> 
<div class="row chg-pass activate_referral">
<div class="col-xs-12 offset-lg-3 col-lg-8">
<div class="title">Formulir Aktivasi Kode Referal</div>
<br>

<?php
// Proses data setelah tombol "Submit" ditekan
if ($_SERVER["REQUEST_METHOD"] == "POST" && (int) $u['status_kyc'] !== 1) {
    // Ambil data dari form
    $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
    $bank_name = htmlspecialchars(trim($_POST['bank_name']));
    $name = htmlspecialchars(trim($_POST['name']));
    $user_identification = $_FILES['user_identification']['name']; // Nama file yang di-upload
    $method = htmlspecialchars(trim($_POST['method']));
    $terms = isset($_POST['terms']) ? 1 : 0; // Cek jika checkbox terms di-cek

    // Validasi data
    if (empty($email) || empty($bank_name) || empty($name) || empty($user_identification) || !$terms) {
        $notification = "Semua field harus diisi dan syarat harus disetujui.";
    } else {
        // Validasi email
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $notification = "Alamat email tidak valid.";
        } else {
            $fullNameCheck = $u['full_name'];
            $check_sql = "SELECT * FROM tb_kyc WHERE name = ?";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("s", $fullNameCheck);
            $check_stmt->execute();
            $result = $check_stmt->get_result();

            if ($result->num_rows > 0) {
                $form_display = false;
                $notification = "Pengajuan KYC sudah dikirim. Silakan tunggu persetujuan admin.";
            } else {
                // Cek tipe file yang di-upload
                $allowed_types = ['image/jpeg', 'image/png', 'application/pdf']; // Ganti sesuai jenis file yang diizinkan
                $file_type = $_FILES['user_identification']['type'];
                $file_size = $_FILES['user_identification']['size'];
                $max_file_size = 2 * 1024 * 1024; // 2MB

                if (!in_array($file_type, $allowed_types)) {
                    $notification = "Tipe file tidak diizinkan. Harap upload file JPG, PNG, atau PDF.";
                } elseif ($file_size > $max_file_size) {
                    $notification = "Ukuran file terlalu besar. Maksimal 2MB.";
                } else {
                    // Proses upload file (misal ke folder 'uploads/')
                    $target_dir = "../../uploads/";
                    $target_file = $target_dir . basename($user_identification);
                    
                    // Pindahkan file ke target directory
                    if (move_uploaded_file($_FILES["user_identification"]["tmp_name"], $target_file)) {
                        // Menggunakan koneksi yang sudah ada untuk menyimpan ke database
                        $sql = "INSERT INTO tb_kyc (email, bank_name, name, user_identification, method, terms) VALUES (?, ?, ?, ?, ?, ?)";
                        $stmt = $conn->prepare($sql);
                        $stmt->bind_param("ssssii", $email, $bank_name, $name, $user_identification, $method, $terms);
                        
                        if ($stmt->execute()) {
                            $notification = "Anda telah berhasil memverifikasi. Silakan tunggu.";
                            $form_display = false;
                        } else {
                            $notification = "Terjadi kesalahan: " . $stmt->error;
                        }
                    } else {
                        $notification = "Gagal mengupload file.";
                    }
                }
            }
        }
    }
}
?>

<?php if ($notification): ?>
    <div class="alert alert-info">
        <?php echo $notification; ?>
    </div>
<?php endif; ?>
<?php if ($form_display): ?>
<form id="chgPwdForm" class="needs-validation activateReferralForm" method="POST" action="" enctype="multipart/form-data" novalidate="novalidate">
    <input type="hidden" name="_token" value="6K4FRkf7cYbSFSRr3I8t5hDitmiyeWx1S8yxtyRJ">
    
    <div id="step_one_form">
        <div class="form-group row ">
            <div class="col-xs-6 radio_2" id="email_radio">
                <input class="" type="radio" name="type" value="email" required>
                <label class="">
                    <span class="radio-title"> Alamat email </span>
                    <span class="marked">
                        <i class="icon-checkmark"></i>
                    </span>
                </label>
            </div>
        </div>
        <div class="form-group row no-gutters" id="email_input">
            <label class="col-md-5 col-form-label text-left">Alamat email<span class="text-danger">&nbsp;*&nbsp;</span></label>
            <div class="col-md-7">
                <input type="text" name="email" id="email" value="<?= htmlspecialchars($u['email']); ?>" class="form-control" required="">
                <div class="form-group row no-gutters">
                    <label class="col-md-5 col-xs-12 col-form-label text-left">Bank<span class="text-danger">&nbsp;*&nbsp;</span></label>
                    <div class="col-md-7 col-xs-12">
                        <select class="form-control" id="bank_user_id" name="bank_name" style="height: 35px;" required>
                            <option selected="" value="">- Silahkan pilih -</option>
                            <option value="<?= htmlspecialchars($sbs['no_rek']); ?>" data-accname="<?= htmlspecialchars($sbs['pemilik']); ?>" data-method="5">
                                <?= htmlspecialchars($sbs['akun']); ?>-XXXX - XXXX - XXXX
                            </option>
                        </select>
                    </div>
                </div>
                <div class="form-group row no-gutters">
                    <label class="col-md-5 col-form-label text-left">Nama Sesuai Rekening<span class="text-danger">&nbsp;*&nbsp;</span></label>
                    <div class="col-md-7">
                        <input type="text" name="name" id="full_name" value="<?= htmlspecialchars($u['full_name']); ?>" class="form-control" placeholder="PLEASE LOG IN THE NAME OF THE ACCOUNT OWNER" required="" readonly="">
                    </div>
                </div>
                <div class="form-group row no-gutters">
                    <label class="col-md-5 col-form-label text-left">ID CARD (KTP / SIM / PASPOR)<span class="text-danger">&nbsp;*&nbsp;</span></label>
                    <div class="col-md-7 d-flex flex-wrap">
                        <div class="file-drop-area">
                            <span class="btn btn-secondary">Pilih File</span>
                            <span class="file-msg">atau seret dan taruh file di sini</span>
                            <input class="file-input" name="user_identification" id="user_identification" type="file" required="">
                        </div>
                    </div>
                </div>
                <div class="alert alert-success message--chg-pass" style="display:none;"></div>
                <div class="form-group row no-gutters mt-3">
                    <div class="col-xs-12 col-6"></div>
                    <div class="col-xs-12 col-6 text-center">
                        <button type="button" class="btn btn-primary" id="next_btn">Lanjut</button>
                    </div>
                </div>
                <input type="hidden" name="method" value="5">
            </div>
        </div>
    </div>

    <div id="step_two_form" style="display: none;">
        <div>
            <h2>Syarat Dan Ketentuan Umum Referal</h2>
            <ul style="list-style: disc; padding: 0 20px;">
                <li>Saya memberikan Informasi Pribadi yang akurat dan benar, serta mempertanggung jawabkan atas ketidakbenaran data yang saya berikan</li>
                <li>Saya berkomitmen untuk tidak melakukan Tindakan Phising. Phising adalah tindakan mempromosikan salah satu website dengan menggunakan Nama website orang lain</li>
                <li>Saya berkomitmen untuk tidak melakukan promosi atau membuat SEO / tautan back link dengan menggunakan situs Link Pemerintah atau metode apapun yang berkaitan dan aktifitas merugikan lainnya.</li>
                <li>Saya menyadari bahwa melanggar syarat dan ketentuan ini dapat mengakibatkan penutupan akun dan pemblokiran data, serta saya bersedia menerima segala konsekuensi yang timbul akibat pelanggaran tersebut</li>
                <li>Semua keputusan pihak Admin / penyelenggara website adalah mutlak dan Admin website berhak melakukan perubahan syarat dan ketentuan ini sewaktu-waktu, harap membaca dengan seksama terkait syarat dan ketentuan ini dari waktu ke waktu.</li>
            </ul>
        </div>
        <div class="form-group form-check">
            <div class="col-md-12 submit-box" style="padding: 0;">
                <div class="checkbox">
                    <label><input type="checkbox" id="terms" name="terms" value="on" required> &nbsp;Dengan memilih tombol KIRIMKAN</label>
                </div>
            </div>
        </div>

        <div class="form-group row no-gutters mt-3">
            <div class="col-xs-12 col-6"></div>
            <div class="col-xs-12 col-6 text-center">
                <button type="submit" class="btn btn-primary">Submit</button>
            </div>
        </div>
    </div>
</form>
<?php endif; ?>
</div>

<script>
// Menambahkan event listener untuk tombol "Lanjut"
document.getElementById('next_btn').addEventListener('click', function() {
    // Validasi input pada langkah satu
    var email = document.getElementById('email').value;
    var bank_name = document.getElementById('bank_user_id').value;
    var name = document.getElementById('full_name').value;
    var user_identification = document.getElementById('user_identification').value;

    // Cek apakah semua field di langkah satu sudah terisi
    if (email && bank_name && name && user_identification) {
        // Menampilkan langkah kedua
        document.getElementById('step_two_form').style.display = 'block';
        document.getElementById('step_one_form').style.display = 'none';
    } else {
        alert("Harap isi semua field yang diperlukan sebelum melanjutkan.");
    }
});
</script>



<?php include "../footer.php";?>