<?php
// db/service-verification-handler.php
header('Content-Type: application/json');
require_once '../core/api.php'; 

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed.']);
    exit;
}

// Obtener datos del cuerpo de la solicitud JSON
$input = file_get_contents('php://input');
$data = json_decode($input, true);

$token = $data['token'] ?? '';
$rating = $data['rating'] ?? 5; 
$feedback = $data['feedback'] ?? null;

// Validar datos mínimos
if (empty($token)) {
    echo json_encode(['success' => false, 'message' => 'Verification token is missing.']);
    exit;
}

try {
    // 1. Iniciar transacción
    $pdo->beginTransaction();

    // 2. Buscar y bloquear la cita para evitar actualizaciones simultáneas
    $stmt = $pdo->prepare("SELECT id, status FROM unique_appointments WHERE verification_token = ? AND status IN ('confirmed', 'pending') FOR UPDATE");
    $stmt->execute([$token]);
    $appointment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$appointment) {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Service already verified or link is invalid/expired.']);
        exit;
    }

    $sql_update = "UPDATE unique_appointments SET 
        status = 'completed', 
        client_rating = ?, 
        client_feedback = ?, 
        verified_at = NOW(),
        verification_token = NULL 
        WHERE id = ?";
        
    $stmt_update = $pdo->prepare($sql_update);
    $success = $stmt_update->execute([
        $rating, 
        $feedback, 
        $appointment['id']
    ]);

    if ($success) {
        $pdo->commit();
        echo json_encode(['success' => true, 'message' => 'Service verified and feedback saved successfully.']);
    } else {
        $pdo->rollBack();
        echo json_encode(['success' => false, 'message' => 'Database update failed.']);
    }

} catch (PDOException $e) {
    if (isset($pdo) && $pdo->inTransaction()) {
        $pdo->rollBack();
    }
    error_log("Verification Error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An internal server error occurred.']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'An unknown error occurred.']);
}
?>