<?php
// api/register_initiate_otp.php

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

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);

    $fullName = $input['fullName'] ?? '';
    $emailOrUsername = $input['emailOrUsername'] ?? '';
    $phoneNumber = $input['phoneNumber'] ?? '';
    $password = $input['password'] ?? '';
    $confirmPassword = $input['confirmPassword'] ?? '';

    // Validasi input
    if (empty($fullName) || empty($emailOrUsername) || empty($phoneNumber) || empty($password) || empty($confirmPassword)) {
        echo json_encode(['success' => false, 'message' => 'Semua field harus diisi.']);
        exit();
    }
    if ($password !== $confirmPassword) {
        echo json_encode(['success' => false, 'message' => 'Password dan Konfirmasi Password tidak cocok.']);
        exit();
    }
    if (strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password minimal 6 karakter.']);
        exit();
    }
    // Validasi format nomor telepon (hanya contoh sederhana, sesuaikan dengan kebutuhan)
    // Pastikan nomor diawali '62' dan tidak ada karakter non-digit lainnya
    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 {
        // Cek apakah email/username atau nomor telepon sudah terdaftar
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email_or_username = :email_or_username OR phone_number = :phone_number");
        $stmt->execute([
            ':email_or_username' => $emailOrUsername,
            ':phone_number' => $phoneNumber
        ]);
        if ($stmt->fetch()) {
            echo json_encode(['success' => false, 'message' => 'Email/Username atau Nomor Telepon sudah terdaftar.']);
            exit();
        }

        // Hash password
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);

        // --- Simpan data pengguna sementara di tabel users dengan is_verified = 0 ---
        $pdo->beginTransaction(); // Mulai transaksi

        $stmt = $pdo->prepare("INSERT INTO users (full_name, email_or_username, phone_number, password_hash, is_verified) VALUES (:full_name, :email_or_username, :phone_number, :password_hash, 0)");
        $stmt->execute([
            ':full_name' => $fullName,
            ':email_or_username' => $emailOrUsername,
            ':phone_number' => $phoneNumber,
            ':password_hash' => $passwordHash
        ]);
        $userId = $pdo->lastInsertId();

        // --- Hasilkan dan Simpan OTP ---
        $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

        $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 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', // Ini penting untuk Fonnte, memastikan format nomor
            ),
          CURLOPT_HTTPHEADER => array(
            "Authorization: $fonnteApiToken"
          ),
        ));
        $response = curl_exec($curl);
        $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);

        $waResponse = json_decode($response, true);

        // Periksa respons dari Fonnte API
        if ($httpCode == 200 && isset($waResponse['status']) && $waResponse['status'] == true) {
            echo json_encode(['success' => true, 'message' => 'Pendaftaran awal berhasil, kode OTP telah dikirim ke WhatsApp Anda.']);
        } else {
            // Jika pengiriman WA gagal, rollback transaksi untuk mencegah user terdaftar tanpa OTP terkirim
            $pdo->rollBack();
            error_log("WhatsApp send failed for user $userId. Fonnte Response: " . ($response ?: 'No response'));
            // Anda bisa tambahkan pesan error spesifik dari Fonnte jika ada di $waResponse
            $errorMessage = isset($waResponse['reason']) ? $waResponse['reason'] : 'Gagal mengirim OTP WhatsApp. Silakan coba lagi.';
            echo json_encode(['success' => false, 'message' => $errorMessage]);
        }

    } catch (\PDOException $e) {
        $pdo->rollBack(); // Rollback transaksi jika ada error database
        error_log("Register initiate OTP error: " . $e->getMessage());
        // Cek jika error karena duplikasi (kode 23000)
        if ($e->getCode() == 23000) {
            echo json_encode(['success' => false, 'message' => 'Email/Username atau Nomor Telepon sudah terdaftar.']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan server saat pendaftaran.']);
        }
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak diizinkan.']);
}
?>