<?php

namespace Webien\AI\Dashboard;

use Google;

class GoogleDrive
{
    private $files = [];
    private $filesTotal = 0;
    private $filesCompleted = 0;
    private $statusFile = __DIR__ . "/uploadStatus.txt";

    //private $nodeApi = 'https://chat.webien.io/api';

    function __construct()
    {

    }


    function download()
    {

        $settings = get_field('webien_ai_google_drive', 'options');

        if(
            empty($settings['webien_ai_google_drive_folder_id']) ||
            empty($settings['webien_ai_google_drive_service_account'])
        ){
            return [
                'status' => 'error',
                'message' => 'Google Drive settings not set'
            ];
        }

        $credentialsFile = get_attached_file((int)$settings['webien_ai_google_drive_service_account']);
        $folderId = $settings['webien_ai_google_drive_folder_id'];

        putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $credentialsFile);

        $client = new Google\Client();
        $client->useApplicationDefaultCredentials();
        $client->setScopes([
            Google\Service\Drive::DRIVE_READONLY,
            Google\Service\Drive::DRIVE_METADATA_READONLY,
        ]);


        // Create the Drive service
        $driveService = new Google\Service\Drive($client);


        // Replace with your actual folder ID

        //$fileList = $this->downloadFolderContents($driveService, $folderId, true);
        $this->downloadFolderContents($driveService, $folderId);

        return $this->files;
    }



    function downloadFolderContents($driveService, $folderId, $dryRun = false) {


        // Get thw webien-ai folder in uploads
        $uploadsDir = wp_upload_dir();
        $localPath = $uploadsDir['basedir'] . '/webien/webien-ai/downloads';
        $uploadsUrlBase = $uploadsDir['baseurl'] . '/webien/webien-ai/downloads/';


        if (!is_dir($localPath)) {
            mkdir($localPath, 0777, true);
        }

        $pageToken = null;

        do {
            $supportedMimeTypes = [
                'application/vnd.google-apps.document',
                'application/vnd.google-apps.spreadsheet',
                'application/vnd.google-apps.presentation',
                'application/pdf',
                'text/plain',
                'text/csv',
                'text/markdown',
                'application/json',
                'text/html',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/vnd.google-apps.folder'
            ];

            $mimeTypeFilters = array_map(function($mimeType) {
                return "mimeType = '$mimeType'";
            }, $supportedMimeTypes);

            $mimeTypeQuery = '(' . implode(' or ', $mimeTypeFilters) . ')';

            $params = [
                'q' => sprintf("'%s' in parents and trashed = false and %s", $folderId, $mimeTypeQuery),
                'fields' => 'nextPageToken, files(id, name, mimeType)',
                'supportsAllDrives' => true,
                'includeItemsFromAllDrives' => true,
                'pageToken' => $pageToken
            ];


            $results = $driveService->files->listFiles($params);

            $fileList = [];




            $this->filesTotal = count($results->getFiles());
            $this->filesCompleted = 0;

            $data = [
                'filesTotal' => $this->filesTotal,
                'filesDone' => $this->filesCompleted,
            ];
            file_put_contents($this->statusFile, json_encode($data));




            foreach ($results->getFiles() as $file) {
                $fileId = $file->getId();
                $fileName = $file->getName();
                $mimeType = $file->getMimeType();

                // Make filename filesystem-safe and prepend a random string
                $safeFileName = preg_replace('/[^\w\-\.]/', '_', $fileName);
                $randomPrefix = substr(bin2hex(random_bytes(3)), 0, 6); // 6-char hex
                $finalName = $randomPrefix . '_' . $safeFileName;

                if ($mimeType === 'application/vnd.google-apps.folder') {
                    // Recurse but save files flat
                    $this->downloadFolderContents($driveService, $fileId, $dryRun);
                } elseif (strpos($mimeType, 'application/vnd.google-apps.') === 0) {
                    // Export native Google files
                    switch ($mimeType) {
                        case 'application/vnd.google-apps.document':
                            $exportMimeType = 'application/pdf';
                            $extension = '.pdf';
                            break;
                        case 'application/vnd.google-apps.spreadsheet':
                            $exportMimeType = 'text/csv';
                            $extension = '.csv';
                            break;
                        case 'application/vnd.google-apps.presentation':
                            $exportMimeType = 'application/pdf';
                            $extension = '.pdf';
                            break;
                        default:
                            echo "Skipping unsupported Google file type: $fileName ($mimeType)\n";
                            continue 2;
                    }

                    try {
                        $response = $driveService->files->export($fileId, $exportMimeType, array(
                            'alt' => 'media'));
                        $content = $response->getBody()->getContents();

                        $response = $driveService->files->export($fileId, $exportMimeType);
                        file_put_contents($localPath . '/' . $finalName . $extension, $content);
                       // echo "Exported: $finalName$extension\n";
                        $this->files[] = $uploadsUrlBase . $finalName . $extension;

                        // Update status file
                        $this->filesCompleted++;

                    } catch (Exception $e) {
                        echo "Failed to export $fileName: " . $e->getMessage() . "\n";
                    }
                } else {
                    // Binary file — download directly
                    try {
                        $response = $driveService->files->get($fileId, ['alt' => 'media']);
                        file_put_contents($localPath . '/' . $finalName, $response->getBody()->getContents());
                       // echo "Downloaded: $finalName\n";
                        $this->files[] = $uploadsUrlBase . $finalName;

                        // Update status file
                        $this->filesCompleted++;

                    } catch (Exception $e) {
                        echo "Failed to download $fileName: " . $e->getMessage() . "\n";
                    }
                }

                $data = [
                    'filesTotal' => $this->filesTotal,
                    'filesDone' => $this->filesCompleted,
                ];
                file_put_contents($this->statusFile, json_encode($data));
            }

            $pageToken = $results->getNextPageToken();
        } while ($pageToken);


        // Clean status file when done
        file_put_contents($this->statusFile, '{}');

    }











}
?>