<?php
// API Pointage Push - Gestion des empreintes digitales
// À placer dans /api/fingerprint/ sur votre serveur cPanel

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE');
header('Access-Control-Allow-Headers: Authorization, Content-Type');

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

$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($path, '/'));

// Récupérer l'ID de l'action depuis l'URL
$action = end($segments);

switch($method) {
    case 'POST':
        if (isset($_POST['action']) && $_POST['action'] === 'register') {
            registerFingerprint();
        } elseif (isset($_POST['action']) && $_POST['action'] === 'verify') {
            verifyFingerprint();
        } 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();
        } else {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'ID employé requis']);
        }
        break;
        
    case 'DELETE':
        if (isset($_GET['fingerprint_id'])) {
            deleteFingerprint();
        } 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() {
    global $pdo;
    
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $employee_id = $_POST['employee_id'] ?? null;
    $template = $_POST['fingerprint_template'] ?? null;
    $position = $_POST['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])) {
        $id = $pdo->lastInsertId();
        echo json_encode([
            'success' => true,
            'message' => 'Empreinte enregistrée',
            'fingerprint_id' => $id
        ]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Erreur base de données']);
    }
}

function listFingerprints() {
    global $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() {
    global $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() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $token = getBearerToken();
    $user = validateToken($token);
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        return;
    }
    
    $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;
    }
    
    // Récupérer toutes les empreintes de l'employé
    $stmt = $pdo->prepare("
        SELECT fingerprint_template FROM employee_fingerprints 
        WHERE employee_id = ?
    ");
    $stmt->execute([$employee_id]);
    $stored = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Comparaison simple - À remplacer par une vraie comparaison de templates
    $match = false;
    $score = 0;
    
    foreach ($stored as $row) {
        // Implémentez ici la comparaison avec votre SDK de matching
        // Exemple simplifié :
        // $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']);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        $requestHeaders = array_change_key_case($requestHeaders, CASE_UPPER);
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }
    
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}
?>