<?php
// api/forgot_password_verify_otp.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'] ?? '';
    $otpCode = $input['otp_code'] ?? '';
    $newPassword = $input['new_password'] ?? '';

    if (empty($phoneNumber) || empty($otpCode) || empty($newPassword)) {
        echo json_encode(['success' => false, 'message' => 'Nomor telepon, OTP, dan password baru harus diisi.']);
        exit();
    }

    if (strlen($newPassword) < 6) {
        echo json_encode(['success' => false, 'message' => 'Password baru minimal 6 karakter.']);
        exit();
    }

    try {
        $pdo->beginTransaction();

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

        if (!$user) {
            echo json_encode(['success' => false, 'message' => 'Nomor telepon tidak terdaftar.']);
            $pdo->rollBack();
            exit();
        }

        $userId = $user['id'];

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

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

        if ($otpData['is_used']) {
            echo json_encode(['success' => false, 'message' => 'Kode OTP sudah digunakan.']);
            $pdo->rollBack();
            exit();
        }

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

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

        // Update password pengguna dan set is_verified jika belum
        $stmt = $pdo->prepare("UPDATE users SET password_hash = :password_hash, is_verified = 1 WHERE id = :user_id");
        $stmt->execute([
            ':password_hash' => $passwordHash,
            ':user_id' => $userId
        ]);

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

        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Password berhasil direset. Silakan login dengan password baru Anda.']);

    } catch (\PDOException $e) {
        $pdo->rollBack();
        error_log("Forgot password verify OTP 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 verify OTP 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.']);
}
?>