<?php
require_once __DIR__ . '/../kap-config.php';

define('GED_CLIENT_ID',     '657289384060-p9pjbrpafnpliu26pbn73rdkb2iio4ub.apps.googleusercontent.com');
define('GED_CLIENT_SECRET', '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');

$shToken  = $_GET['token']  ?? '';
$shFileId = $_GET['fileId'] ?? '';
$shPw     = $_GET['pw']     ?? '';
$shDl     = $_GET['dl']     ?? '';

if (!$shToken) { http_response_code(400); exit('Token manquant'); }

try {
    $pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET, DB_USER, DB_PASS, [PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION]);

    $stmt = $pdo->prepare('SELECT * FROM ged_partages WHERE token=? AND actif=1');
    $stmt->execute([$shToken]); $p = $stmt->fetch();
    if (!$p) { http_response_code(404); exit('Lien invalide'); }
    if ($p['date_expiration'] && strtotime($p['date_expiration']) < time()) { http_response_code(403); exit('Lien expire'); }
    if ($p['nb_acces_max'] && $p['nb_acces'] >= $p['nb_acces_max']) { http_response_code(403); exit('Acces max atteint'); }
    if ($p['password_hash'] && !password_verify($shPw, $p['password_hash'])) { http_response_code(401); exit('Mot de passe incorrect'); }

    $driveId = $shFileId ?: $p['drive_item_id'];

    // Token Drive
    $driveTk = '';
    $row = $pdo->prepare("SELECT valeur FROM app_settings WHERE cle='ged_access_token'");
    $row->execute(); $tkData = $row->fetchColumn();
    if ($tkData) {
        $arr = json_decode($tkData, true);
        if (!empty($arr['access_token']) && ($arr['expires_at']??0) > time()+60)
            $driveTk = $arr['access_token'];
    }
    if (!$driveTk) {
        $row2 = $pdo->prepare("SELECT valeur FROM app_settings WHERE cle='ged_refresh_token'");
        $row2->execute(); $rt = $row2->fetchColumn();
        if ($rt) {
            $ch = curl_init('https://oauth2.googleapis.com/token');
            curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true,
                CURLOPT_POSTFIELDS=>http_build_query(['client_id'=>GED_CLIENT_ID,'client_secret'=>GED_CLIENT_SECRET,'refresh_token'=>$rt,'grant_type'=>'refresh_token']),
                CURLOPT_HTTPHEADER=>['Content-Type: application/x-www-form-urlencoded']]);
            $res = curl_exec($ch); curl_close($ch);
            $arr2 = json_decode($res, true);
            $driveTk = $arr2['access_token'] ?? '';
        }
    }
    if (!$driveTk) { http_response_code(500); exit('Token Drive indisponible'); }

    // Metadata
    $ch = curl_init("https://www.googleapis.com/drive/v3/files/$driveId?fields=name,mimeType,size&supportsAllDrives=true");
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_HTTPHEADER=>["Authorization: Bearer $driveTk"]]);
    $meta = json_decode(curl_exec($ch), true) ?? []; curl_close($ch);
    $name = $meta['name'] ?? 'document';
    $mime = $meta['mimeType'] ?? 'application/octet-stream';

    // Export Google natifs
    $exports = [
        'application/vnd.google-apps.document'     => 'application/pdf',
        'application/vnd.google-apps.spreadsheet'  => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.google-apps.presentation' => 'application/pdf',
    ];
    if (isset($exports[$mime])) {
        $mime   = $exports[$mime];
        $dlUrl  = "https://www.googleapis.com/drive/v3/files/$driveId/export?mimeType=".urlencode($mime)."&supportsAllDrives=true";
    } else {
        $dlUrl  = "https://www.googleapis.com/drive/v3/files/$driveId?alt=media&supportsAllDrives=true";
    }

    $inline = !$shDl && in_array($mime, ['application/pdf','image/jpeg','image/png','image/gif','image/webp','text/plain']);

    header('Content-Type: ' . $mime);
    header('Content-Disposition: '.($inline ? 'inline' : 'attachment').'; filename="'.rawurlencode($name).'"');
    header('Cache-Control: private, max-age=300');
    header('X-Content-Type-Options: nosniff');

    $ch2 = curl_init($dlUrl);
    curl_setopt_array($ch2, [
        CURLOPT_RETURNTRANSFER => false,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER     => ["Authorization: Bearer $driveTk"],
        CURLOPT_WRITEFUNCTION  => function($c, $d) { echo $d; return strlen($d); },
    ]);
    curl_exec($ch2); curl_close($ch2);

} catch (Exception $e) {
    http_response_code(500);
    exit('Erreur: ' . $e->getMessage());
}
