<?php

require_once "config.php";

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

if ($method === '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 lstatus FROM tbtmpwa WHERE cnotelp = '$cnohp' LIMIT 1");
        
        if ($cek->num_rows > 0) {
            $dcek = $cek->fetch_assoc();
            if ($dcek['lstatus'] == 1) { 
                $conn->query("UPDATE tbtmpwa SET cotp = '$cotp', lstatus = '0', cnama = '$cnama' WHERE cnotelp = '$cnohp'");
                http_response_code(200);
                echo json_encode(['message' => 'Berhasil mengupdate OTP']);
            } else {
                http_response_code(409);
                echo json_encode(['message' => 'Insert Failed', 'error' => 'Email sudah terdaftar dengan status 0']);
            }
        } else {
            $conn->query("INSERT INTO tbtmpwa (cnotelp, cnama, cotp, cketerangan, lstatus) VALUES ('$cnohp', '$cnama', '$cotp', '', '0')");
            http_response_code(200);
            echo json_encode(['message' => 'Berhasil menambahkan member baru dan mengirim OTP']);
        }
    } catch (Exception $e) {
        http_response_code(409);
        echo json_encode(['message' => 'Gagal Generate OTP', 'error' => $e->getMessage()]);
    }
} elseif ($method === 'PUT') {
    $data = json_decode(file_get_contents('php://input'), true);
    $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);
    var_dump($newNomer);
    
    $cek = $conn->query("SELECT lstatus FROM tbtmpwa WHERE cnotelp = '$cnohp' 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 tbtmpwa WHERE cnotelp = '$cnohp'");


        $conn->query("INSERT INTO tbmember SELECT '$cemail', 'gZOOjM5J99sd8JSF4aisaA==' , '$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']);
    }
} else {
    http_response_code(405);
    echo json_encode(['message' => 'Metode tidak diizinkan']);
}

?>
