<?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("DELETE FROM tbmemberreg WHERE cemail = '$cemail'");
        $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'];
            $cotp = rand(10000, 99999);
            
            // Cek apakah email sudah ada di tabel tbmemberreg
            $cek = $conn->query("SELECT cstatus FROM tbmemberreg WHERE cemail = '$cemail' LIMIT 1");
            
            if ($cek->num_rows > 0) {
                // Jika email sudah ada, lakukan update
                $dcek = $cek->fetch_assoc();
                if ($dcek['cstatus'] == 0) {
                    // 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 Caffe Galss 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 = 'KKB One-Time Password (OTP): ' . $cotp;
                    $mail->send();
                    
                    // Update OTP untuk email tersebut
                    $conn->query("UPDATE tbmemberreg SET cotp = '$cotp' WHERE cemail = '$cemail'");
                    http_response_code(200);
                    echo json_encode(['message' => 'OTP terkirim', 'otp' => $cotp]);
                } else {
                    // Jika status pengguna tidak aktif, kirimkan pesan kesalahan
                    http_response_code(403);
                    echo json_encode(['message' => 'Status pengguna tidak aktif']);
                }
            } else {
                // Jika email belum ada, lakukan insert
                $conn->query("INSERT INTO tbmemberreg (cemail, cotp, cstatus) VALUES ('$cemail', '$cotp', 0)");
                
                // 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 Caffe Galss 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 = 'KKB One-Time Password (OTP): ' . $cotp;
                $mail->send();

                http_response_code(200);
                echo json_encode(['message' => 'OTP terkirim dan pengguna baru dibuat', 'otp' => $cotp]);
            }
        } catch (Exception $e) {
            // Tangani kesalahan jika terjadi
            http_response_code(500);
            echo json_encode(['message' => 'Gagal mengirim OTP', 'error' => $e->getMessage()]);
        }
        break;
    case 'PUT':
    $data = json_decode(file_get_contents('php://input'), true);
    try {
        $cemail = $data['cemail'];
        $cotp = $data['cotp'];
        
        // Verifikasi apakah pengguna memiliki cstatus = 1
        $cek =  $conn->query("SELECT cstatus FROM tbmemberreg WHERE cemail = '$cemail' AND cotp = '$cotp' LIMIT 1");
        
        if ($cek->num_rows > 0) {
            $dcek = $cek->fetch_assoc();
            // Jika status pengguna sudah aktif, kirimkan pesan bahwa pengguna sudah menjadi member
            http_response_code(200);
            echo json_encode(['message' => 'Pengguna sudah menjadi member']);
        } else {
            // Jika pengguna tidak memiliki cstatus = 1 atau OTP tidak cocok dengan yang tersimpan dalam database, kirimkan pesan kesalahan
            http_response_code(403);
            echo json_encode(['message' => 'Kode OTP Salah atau Status pengguna tidak aktif']);
        }
    } catch (Exception $e) {
        // Tangani kesalahan jika terjadi
        http_response_code(500);
        echo json_encode(['message' => 'Terjadi kesalahan dalam pemrosesan', 'error' => $e->getMessage()]);
    }
break;


}
?>