<?php

namespace EasyLinkAutomations\HTTP\Controllers\Actions;

if (!defined('ABSPATH')) {
    exit;
}

use EasyLinkAutomations\HTTP\Request\Request;
use EasyLinkAutomations\HTTP\Response;
use EasyLinkAutomations\Actions\GoogleSheets\GoogleSheetsHelper;
use EasyLinkAutomations\Models\Connection;

/**
 * Controller for Google Sheets related API calls.
 * Handles fetching spreadsheets, sheets, etc. for dynamic field loading.
 */
final class GoogleSheetsController
{
    private const DRIVE_API_BASE = 'https://www.googleapis.com/drive/v3';
    private const SHEETS_API_BASE = 'https://sheets.googleapis.com/v4/spreadsheets';

    /**
     * Get list of spreadsheets accessible by the connection.
     */
    public function spreadsheets(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        // Use Google Drive API to list spreadsheets
        $url = self::DRIVE_API_BASE . '/files?' . http_build_query([
            'q'                          => "mimeType='application/vnd.google-apps.spreadsheet' and trashed=false",
            'fields'                     => 'nextPageToken,files(id,name,modifiedTime,createdTime)',
            'orderBy'                    => 'modifiedTime desc',
            'pageSize'                   => 100,
            'includeItemsFromAllDrives'  => 'true',
            'supportsAllDrives'          => 'true',
        ]);

        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ],
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch spreadsheets: ' . $response->get_error_message());
        }

        $statusCode = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($statusCode !== 200) {
            $errorMsg = $body['error']['message'] ?? 'Unknown error';
            $errorReason = $body['error']['reason'] ?? '';
            return Response::error('Google API error: ' . $errorMsg, $statusCode);
        }

        $spreadsheets = [];
        foreach ($body['files'] ?? [] as $file) {
            $spreadsheets[] = [
                'value' => $file['id'],
                'label' => $file['name'],
            ];
        }

        return Response::success(['spreadsheets' => $spreadsheets]);
    }

    /**
     * Get list of sheets (tabs) within a spreadsheet.
     */
    public function sheets(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        $spreadsheetId = $request->get('spreadsheet_id');

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        if (empty($spreadsheetId)) {
            return Response::error('Spreadsheet ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        // Fetch spreadsheet metadata to get sheet names
        $url = self::SHEETS_API_BASE . '/' . rawurlencode($spreadsheetId) . '?fields=sheets.properties';

        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ],
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch sheets: ' . $response->get_error_message());
        }

        $statusCode = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($statusCode !== 200) {
            $errorMsg = $body['error']['message'] ?? 'Unknown error';
            return Response::error('Google API error: ' . $errorMsg, $statusCode);
        }

        $sheets = [];
        foreach ($body['sheets'] ?? [] as $sheet) {
            $props = $sheet['properties'] ?? [];
            $sheets[] = [
                'value' => $props['title'] ?? '',
                'label' => $props['title'] ?? 'Sheet',
            ];
        }

        return Response::success(['sheets' => $sheets]);
    }

    /**
     * Get column headers from the first row of a sheet.
     */
    public function columns(Request $request): Response
    {
        $connectionId = (int) $request->get('connection_id');
        $spreadsheetId = $request->get('spreadsheet_id');
        $sheetName = $request->get('sheet_name') ?? 'Sheet1';
        $headerRow = (int) ($request->get('header_row') ?? 1);

        if (!$connectionId) {
            return Response::error('Connection ID is required', 400);
        }

        if (empty($spreadsheetId)) {
            return Response::error('Spreadsheet ID is required', 400);
        }

        $token = Connection::getAccessToken($connectionId);
        if (empty($token)) {
            return Response::error('Invalid connection or token expired', 401);
        }

        // Fetch the specified header row to get column headers
        $range = rawurlencode(GoogleSheetsHelper::quoteSheetName((string) $sheetName) . "!{$headerRow}:{$headerRow}");
        $url = self::SHEETS_API_BASE . '/' . rawurlencode($spreadsheetId) . '/values/' . $range;

        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ],
            'timeout' => 30,
        ]);

        if (is_wp_error($response)) {
            return Response::error('Failed to fetch columns: ' . $response->get_error_message());
        }

        $statusCode = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($statusCode !== 200) {
            $errorMsg = $body['error']['message'] ?? 'Unknown error';
            return Response::error('Google API error: ' . $errorMsg, $statusCode);
        }

        $columns = [];
        $values = $body['values'][0] ?? [];
        foreach ($values as $index => $header) {
            $columns[] = [
                'value' => $header,
                'label' => $header,
                'column_letter' => GoogleSheetsHelper::numberToColumn($index),
            ];
        }

        return Response::success(['columns' => $columns]);
    }
}
