<?php
defined('BASEPATH') or exit('No direct script access allowed');

class GoogleDrive extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('GoogleServiceJWT');
        $this->load->library('GoogleDriveDocs'); // -> $this->googledrivedocs
    }

    /** Compat historique: GET /index.php/GoogleDrive/list_folders?parent_id=... */
    public function list_folders()
    {
        $parent_id = $this->input->get('parent_id', true);
        if (!$parent_id) {
            return $this->output->set_status_header(400)
                ->set_content_type('application/json; charset=utf-8')
                ->set_output(json_encode(['error' => 'parent_id requis']));
        }

        try {
            $res = $this->googledrivedocs->listChildrenFolders($parent_id);
            $folders = [];
            foreach (($res['files'] ?? []) as $f) {
                if (!empty($f['id']) && !empty($f['name'])) {
                    $folders[] = ['id' => $f['id'], 'name' => $f['name']];
                }
            }
            usort($folders, fn($a,$b)=>strcasecmp($a['name'],$b['name']));

            return $this->output->set_content_type('application/json; charset=utf-8')
                ->set_output(json_encode(['folders' => $folders]));
        } catch (Throwable $e) {
            log_message('error', '[GoogleDrive/list_folders] '.$e->getMessage());
            return $this->output->set_status_header(500)
                ->set_content_type('application/json; charset=utf-8')
                ->set_output(json_encode(['error'=>true,'message'=>$e->getMessage()]));
        }
    }

    /**
     * GET /index.php/GoogleDrive/folders
     *  - mode=children&parent_id=...   -> {folders:[{id,name},...]}
     *  - mode=ancestors&base_id=...&folder_id=... -> {chain:[{id,name},...]}
     */
    public function folders()
    {
        $mode = $this->input->get('mode', true) ?: 'children';

        if ($mode === 'children') {
            return $this->list_folders(); // réutilise la logique ci-dessus
        }

        if ($mode === 'ancestors') {
            $folder_id = $this->input->get('folder_id', true);
            $base_id   = $this->input->get('base_id', true);
            if (!$folder_id || !$base_id) {
                return $this->output->set_status_header(400)
                    ->set_content_type('application/json; charset=utf-8')
                    ->set_output(json_encode(['error' => 'folder_id et base_id requis']));
            }

            if (!method_exists($this->googledrivedocs, 'getFileMeta')) {
                return $this->output->set_status_header(501)
                    ->set_content_type('application/json; charset=utf-8')
                    ->set_output(json_encode(['error'=>true,'message'=>'getFileMeta() manquant dans GoogleDriveDocs']));
            }

            try {
                $chain = [];
                $cur   = $folder_id;
                $guard = 0;
                while ($cur && $guard < 100) {
                    $meta = $this->googledrivedocs->getFileMeta($cur);
                    if (!$meta) break;
                    $chain[] = ['id'=>$meta['id'], 'name'=>$meta['name'] ?? $meta['id']];
                    if ($cur === $base_id) break;
                    $parents = $meta['parents'] ?? [];
                    $cur = $parents[0] ?? null;
                    $guard++;
                }
                $hasBase = false;
                foreach ($chain as $n) { if ($n['id'] === $base_id) { $hasBase = true; break; } }
                if (!$hasBase) {
                    return $this->output->set_content_type('application/json; charset=utf-8')
                        ->set_output(json_encode(['chain' => []]));
                }
                $chain = array_reverse($chain);
                return $this->output->set_content_type('application/json; charset=utf-8')
                    ->set_output(json_encode(['chain'=>$chain]));
            } catch (Throwable $e) {
                log_message('error', '[GoogleDrive/folders ancestors] '.$e->getMessage());
                return $this->output->set_status_header(500)
                    ->set_content_type('application/json; charset=utf-8')
                    ->set_output(json_encode(['error'=>true,'message'=>$e->getMessage()]));
            }
        }

        return $this->output->set_status_header(400)
            ->set_content_type('application/json; charset=utf-8')
            ->set_output(json_encode(['error' => 'mode invalide']));
    }
}
