<?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'] ?? '';
$shPw    = $_GET['pw']    ?? '';

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['type'] !== 'dossier') { http_response_code(400); exit('Pas un dossier'); }
    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'); }
    if ($p['password_hash'] && !password_verify($shPw, $p['password_hash'])) { http_response_code(401); exit('Mot de passe incorrect'); }

    // 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'); }

    // Lister les fichiers du dossier
    $folderId = $p['drive_item_id'];
    $isSD = strlen($folderId) > 2 && substr($folderId, 0, 2) === '0A';
    $fields = urlencode('files(id,name,mimeType,size)');
    if ($isSD) {
        $listUrl = "https://www.googleapis.com/drive/v3/files?driveId=$folderId&corpora=drive&includeItemsFromAllDrives=true&supportsAllDrives=true&fields=$fields&pageSize=100&q=".urlencode("trashed=false");
    } else {
        $q = urlencode("'$folderId' in parents and trashed=false");
        $listUrl = "https://www.googleapis.com/drive/v3/files?q=$q&fields=$fields&pageSize=100&supportsAllDrives=true&includeItemsFromAllDrives=true";
    }
    $ch = curl_init($listUrl);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_HTTPHEADER=>["Authorization: Bearer $driveTk"]]);
    $files = json_decode(curl_exec($ch), true)['files'] ?? []; curl_close($ch);

    // Filtrer les dossiers
    $files = array_filter($files, fn($f) => $f['mimeType'] !== 'application/vnd.google-apps.folder');

    if (empty($files)) { http_response_code(204); exit('Dossier vide'); }

    // Export MIME pour Google natifs
    $exports = [
        'application/vnd.google-apps.document'     => ['mime'=>'application/pdf', 'ext'=>'.pdf'],
        'application/vnd.google-apps.spreadsheet'  => ['mime'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'ext'=>'.xlsx'],
        'application/vnd.google-apps.presentation' => ['mime'=>'application/pdf', 'ext'=>'.pdf'],
    ];

    // Créer le ZIP en mémoire
    $zipName = preg_replace('/[^a-zA-Z0-9_\-]/', '_', $p['nom_affichage']) . '.zip';
    $tmpZip  = tempnam(sys_get_temp_dir(), 'ged_zip_');
    $zip = new ZipArchive();
    $zip->open($tmpZip, ZipArchive::OVERWRITE);

    foreach ($files as $f) {
        $mime = $f['mimeType'];
        $name = $f['name'];
        if (isset($exports[$mime])) {
            $dlUrl = "https://www.googleapis.com/drive/v3/files/{$f['id']}/export?mimeType=".urlencode($exports[$mime]['mime'])."&supportsAllDrives=true";
            $name  = pathinfo($name, PATHINFO_FILENAME) . $exports[$mime]['ext'];
        } else {
            $dlUrl = "https://www.googleapis.com/drive/v3/files/{$f['id']}?alt=media&supportsAllDrives=true";
        }
        $ch = curl_init($dlUrl);
        curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_FOLLOWLOCATION=>true, CURLOPT_HTTPHEADER=>["Authorization: Bearer $driveTk"]]);
        $content = curl_exec($ch); curl_close($ch);
        if ($content) $zip->addFromString($name, $content);
    }
    $zip->close();

    // Envoyer le ZIP
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="'.rawurlencode($zipName).'"');
    header('Content-Length: '.filesize($tmpZip));
    header('Cache-Control: private, max-age=0');
    readfile($tmpZip);
    unlink($tmpZip);

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