<?php
// api/forgot_password_initiate.php

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

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['phone_number'] ?? '';

    if (empty($phoneNumber)) {
        echo json_encode(['success' => false, 'message' => 'Nomor Telepon harus diisi.']);
        exit();
    }

    // Validasi server-side untuk format nomor telepon (misal: 628xxxx)
    if (!preg_match('/^62[0-9]{8,13}$/', $phoneNumber)) { // Regex untuk 62 diikuti 8-13 digit
        echo json_encode(['success' => false, 'message' => 'Format nomor telepon tidak valid. Gunakan format 62xxxxxxxxxx.']);
        exit();
    }

    try {
        $pdo->beginTransaction();

        // Cari user berdasarkan nomor telepon
        $stmt = $pdo->prepare("SELECT id, phone_number, is_verified FROM users WHERE phone_number = :phone_number");
        $stmt->execute([':phone_number' => $phoneNumber]);
        $user = $stmt->fetch();

        if (!$user) {
            // Untuk keamanan, jangan beri tahu jika nomor tidak terdaftar secara spesifik.
            // Bisa memberikan pesan generik atau pesan sukses palsu.
            // Untuk debugging, kita bisa lebih spesifik dulu.
            echo json_encode(['success' => false, 'message' => 'Nomor telepon tidak terdaftar.']);
            $pdo->rollBack();
            exit();
        }

        if ($user['is_verified'] == 0) {
            echo json_encode(['success' => false, 'message' => 'Akun Anda belum terverifikasi. Silakan selesaikan pendaftaran.']);
            $pdo->rollBack();
            exit();
        }

        $userId = $user['id'];

        // Implementasi cooldown untuk resend OTP (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);
        $expiresAt = date('Y-m-d H:i:s', strtotime('+5 minutes')); // OTP berlaku 5 menit

        // Masukkan OTP baru ke database
        // Tandai OTP lama yang belum digunakan sebagai sudah digunakan jika ada (opsional, untuk kebersihan)
        $stmt = $pdo->prepare("UPDATE otp_codes SET is_used = 1 WHERE user_id = :user_id AND is_used = 0");
        $stmt->execute([':user_id' => $userId]);

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

        // --- KIRIM OTP VIA WHATSAPP API Fonnte ---
        $fonnteApiToken = 'zeUCZ5io8H5B7E3rNkqN'; // Pastikan ini API Key Fonnte Anda
        $message = "Kode OTP Anda untuk reset password 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);
        $curlError = curl_error($curl); // Dapatkan error cURL jika ada
        curl_close($curl);

        if ($curlError) {
            error_log("Fonnte API cURL Error: " . $curlError);
            echo json_encode(['success' => false, 'message' => 'Gagal terhubung ke layanan WhatsApp. Silakan coba lagi.']);
            exit();
        }

        $waResponse = json_decode($response, true);

        if ($httpCode == 200 && isset($waResponse['status']) && $waResponse['status'] == true) {
            echo json_encode(['success' => true, 'message' => 'Kode verifikasi telah dikirim ke WhatsApp Anda.']);
        } else {
            error_log("WhatsApp reset password OTP send failed for user $userId. Fonnte Response: " . ($response ?: 'No response') . ", HTTP Code: " . $httpCode);
            $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();
        error_log("Forgot password initiate PDO error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan server database. Silakan coba lagi.']);
    } catch (\Exception $e) {
        $pdo->rollBack();
        error_log("Forgot password initiate general error: " . $e->getMessage());
        echo json_encode(['success' => false, 'message' => 'Terjadi kesalahan server umum. Silakan coba lagi.']);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Metode request tidak diizinkan.']);
}
?>