<?php
/**
 * API pour les pointages (Vente de tickets)
 * Répertoire: Includes/Ventes/
 * Sécurisée avec authentification
 */

include_once __DIR__ . '/../auth_check.php';

// Rate limiting par IP
checkRateLimit($_SERVER['REMOTE_ADDR'] ?? 'unknown');

// Connexion à la base de données
$pdo = getDbConnection();

// Vérifier l'authentification
$auth = checkApiAuth($pdo);
if (!$auth['success']) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Authentification requise']);
    exit;
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

try {
    if ($method === 'GET') {
        if ($action === 'list') {
            // Liste des pointages avec filtres
            $siteId = $_GET['site_id'] ?? null;
            $date = $_GET['date'] ?? date('Y-m-d');
            
            $query = "
                SELECT p.*, u.nom as operateur_nom, u.prenom as operateur_prenom,
                       s.Nom_Site as site_nom
                FROM Pointages p
                LEFT JOIN Utilisateurs u ON p.OperateurID = u.code_utilisateur
                LEFT JOIN Sites s ON p.SiteID = s.SiteID
                WHERE DATE(p.DatePointage) = ?
            ";
            $params = [$date];
            
            if ($siteId) {
                $query .= " AND p.SiteID = ?";
                $params[] = $siteId;
            }
            
            $query .= " ORDER BY p.DatePointage DESC, p.HeurePointage DESC";
            
            $stmt = $pdo->prepare($query);
            $stmt->execute($params);
            echo json_encode(['success' => true, 'data' => $stmt->fetchAll()]);
            exit;
        }
        
        if ($action === 'get' && isset($_GET['id'])) {
            $stmt = $pdo->prepare("SELECT * FROM Pointages WHERE id = ?");
            $stmt->execute([$_GET['id']]);
            $pointage = $stmt->fetch();
            echo json_encode(['success' => (bool)$pointage, 'data' => $pointage]);
            exit;
        }
        
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Action invalide']);
        exit;
    }
    
    if ($method === 'POST') {
        $inputJson = file_get_contents('php://input');
        $input = json_decode($inputJson, true);
        $input = sanitizeInput($input);
        
        $operateurId = $input['OperateurID'] ?? $auth['user_id'];
        $siteId = $input['SiteID'] ?? $auth['site_id'];
        $typePointage = $input['TypePointage'] ?? 'DEBUT'; // DEBUT ou FIN
        $observations = $input['Observations'] ?? '';
        
        if (!$operateurId || !$siteId) {
            http_response_code(400);
            echo json_encode(['success' => false, 'message' => 'OperateurID et SiteID requis']);
            exit;
        }
        
        $stmt = $pdo->prepare("
            INSERT INTO Pointages (OperateurID, SiteID, DatePointage, HeurePointage, TypePointage, Observations)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        
        $now = new DateTime();
        $ok = $stmt->execute([
            $operateurId,
            $siteId,
            $now->format('Y-m-d'),
            $now->format('H:i:s'),
            $typePointage,
            $observations
        ]);
        
        // Journaliser
        logAction($pdo, $auth['user_id'], 'CREATE_POINTAGE', "Type: $typePointage, Opérateur: $operateurId");
        
        echo json_encode(['success' => $ok, 'id' => $pdo->lastInsertId()]);
        exit;
    }
    
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Méthode non supportée']);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Erreur: ' . $e->getMessage()]);
}

function logAction($pdo, $userId, $action, $details) {
    try {
        $stmt = $pdo->prepare("
            INSERT INTO Journalisation (DateJournal, TimeJournal, OperateurID, Action, Details) 
            VALUES (?, ?, ?, ?, ?)
        ");
        $stmt->execute([
            date('Y-m-d'),
            date('H:i:s'),
            $userId,
            $action,
            $details
        ]);
    } catch (Exception $e) {
        // Ne pas bloquer
    }
}
?>
