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

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

// seting email
$mail = new PHPMailer();
$mail->isSMTP();                                            //Send using SMTP
$mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
$mail->SMTPAuth   = true;                                   //Enable SMTP authentication
$mail->Username   = 'edisby2017@gmail.com';                     //SMTP username
$mail->Password   = 'gawufuthmyqabkos';                               //SMTP password
$mail->SMTPSecure = 'tls';            //Enable implicit TLS encryption
$mail->Port       = 587;
$mail->setFrom('edisby2017@gmail.com', 'kkb');
// end  seting email

require_once "config.php";

header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        $cemail = $_GET['cemail'];
        $cpassword = encode($_GET["cpassword"]);
        $conn->query("UPDATE tbmember SET cpassword = '$cpassword' WHERE cemail = '$cemail'");
        http_response_code(200);
        echo json_encode(['message' => 'Berhasil Set Password']);
        
    break;
    case 'POST':
    $data = json_decode(file_get_contents('php://input'), true);
    try{
        $cemail = $data['cemail'];
        $cnama = $data['cnama'];
        $cnohp = $data['cnohp'];
        $cotp = rand(10000, 99999);
        $cek =  $conn->query(" SELECT cstatus FROM tbmemberreg WHERE cemail = '$cemail' AND cnama = '$cnama' AND cstatus = 0 LIMIT 1");
        if($cek->num_rows > 0){
            $dcek = $cek->fetch_assoc();
            if($dcek['cstatus'] == 1){
                http_response_code(409);
                echo json_encode(['message' => 'Insert Failed', "error" => "email sudah terdaftar"]);
            }else{
                // php mail
                $mail->isHTML(true);
                $mail->addAddress($cemail, $cnama);
                $mail->Subject = 'KKB One-Time Password (OTP)';
                $mail->Body    = '<h1>KKB One-Time Password (OTP)</h1>'
                              . '<p>Halo Member KKB ,</p>'
                              . '<p>Kode OTP Member KKB Anda : <b>' . $cotp . '</b></p>'
                              . '<p>Jika Anda tidak meminta OTP ini, silakan abaikan email ini atau hubungi dukungan. </p>'
                              . '<p>Salam Hangat,<br>KKB</p>';
                $mail->AltBody = '<h1>KKB One-Time Password (OTP)</h1>'
                              . '<p>Halo Member KKB ,</p>'
                              . '<p>Kode OTP Member KKB Anda : <b>' . $cotp . '</b></p>'
                              . '<p>Jika Anda tidak meminta OTP ini, silakan abaikan email ini atau hubungi dukungan. </p>'
                              . '<p>Salam Hangat,<br>KKB</p>';
                $mail->send();
                $conn->query("UPDATE tbmemberreg SET cotp = '$cotp' WHERE cemail = '$cemail' AND cnama = '$cnama'");
                http_response_code(200);
                echo json_encode(['message' => 'OTP Terkirim UPDATE']);
            }
        }else{
                // php mail
                $mail->isHTML(true);      
                $mail->addAddress($cemail, $cnama);
                $mail->Subject = 'KKB One-Time Password (OTP)';
                $mail->Body    = '<h1>KKB One-Time Password (OTP)</h1>'
                              . '<p>Halo Member KKB ,</p>'
                              . '<p>Kode OTP Member KKB Anda : <b>' . $cotp . '</b></p>'
                              . '<p>Jika Anda tidak meminta OTP ini, silakan abaikan email ini atau hubungi dukungan. </p>'
                              . '<p>Salam Hangat,<br>KKB</p>';
                $mail->AltBody = '<h1>KKB One-Time Password (OTP)</h1>'
                              . '<p>Halo Member KKB ,</p>'
                              . '<p>Kode OTP Member KKB Anda : <b>' . $cotp . '</b></p>'
                              . '<p>Jika Anda tidak meminta OTP ini, silakan abaikan email ini atau hubungi dukungan. </p>'
                              . '<p>Salam Hangat,<br>KKB</p>';
                $mail->send();
            $conn->query("INSERT INTO tbmemberreg VALUES ('$cemail', '$cnama', '$cnohp', '$cotp', '0')");
            http_response_code(200);
            echo json_encode(['message' => 'OTP Terkirim NEW']);
        }
    }catch(Exception $e) {
        http_response_code(409);
        echo json_encode(['message' => 'Gagal Genrate OTP', "error" => $mail->ErrorInfo]);
    }
    break;
    case 'PUT':
        $data = json_decode(file_get_contents('php://input'), true);
        $cemail = $data['cemail'];
        $cnama = $data['cnama'];
        $cotp = $data['cotp'];
        $cnohp = $data['cnohp'];
        
                date_default_timezone_set('Asia/Jakarta');
        
        $currentDate = date('Y-m-d H:i:s');


        $tahunBulanHari = substr(date("Y"), -2) . date("m") . date("d");
        
        // Mendapatkan nomor terakhir dari database
        $getLastNumberQuery = $conn->query("SELECT ckodecust FROM tbmember WHERE ckodecust LIKE '9$tahunBulanHari%' ORDER BY ckodecust DESC LIMIT 1");
        
        if ($getLastNumberQuery->num_rows > 0) {
            $lastNumber = (int) substr($getLastNumberQuery->fetch_assoc()['ckodecust'], -3);
            $newNumber = $lastNumber + 1;
        } else {
            // Jika tidak ada nomor sebelumnya, mulai dari 1
            $newNumber = 1;
        }
        
        $newNomer = "9$tahunBulanHari" . sprintf("%03d", $newNumber);
    
        $cek =  $conn->query(" SELECT cstatus FROM tbmemberreg WHERE cemail = '$cemail' AND cotp = '$cotp' LIMIT 1");
        if($cek->num_rows > 0){
            // $conn->query("UPDATE tbmemberreg SET cstatus = '1' WHERE cemail = '$cemail' AND cotp = '$cotp'");
            $conn->query("DELETE FROM tbmemberreg WHERE cemail = '$cemail'");

            $conn->query("INSERT INTO tbmember SELECT '$cemail', 'a1fJnwZFpP5B+R5jbMittQ==' , '$cnama', '$cnohp', '2099-01-01' , '' , '', '', '$newNomer' , NULL , '0', 'SILVER', '', ''");
            http_response_code(200);
            echo json_encode(['message' => 'Berhasil Menjadi member']);
        }else{
            http_response_code(403);
            echo json_encode(['message' => 'Kode OTP Salah']);
        }
    break;
}
?>