<?php
// api/register_verify_otp.php

header('Content-Type: application/json');
require_once 'db_connect.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $emailOrUsername = $input['emailOrUsername'] ?? ''; // Dari userDataTemp
    $otpCode = $input['otpCode'] ?? '';

    if (empty($emailOrUsername) || empty($otpCode)) {
        echo json_encode(['success' => false, 'message' => 'Email/Username dan Kode OTP harus diisi.']);
        exit();
    }

    try {
        $pdo->beginTransaction();

        // Dapatkan user_id dari email/username
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email_or_username = :email_or_username AND is_verified = 0");
        $stmt->execute([':email_or_username' => $emailOrUsername]);
        $user = $stmt->fetch();

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'Pengguna tidak ditemukan atau sudah terverifikasi.']);
            $pdo->rollBack();
            exit();
        }
        $userId = $user['id'];

        // Cek OTP
        $stmt = $pdo->prepare("SELECT id, expires_at, is_used FROM otp_codes WHERE user_id = :user_id AND otp_code = :otp_code AND is_used = 0 ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([
            ':user_id' => $userId,
            ':otp_code' => $otpCode
        ]);
        $otpData = $stmt->fetch();

        if ($otpData) {
            // Cek apakah OTP sudah kedaluwarsa
            if (new DateTime() > new DateTime($otpData['expires_at'])) {
                echo json_encode(['success' => false, 'message' => 'Kode OTP sudah kedaluwarsa.']);
                $pdo->rollBack();
                exit();
            }

            // Tandai OTP sebagai sudah digunakan
            $stmt = $pdo->prepare("UPDATE otp_codes SET is_used = 1 WHERE id = :id");
            $stmt->execute([':id' => $otpData['id']]);

            // Verifikasi pengguna (set is_verified = 1)
            $stmt = $pdo->prepare("UPDATE users SET is_verified = 1 WHERE id = :user_id");
            $stmt->execute([':user_id' => $userId]);

            $pdo->commit(); // Commit transaksi
            echo json_encode(['success' => true, 'message' => 'Verifikasi OTP berhasil! Akun Anda sekarang aktif.']);

        } else {
            echo json_encode(['success' => false, 'message' => 'Kode OTP tidak valid.']);
            $pdo->rollBack();
        }

    } catch (\PDOException $e) {
        $pdo->rollBack();
        error_log("Register verify OTP error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan server saat verifikasi OTP.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak diizinkan.']);
}
?>