<?php
// config.php - Fichier protégé

// Blocage accès direct
if (basename(__FILE__) === basename($_SERVER['REQUEST_METHOD'])) {
    http_response_code(403);
    exit('Accès interdit');
}

// === CONFIGURATION ===
define('DB_HOST', '154.73.92.52');
define('DB_NAME', 'transubd_PointageBus');
define('DB_USER', 'transubd_transub_user');
define('DB_PASS', 'Tr@nsub2@24');

// Clé secrète token (générée aléatoirement, change-la)
define('TOKEN_SECRET', bin2hex(random_bytes(32))); // Ex: 'a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6'

// Durée token (2h)
define('TOKEN_EXPIRY', 7200);

// Rate limiting (max 5 tentatives / 5 min par IP)
define('RATE_LIMIT', 5);
define('RATE_WINDOW', 300); // secondes

// Timezone
date_default_timezone_set('Africa/Algiers');

// === CONNEXION PDO ===
function getPDO() {
    static $pdo = null;
    if ($pdo === null) {
        try {
            $pdo = new PDO(
                "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
                DB_USER,
                DB_PASS,
                [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES => false,
                ]
            );
        } catch (PDOException $e) {
            logAction('DB_ERROR', $e->getMessage());
            http_response_code(503);
            die(json_encode(['success' => false, 'message' => 'Service indisponible']));
        }
    }
    return $pdo;
}

// === Token ===
function generateToken($userId, $role) {
    $payload = json_encode([
        'user_id' => $userId,
        'role' => $role,
        'iat' => time(),
        'exp' => time() + TOKEN_EXPIRY
    ]);
    $signature = hash_hmac('sha256', $payload, TOKEN_SECRET);
    return base64_encode($payload) . '.' . $signature;
}

function verifyToken($token) {
    $parts = explode('.', $token);
    if (count($parts) !== 2) return false;
    $payload = base64_decode($parts[0]);
    $signature = $parts[1];
    $expected = hash_hmac('sha256', $payload, TOKEN_SECRET);
    if (!hash_equals($expected, $signature)) return false;
    $data = json_decode($payload, true);
    if ($data['exp'] < time()) return false;
    return $data;
}

// === Log ===
function logAction($type, $message) {
    $entry = date('Y-m-d H:i:s') . " [$type] $message - IP: " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown') . PHP_EOL;
    file_put_contents(__DIR__ . '/logs/api_log.txt', $entry, FILE_APPEND);
}

// === Rate limiting (contre brute-force) ===
function checkRateLimit($key) {
    $file = __DIR__ . '/logs/rate_' . md5($key) . '.txt';
    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true);
        if (time() - $data['time'] < RATE_WINDOW) {
            if ($data['count'] >= RATE_LIMIT) {
                return false;
            }
            $data['count']++;
        } else {
            $data = ['time' => time(), 'count' => 1];
        }
    } else {
        $data = ['time' => time(), 'count' => 1];
    }
    file_put_contents($file, json_encode($data));
    return true;
}
?>