<?php
// À placer dans: public_html/api.transub.dz/apipointagepush/api/fingerprints.php

require_once 'config/database.php';
require_once 'config/auth.php';

$method = $_SERVER['REQUEST_METHOD'];

switch($method) {
    case 'POST':
        $input = json_decode(file_get_contents('php://input'), true);
        if (isset($input['action']) && $input['action'] === 'register') {
            registerFingerprint($pdo);
        } elseif (isset($input['action']) && $input['action'] === 'verify') {
            verifyFingerprint($pdo);
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'Action non spécifiée']);
        }
        break;
        
    case 'GET':
        if (isset($_GET['employee_id'])) {
            listFingerprints($pdo);
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID employé requis']);
        }
        break;
        
    case 'DELETE':
        if (isset($_GET['fingerprint_id'])) {
            deleteFingerprint($pdo);
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID empreinte requis']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'message' => 'Méthode non autorisée']);
}

function registerFingerprint($pdo) {
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $employee_id = $input['employee_id'] ?? null;
    $template = $input['fingerprint_template'] ?? null;
    $position = $input['finger_position'] ?? 'unknown';
    
    if (!$employee_id || !$template) {
        echo json_encode(['success' => false, 'message' => 'Données incomplètes']);
        return;
    }
    
    $stmt = $pdo->prepare("
        INSERT INTO employee_fingerprints (employee_id, fingerprint_template, finger_position) 
        VALUES (?, ?, ?)
    ");
    
    if ($stmt->execute([$employee_id, $template, $position])) {
        echo json_encode(['success' => true, 'message' => 'Empreinte enregistrée']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Erreur base de données']);
    }
}

function listFingerprints($pdo) {
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $employee_id = $_GET['employee_id'];
    
    $stmt = $pdo->prepare("
        SELECT id, employee_id, finger_position, created_at 
        FROM employee_fingerprints 
        WHERE employee_id = ?
        ORDER BY created_at DESC
    ");
    $stmt->execute([$employee_id]);
    $fingerprints = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode(['success' => true, 'fingerprints' => $fingerprints]);
}

function deleteFingerprint($pdo) {
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $fingerprint_id = $_GET['fingerprint_id'];
    $stmt = $pdo->prepare("DELETE FROM employee_fingerprints WHERE id = ?");
    
    if ($stmt->execute([$fingerprint_id])) {
        echo json_encode(['success' => true, 'message' => 'Empreinte supprimée']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Erreur suppression']);
    }
}

function verifyFingerprint($pdo) {
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $employee_id = $input['employee_id'] ?? null;
    $template = $input['fingerprint_template'] ?? null;
    
    if (!$employee_id || !$template) {
        echo json_encode(['success' => false, 'message' => 'Données incomplètes']);
        return;
    }
    
    $stmt = $pdo->prepare("
        SELECT fingerprint_template FROM employee_fingerprints 
        WHERE employee_id = ?
    ");
    $stmt->execute([$employee_id]);
    $stored = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $match = false;
    $score = 0;
    
    foreach ($stored as $row) {
        // NOTE: Implémentez ici la vraie comparaison de templates
        // avec votre algorithme de matching (Hamming distance, etc.)
        // $score = compareTemplates($template, $row['fingerprint_template']);
        // if ($score > 70) { $match = true; break; }
    }
    
    echo json_encode(['success' => true, 'match' => $match, 'score' => $score]);
}

function getBearerToken() {
    $headers = null;
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER['Authorization']);
    } elseif (isset($_SERVER['HTTP_AUTHORIZATION'])) {
        $headers = trim($_SERVER['HTTP_AUTHORIZATION']);
    }
    
    if (!empty($headers) && preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
        return $matches[1];
    }
    return null;
}