<?php
require_once 'config/database.php';
require_once 'utils/helpers.php';

try {

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        Helpers::sendResponse(false, 'Method not allowed', null, 405);
    }

    $data = json_decode(file_get_contents("php://input"));

    // Validate required fields
    if (empty($data->email) || empty($data->otp)) {
        Helpers::sendResponse(false, 'Email and OTP are required', null, 400);
    }

    $database = new Database();
    $db = $database->getConnection();

    // Check if OTP is valid
    $query = "SELECT id, verification_code, verification_expires, is_verified 
          FROM users 
          WHERE email = :email";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':email', $data->email);
    $stmt->execute();

    if ($stmt->rowCount() === 0) {
        Helpers::sendResponse(false, 'User not found', null, 404);
    }

    $user = $stmt->fetch();

    if ($user['is_verified']) {
        Helpers::sendResponse(false, 'Email already verified', null, 400);
    }

    if ($user['verification_code'] !== $data->otp) {
        Helpers::sendResponse(false, 'Invalid verification code', null, 400);
    }

    if (strtotime($user['verification_expires']) < time()) {
        Helpers::sendResponse(false, 'Verification code has expired', null, 400);
    }

    // Mark as verified
    $query = "UPDATE users 
          SET is_verified = TRUE, 
              verification_code = NULL, 
              verification_expires = NULL 
          WHERE id = :id";

    $stmt = $db->prepare($query);
    $stmt->bindParam(':id', $user['id']);

    if ($stmt->execute()) {
        Helpers::sendResponse(true, 'Email verified successfully', [
            'user_id' => $user['id']
        ]);
    } else {
        Helpers::sendResponse(false, 'Verification failed', null, 500);
    }
} catch (PDOException $e) {
    ErrorLogger::logDatabaseError($e, $logQuery ?? 'Verification query', [
        'endpoint' => 'auth/verify',
        'user_id' => $user->user_id ?? 'unknown'
    ]);
    Helpers::sendResponse(false, 'An error occurred during verification', null, 500);
} catch (Exception $e) {
    ErrorLogger::logError($e, [
        'endpoint' => 'auth/verify'
    ]);
    Helpers::sendResponse(false, 'An unexpected error occurred during verification', null, 500);
}
