<?php
error_reporting(E_ALL ^ E_NOTICE);
header('Content-Type: application/json; charset=utf-8');

require __DIR__ . '/../vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;

$FOLDER_ID = '11LkB7xSCtRs9_oGMjAWyQjOlYhWS9BVa';
$SA_JSON   = '/home/sicse/public_html/mkj.sicsemkj.com/credenciales/sa.json';

try {
  if (!is_readable($SA_JSON)) throw new Exception("No puedo leer sa.json en: $SA_JSON");

  // Mostrar qué SA estamos usando (debug)
  $saInfo = json_decode(file_get_contents($SA_JSON), true);
  $saMail = $saInfo['client_email'] ?? '(desconocido)';

  $client = new Client();
  $client->setAuthConfig($SA_JSON);
  $client->setScopes([Drive::DRIVE_READONLY]);

  $drive = new Drive($client);

  // 1) Comprobar que la SA ve la carpeta (nombre/permisos básicos)
  $folder = $drive->files->get($FOLDER_ID, [
    'fields' => 'id,name,owners/displayName,permissions(emailAddress,role)',
    'supportsAllDrives' => true
  ]);

  // 2) Listar hijos directos del folder (sin filtrar por mimeType)
  $res = $drive->files->listFiles([
    'q' => "'$FOLDER_ID' in parents and trashed=false",
    'fields' => 'files(id,name,mimeType,size,modifiedTime)',
    'orderBy' => 'modifiedTime desc',
    'pageSize' => 100,
    'supportsAllDrives' => true,
    'includeItemsFromAllDrives' => true
  ]);

  $files = $res->getFiles() ?: [];
  echo json_encode([
    'ok' => true,
    'service_account' => $saMail,
    'folder' => [
      'id' => $folder->id,
      'name' => $folder->name,
      'owners' => $folder->owners,
      'perm_count' => is_array($folder->permissions) ? count($folder->permissions) : 0
    ],
    'incompleteSearch' => $res->getIncompleteSearch(),
    'count' => count($files),
    'files' => $files
  ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'msg'=>$e->getMessage()]);
}
