<?php
// verifikasiotp.php

header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'rate_limit.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on verifikasiotp.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Rate limit (misal 5x per menit)
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 5, 60, $identifier);

$input_raw = file_get_contents('php://input');
$input = json_decode($input_raw, true);
$input = sanitize_input($input);

// Pastikan ada `email` dan `otp`
if (empty($input['email']) || empty($input['otp'])) {
    http_response_code(400);
    echo json_encode(['error' => 'email and otp are required']);
    log_activity("Missing fields in verifikasiotp from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

$email   = $input['email'];
$otpUser = $input['otp'];

// Validasi email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['error' => 'Invalid email format']);
    log_activity("Invalid email format '$email' in verifikasiotp.");
    exit;
}

try {
    // ---------------
    // 1) CEK JIKA AKUN DEMO
    // ---------------
    if ($email === 'admin@demo.com' && $otpUser === '888888') {
        $token = bin2hex(random_bytes(32)); // 64 char hex
        $tokenExpires = date('Y-m-d H:i:s', time() + 604800); // 7 hari

        // Simpan token ke database
        $stmt = $pdo->prepare("
            INSERT INTO tokens (user_id, token, expires_at) 
            VALUES ((SELECT id FROM users WHERE email = ?), ?, ?)
        ");
        $stmt->execute([$email, $token, $tokenExpires]);

        http_response_code(200);
        echo json_encode([
            'message'    => 'Demo OTP verified. Token generated.',
            'token'      => $token,
            'expires_at' => $tokenExpires
        ]);
        log_activity("Demo user '$email' OTP verified. Token issued.");
        exit;
    }

    // ---------------
    // 2) CARI USER DI DATABASE
    // ---------------
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
        log_activity("OTP verification failed: email '$email' not found.");
        exit;
    }

    // ---------------
    // 3) HASH OTP YANG DIMASUKKAN USER
    // ---------------
    $hashedInput = md5($otpUser);

    // ---------------
    // 4) CEK OTP DI DATABASE
    // ---------------
    $stmt = $pdo->prepare("
        SELECT * 
        FROM otps 
        WHERE user_id = ? 
          AND otp_code = ? 
          AND expires_at >= NOW()
        ORDER BY id DESC
        LIMIT 1
    ");
    $stmt->execute([$user['id'], $hashedInput]);
    $otpRecord = $stmt->fetch();

    if (!$otpRecord) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired OTP']);
        log_activity("Invalid/expired OTP for user '$email'.");
        exit;
    }

    // ---------------
    // 5) BUAT TOKEN LOGIN
    // ---------------
    $token = bin2hex(random_bytes(32)); // 64 char hex
    $tokenExpires = date('Y-m-d H:i:s', time() + 604800); // 7 hari

    $stmt = $pdo->prepare("
        INSERT INTO tokens (user_id, token, expires_at) 
        VALUES (?, ?, ?)
    ");
    $stmt->execute([$user['id'], $token, $tokenExpires]);

    // (Opsional) Hapus OTP dari tabel agar tidak bisa digunakan ulang
    $stmtDel = $pdo->prepare("DELETE FROM otps WHERE id = ?");
    $stmtDel->execute([$otpRecord['id']]);

    // ---------------
    // 6) RESPONSE
    // ---------------
    http_response_code(200);
    echo json_encode([
        'message'    => 'OTP verified. Token generated.',
        'token'      => $token,
        'expires_at' => $tokenExpires
    ]);
    log_activity("User '$email' OTP verified. Token issued.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
    log_activity("verifikasiotp.php error: " . $e->getMessage());
    exit;
}
