<?php
// api/resend_otp_register.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);

    $phoneNumber = $input['phoneNumber'] ?? '';

    if (empty($phoneNumber)) {
        echo json_encode(['success' => false, 'message' => 'Nomor telepon harus diisi.']);
        exit();
    }
    // Validasi format nomor telepon
    if (!preg_match('/^62[0-9]{9,13}$/', $phoneNumber)) { // Contoh: 628xxxxxxxx (total 11-15 digit)
        echo json_encode(['success' => false, 'message' => 'Format nomor telepon tidak valid. Gunakan format 628xxxxxxxx.']);
        exit();
    }

    try {
        $pdo->beginTransaction();

        // Cari user yang belum terverifikasi dengan nomor telepon ini
        // Penting: Pastikan is_verified = 0, agar hanya user yang belum verify yang bisa resend
        $stmt = $pdo->prepare("SELECT id FROM users WHERE phone_number = :phone_number AND is_verified = 0");
        $stmt->execute([':phone_number' => $phoneNumber]);
        $user = $stmt->fetch();

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

        // Implementasi cooldown untuk resend OTP (misal, 60 detik)
        $stmt = $pdo->prepare("SELECT created_at FROM otp_codes WHERE user_id = :user_id ORDER BY created_at DESC LIMIT 1");
        $stmt->execute([':user_id' => $userId]);
        $lastOtp = $stmt->fetch();

        if ($lastOtp) {
            $lastOtpTime = new DateTime($lastOtp['created_at']);
            $currentTime = new DateTime();
            $interval = $currentTime->getTimestamp() - $lastOtpTime->getTimestamp();
            if ($interval < 60) { // Cooldown 60 detik
                echo json_encode(['success' => false, 'message' => 'Mohon tunggu ' . (60 - $interval) . ' detik sebelum mengirim ulang OTP.']);
                $pdo->rollBack();
                exit();
            }
        }

        // Hasilkan OTP baru
        $otpCode = str_pad(rand(0, 999999), 6, '0', STR_PAD_LEFT); // 6 digit OTP
        $expiresAt = date('Y-m-d H:i:s', strtotime('+5 minutes')); // OTP berlaku 5 menit

        // Masukkan OTP baru ke database
        $stmt = $pdo->prepare("INSERT INTO otp_codes (user_id, otp_code, expires_at) VALUES (:user_id, :otp_code, :expires_at)");
        $stmt->execute([
            ':user_id' => $userId,
            ':otp_code' => $otpCode,
            ':expires_at' => $expiresAt
        ]);

        $pdo->commit(); // Commit transaksi

        // --- KIRIM OTP VIA WHATSAPP API Fonnte ---
        $fonnteApiToken = 'zeUCZ5io8H5B7E3rNkqN'; // <--- INI SUDAH DIUPDATE
        $message = "Kode OTP baru Anda untuk pendaftaran Aplikasi Lapor Bumil adalah: " . $otpCode . ". Kode ini berlaku 5 menit. Jangan bagikan kode ini kepada siapa pun.";

        $curl = curl_init();
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://api.fonnte.com/send',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS => array(
                'target' => $phoneNumber,
                'message' => $message,
                'countryCode' => '62',
            ),
          CURLOPT_HTTPHEADER => array(
            "Authorization: $fonnteApiToken"
          ),
        ));
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        $waResponse = json_decode($response, true);

        if ($httpCode == 200 && isset($waResponse['status']) && $waResponse['status'] == true) {
            echo json_encode(['success' => true, 'message' => 'OTP baru berhasil dikirim ke WhatsApp Anda.']);
        } else {
            error_log("WhatsApp resend failed for user $userId. Fonnte Response: " . ($response ?: 'No response'));
            $errorMessage = isset($waResponse['reason']) ? $waResponse['reason'] : 'Gagal mengirim ulang OTP WhatsApp. Silakan coba lagi.';
            echo json_encode(['success' => false, 'message' => $errorMessage]);
        }

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