<?php
// api/verifikasi_otp.php
session_start();
include '../config/database.php';

header('Content-Type: application/json');

// Proteksi Dasar
if (!isset($_SESSION['user_id']) || empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    echo json_encode(['status' => 'error', 'message' => 'Akses tidak sah.']);
    exit;
}

$user_id = $_SESSION['user_id'];
$input_otp = trim($_POST['otp'] ?? '');

if (empty($input_otp) || strlen($input_otp) !== 6) {
    echo json_encode(['status' => 'error', 'message' => 'Format kode OTP tidak valid.']);
    exit;
}

date_default_timezone_set('Asia/Jakarta');
$waktu_sekarang = date('Y-m-d H:i:s');

// Cek OTP di Database
$stmt = $conn->prepare("SELECT otp_code, otp_expiry FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();
$user_data = $res->fetch_assoc();
$stmt->close();

// Validasi
if (empty($user_data['otp_code'])) {
    echo json_encode(['status' => 'error', 'message' => 'Anda belum meminta kode OTP.']);
    exit;
}

if ($input_otp !== $user_data['otp_code']) {
    echo json_encode(['status' => 'error', 'message' => 'Kode OTP salah.']);
    exit;
}

if ($waktu_sekarang > $user_data['otp_expiry']) {
    echo json_encode(['status' => 'error', 'message' => 'Kode OTP sudah kedaluwarsa. Silakan muat ulang halaman dan minta kode baru.']);
    exit;
}

// JIKA SUKSES: Ubah status jadi 'pending' dan hapus OTP agar tidak bisa dipakai 2 kali
$stmt_update = $conn->prepare("UPDATE users SET status_broadcast = 'pending', otp_code = NULL, otp_expiry = NULL WHERE id = ?");
$stmt_update->bind_param("i", $user_id);

if ($stmt_update->execute()) {
    echo json_encode(['status' => 'success']);
} else {
    echo json_encode(['status' => 'error', 'message' => 'Gagal memperbarui status ke database.']);
}

$stmt_update->close();
?>