<br />
<b>Warning</b>:  Undefined variable $auth in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<br />
<b>Warning</b>:  Trying to access array offset on value of type null in <b>/home/pevo0181/public_html/pia-soft.com/cleania/routes/index.php</b> on line <b>542</b><br />
<?php
// ============================================================
//  PIASCHOOL — fichiers.php
//  Sert les fichiers ministere via lien de telechargement
//  Deposer dans : https://pia-soft.com/piaschool/piaschool1/
// ============================================================

define('DB_HOST', 'localhost');
define('DB_NAME', 'pevo0181_piaschool1');
define('DB_USER', 'pevo0181_piaschool1');
define('DB_PASS', 'Piasoft2021');
define('SYNC_TOKEN', 'Pia2026xK9mZqR7vLSnW4');

// Connexion DB
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]
    );
} catch (Exception $e) {
    http_response_code(500);
    die('Erreur serveur');
}

$action = $_GET['action'] ?? 'telecharger';

// ── Action : uploader un fichier depuis Piaschool desktop
if ($action === 'upload') {
    // Vérifier token
    $token = str_replace('Bearer ', '', $_SERVER['HTTP_AUTHORIZATION'] ?? $_GET['token'] ?? '');
    if ($token !== SYNC_TOKEN) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Token invalide']);
        exit();
    }

    header('Content-Type: application/json');

    $body = json_decode(file_get_contents('php://input'), true) ?? [];
    $nom         = $body['nom']         ?? '';
    $type_examen = $body['type_examen'] ?? '';
    $description = $body['description'] ?? '';
    $data_base64 = $body['data']        ?? '';
    $notifier    = $body['notifier']    ?? false;

    if (!$nom || !$data_base64) {
        echo json_encode(['success' => false, 'message' => 'Nom et data requis']);
        exit();
    }

    // Dossier upload
    $uploadDir = __DIR__ . '/fichiers_examens/';
    if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

    $ext      = strtolower(pathinfo($nom, PATHINFO_EXTENSION));
    $filename = 'examen_' . time() . '_' . rand(1000,9999) . '.' . $ext;
    $filePath = $uploadDir . $filename;

    // Décoder et sauvegarder
    $base64Data = preg_replace('/^data:[^;]+;base64,/', '', $data_base64);
    $fileBytes  = base64_decode($base64Data);
    file_put_contents($filePath, $fileBytes);

    $taille = strlen($fileBytes) < 1024*1024
        ? round(strlen($fileBytes)/1024, 1) . ' KB'
        : round(strlen($fileBytes)/1024/1024, 1) . ' MB';

    // Créer table si nécessaire
    $pdo->exec("CREATE TABLE IF NOT EXISTS examens_fichiers_cloud (
        id INT AUTO_INCREMENT PRIMARY KEY,
        nom VARCHAR(255) NOT NULL,
        type_examen VARCHAR(20) DEFAULT NULL,
        description VARCHAR(255) DEFAULT NULL,
        chemin VARCHAR(500) NOT NULL,
        taille VARCHAR(30) DEFAULT NULL,
        notifies INT DEFAULT 0,
        telechargements INT DEFAULT 0,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

    $stmt = $pdo->prepare("INSERT INTO examens_fichiers_cloud (nom, type_examen, description, chemin, taille) VALUES (?,?,?,?,?)");
    $stmt->execute([$nom, $type_examen, $description ?: null, $filename, $taille]);
    $fichierId = $pdo->lastInsertId();

    $lien = 'https://pia-soft.com/piaschool/piaschool1/fichiers.php?id=' . $fichierId;
    echo json_encode(['success' => true, 'id' => $fichierId, 'lien' => $lien]);
    exit();
}

// ── Action : télécharger un fichier (accès public par lien)
$id = intval($_GET['id'] ?? 0);
if (!$id) {
    http_response_code(400);
    die('ID manquant');
}

// Chercher d'abord dans la table cloud
try {
    $stmt = $pdo->prepare("SELECT * FROM examens_fichiers_cloud WHERE id = ?");
    $stmt->execute([$id]);
    $fichier = $stmt->fetch();

    if (!$fichier) {
        // Chercher dans la table locale (sync depuis desktop)
        $stmt2 = $pdo->prepare("SELECT * FROM examens_fichiers WHERE id = ?");
        $stmt2->execute([$id]);
        $fichier = $stmt2->fetch();
    }
} catch(Exception $e) {
    $fichier = null;
}

if (!$fichier) {
    http_response_code(404);
    // Page 404 propre
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Fichier introuvable</title>
    <style>body{font-family:Arial;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#f1f5f9;margin:0}
    .box{background:white;border-radius:16px;padding:40px;text-align:center;box-shadow:0 4px 20px rgba(0,0,0,0.1)}
    h2{color:#dc2626} p{color:#64748b}</style></head>
    <body><div class="box"><h2>Fichier introuvable</h2><p>Ce fichier n\'existe pas ou a ete supprime.</p></div></body></html>';
    exit();
}

// Fichier cloud : servir depuis le dossier
$uploadDir = __DIR__ . '/fichiers_examens/';
$filePath  = $uploadDir . basename($fichier['chemin']);

if (!file_exists($filePath)) {
    // Afficher page de telechargement avec info
    $nom = $fichier['nom'] ?? 'Document';
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Piaschool — ' . htmlspecialchars($nom) . '</title>
    <style>
    *{margin:0;padding:0;box-sizing:border-box}
    body{font-family:Arial,sans-serif;background:linear-gradient(135deg,#1e293b,#0f172a);min-height:100vh;display:flex;align-items:center;justify-content:center;}
    .box{background:white;border-radius:20px;padding:40px;text-align:center;max-width:500px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,0.3)}
    .logo{width:60px;height:60px;background:#1a73e8;border-radius:16px;display:flex;align-items:center;justify-content:center;font-size:28px;margin:0 auto 16px}
    h2{font-size:20px;margin-bottom:8px}
    p{color:#64748b;font-size:14px;margin-bottom:20px}
    .info{background:#f8fafc;border-radius:10px;padding:16px;margin-bottom:20px;text-align:left}
    .info div{font-size:13px;margin-bottom:6px}
    .badge{display:inline-block;padding:3px 10px;border-radius:20px;font-size:12px;font-weight:700;background:#dbeafe;color:#1d4ed8}
    .err{color:#dc2626;font-size:13px}
    </style></head>
    <body><div class="box">
    <div class="logo">🎓</div>
    <h2>PIASCHOOL</h2>
    <div class="info">
    <div><strong>Document :</strong> ' . htmlspecialchars($fichier['nom'] ?? '') . '</div>
    <div><strong>Type :</strong> <span class="badge">' . htmlspecialchars($fichier['type_examen'] ?? '') . '</span></div>
    <div><strong>Description :</strong> ' . htmlspecialchars($fichier['description'] ?? '') . '</div>
    </div>
    <p class="err">Ce fichier a ete supprime ou est temporairement indisponible.</p>
    </div></body></html>';
    exit();
}

// Compteur téléchargements
try {
    $tbl = isset($fichier['telechargements']) ? 'examens_fichiers_cloud' : 'examens_fichiers';
    $pdo->prepare("UPDATE $tbl SET telechargements = COALESCE(telechargements,0) + 1 WHERE id=?")->execute([$id]);
} catch(Exception $e) {}

// Servir le fichier
$nom = $fichier['nom'] ?? 'document';
$ext = strtolower(pathinfo($nom, PATHINFO_EXTENSION));
$mimeTypes = [
    'pdf'  => 'application/pdf',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'xls'  => 'application/vnd.ms-excel',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  