<?php

namespace ViartasThemes\FlorialLanding\Modules\MainPage;

use Illuminate\Support\Facades\Http;
use Google\Client as GoogleClient;
use Google\Service\Sheets;
use Google\Service\Drive;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;
use ViartasThemes\FlorialLanding\Forms\ContactForm;
use ViartasThemes\FlorialLanding\Mails\ContactForm as ContactFormMail;

class MainPageController extends \ViartasCore\Core\Controllers\WebController
{
    public function contact(ContactForm $form)
    {
        $data = $form->toArray();

        $html = theme_view('web.main-page.contact-form', [
            'full_name' => $data['full_name'],
            'phone' => $data['phone'] ?? '',
            'email' => $data['email'],
            'messageText' => $data['message'] ?? '',
        ])->render();

        Mail::to(env('MAIL_TO_ADDRESS'))
            ->queue(new ContactFormMail(
                full_name: $data['full_name'],
                phone: $data['phone'] ?? '',
                email: $data['email'],
                messageText: $data['message'] ?? '',
                messageHtml: $html,
            ));

        if ($form->expectsJson()) {
            return session()->flash('success', __('Jūsų užklausa sėkmingai gauta. Artimiausiu metu su Jumis susisieksime.'));
        }

        return theme_redirect()->route('web.main_page.index')->with('success', __('Jūsų užklausa sėkmingai gauta. Artimiausiu metu su Jumis susisieksime.'));
    }

    public function contacts()
    {
        return theme_view('web.main-page.contacts', []);
    }

    public function privacy()
    {
        return theme_view('web.main-page.privacy', []);
    }

    public function taisykles()
    {
        return theme_view('web.main-page.taiyskles', []);
    }

    public function index(ContactForm $form)
    {
        $flowers = Http::timeout(10)->get('https://www.topgeles.lt/cart?action=export')->json();

        $products = [];
        foreach ($flowers['products'] as $product) {
            if ($product['is_visible'] == 1) {
                $products[] = $product;
            }
        }

        $puokstes = cache()->remember('drive-file-puokstes', 10, function () {
            return $this->readPuokstesWithHyperlinks(
                'https://docs.google.com/spreadsheets/d/12CFJ3iBLKqVu2oPKsa8I9kRucDBvpjlhx0jVfldqAro/edit'
            );
        });

        foreach ($puokstes as $key => $puoksta) {
            $puokstes[$key]['image'] = $this->extractDriveFileId($puoksta['image']);
            if ($puokstes[$key]['is_enabled'] == 0) {
                unset($puokstes[$key]);
            }
        }

        $geles = cache()->remember('drive-file-geles', 100, function () {
            return $this->readPuokstesWithHyperlinks(
                'https://docs.google.com/spreadsheets/d/12CFJ3iBLKqVu2oPKsa8I9kRucDBvpjlhx0jVfldqAro/edit',
                'Geles'
            );
        });

        foreach ($geles as $key => $puoksta) {
            $geles[$key]['image'] = $this->extractDriveFileId($puoksta['image']);
            if ($geles[$key]['is_enabled'] == 0) {
                unset($geles[$key]);
            }
        }

        $form = $form->build();

        return theme_view('web.main-page.index', compact('products', 'puokstes', 'geles', 'form'));
    }

    public function fb() {
        $geles = cache()->remember('drive-file-geles', 100, function () {
            return $this->readPuokstesWithHyperlinks(
                'https://docs.google.com/spreadsheets/d/12CFJ3iBLKqVu2oPKsa8I9kRucDBvpjlhx0jVfldqAro/edit',
                'Geles'
            );
        });

        foreach ($geles as $key => $puoksta) {
            $geles[$key]['image'] = $this->extractDriveFileId($puoksta['image']);
            if ($geles[$key]['is_enabled'] == 0) {
                unset($geles[$key]);
            }
        }

        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="products.csv"');
        header("Content-type: text/html; charset=utf-8");

        echo "id\ttitle\tdescription\tlink\timage_link\tavailability\tprice\tcurrency\tcondition"."\n";

        foreach ($geles as $gele) {
            echo implode("\t", [
                Str::slug($gele['title']),
                $gele['title'],
                $gele['title'],
                'https://www.florial.lt',
                app_route('web.florial.images', ['id' => $gele['image']]),
                'in stock',
                str_replace(',','.', $gele['price']),
                'EUR',
                'new',
            ])."\n";
        }

        exit();
    }

    function fetchPuokstesCsv(string $spreadsheetId): array
    {
        $url = "https://docs.google.com/spreadsheets/d/{$spreadsheetId}/gviz/tq?tqx=out:csv&sheet=Puokstes";
        $csv = Http::get($url)->throw()->body();

        $lines = array_map('str_getcsv', preg_split("/\r\n|\n|\r/", trim($csv)));
        $header = array_map('strtolower', array_shift($lines)); // title, price, image

        $out = [];
        foreach ($lines as $row) {
            $item = array_combine($header, array_pad($row, count($header), null));
            if (!$item || empty($item['title'])) continue;

            // jei image yra =IMAGE("..."), ištraukiam URL
            if (!empty($item['image']) && preg_match('/=IMAGE\("([^"]+)"/i', $item['image'], $m)) {
                $item['image'] = $m[1];
            }

            $out[] = $item;
        }
        return $out;
    }

    function readPuokstes(string $spreadsheetUrlOrId): array
    {
        // 1. Klientas
        $client = new GoogleClient();
        $client->setApplicationName('Laravel Sheets Reader');
        $client->setScopes([Sheets::SPREADSHEETS_READONLY]);
        $client->setAuthConfig(storage_path('app/private/'.env('KEY_GOOGLE')));

        $service = new Sheets($client);

        // 2. Spreadsheet ID
        if (preg_match('~/spreadsheets/d/([a-zA-Z0-9-_]+)~', $spreadsheetUrlOrId, $m)) {
            $spreadsheetId = $m[1];
        } else {
            $spreadsheetId = $spreadsheetUrlOrId;
        }

        // 3. Nuskaitymas
        $response = $service->spreadsheets_values->get(
            $spreadsheetId,
            'Puokstes!A2:D',
            ['valueRenderOption' => 'FORMULA'] // kad gautume =IMAGE(...)
        );

        $rows = $response->getValues() ?? [];
        $result = [];

        foreach ($rows as $row) {
            $title = $row[0] ?? null;
            $price = $row[1] ?? null;
            $imageCell = $row[2] ?? null;
            $is_enabled = $row[3] ?? null;

            // Jei =IMAGE("url") – ištraukiam URL
            $image = $imageCell;
            if (is_string($imageCell) &&
                preg_match('/=IMAGE\("([^"]+)"/i', $imageCell, $m)) {
                $image = $m[1];
            }

            if (!$title) continue;

            $result[] = [
                'title' => $title,
                'price' => $price,
                'image' => $image,
                'is_enabled' => $is_enabled,
            ];
        }

        return $result;
    }

    function extractSpreadsheetId(string $urlOrId): string
    {
        if (preg_match('~/spreadsheets/d/([a-zA-Z0-9-_]+)~', $urlOrId, $m)) {
            return $m[1];
        }
        return $urlOrId;
    }

    /**
     * Nuskaito "Puokstes" tabą ir grąžina title|price|image, kur image yra hyperlink URL iš C stulpelio.
     *
     * @param string $spreadsheetUrlOrId  Google Sheets URL arba ID
     * @param string $tabName            Sheet tab pavadinimas (pvz. "Puokstes")
     * @param int    $limitRows          kiek eilučių skaityti (nuo 2 eilutės)
     * @return array<int, array{title: string|null, price: string|null, image: string|null}>
     */
    function readPuokstesWithHyperlinks(
        string $spreadsheetUrlOrId,
        string $tabName = 'Puokstes',
        int $limitRows = 500
    ): array {
        // 1) Google klientas
        $client = new GoogleClient();
        $client->setApplicationName('Laravel Sheets Hyperlink Reader');
        $client->setScopes([Sheets::SPREADSHEETS_READONLY]);
        $client->setAuthConfig(storage_path('app/private/'.env('KEY_GOOGLE')));

        $service = new Sheets($client);

        // 2) Spreadsheet ID
        $spreadsheetId = $this->extractSpreadsheetId($spreadsheetUrlOrId);

        // 3) Range (A2:C + limit)
        // A2:C reiškia nuo 2 eilutės. Kad nedidelint payload, ribojam iki A{limit+1}:C{limit+1}
        $endRow = 1 + $limitRows; // nes startas yra 2 eilutė
        $rangeA1 = sprintf("%s!A2:D%d", $tabName, $endRow);

        // 4) Imame su includeGridData, kad gautume hyperlink metaduomenis
        // fields apribojam iki to, ko reikia
        $resp = $service->spreadsheets->get($spreadsheetId, [
            'ranges' => [$rangeA1],
            'includeGridData' => true,
            'fields' => 'sheets(data(rowData(values(formattedValue,hyperlink,textFormatRuns(format(link(uri)))))))',
        ]);

        $sheets = $resp->getSheets() ?? [];
        if (count($sheets) === 0) {
            return [];
        }

        $dataBlocks = $sheets[0]->getData() ?? [];
        if (count($dataBlocks) === 0) {
            return [];
        }

        $rowData = $dataBlocks[0]->getRowData() ?? [];

        $out = [];
        foreach ($rowData as $row) {
            $cells = $row->getValues() ?? [];

            $title = $cells[0]->getFormattedValue() ?? null;
            $price = $cells[1]->getFormattedValue() ?? null;
            $is_enabled = $cells[3]->getFormattedValue() ?? null;

            // C langelis (image)
            $imageText = $cells[2]->getFormattedValue() ?? null; // pvz. "5_xls.jpg"
            $imageLink = $cells[2]->getHyperlink() ?? null;      // tikras URL jei yra

            // Jei hyperlink ne tiesioginiame lauke, pabandom iš textFormatRuns (kai nuoroda ant dalies teksto)
            if (!$imageLink) {
                $runs = $cells[2]->getTextFormatRuns() ?? [];
                foreach ($runs as $run) {
                    $uri = $run->getFormat()?->getLink()?->getUri();
                    if ($uri) {
                        $imageLink = $uri;
                        break;
                    }
                }
            }

            // Praleidžiam tuščias eilutes
            if ($title === null || trim((string)$title) === '') {
                continue;
            }

            $out[] = [
                'title' => $title,
                'price' => $price,
                // jei nuorodos nėra, paliekam tai, kas matosi (pvz. failo vardą)
                'image' => $imageLink ?? $imageText,
                'is_enabled' => $is_enabled ?? 0,
            ];
        }

        return $out;
    }

    function extractDriveFileId(string $urlOrId): ?string
    {
        // /file/d/FILE_ID/
        if (preg_match('~/file/d/([a-zA-Z0-9_-]+)~', $urlOrId, $m)) return $m[1];

        // id=FILE_ID
        if (preg_match('~[?&]id=([a-zA-Z0-9_-]+)~', $urlOrId, $m)) return $m[1];

        // jei jau paduotas ID
        if (preg_match('~^[a-zA-Z0-9_-]{10,}$~', $urlOrId)) return $urlOrId;

        return null;
    }

    function downloadDriveFileBytes(string $fileId): string
    {
        return cache()->remember('drive-file-new-'.$fileId, 1500, function () use ($fileId) {
            $client = new GoogleClient();
            $client->setApplicationName('Laravel Drive Downloader');
            $client->setAuthConfig(storage_path('app/private/'.env('KEY_GOOGLE')));
            $client->setScopes([Drive::DRIVE_READONLY]);

            $drive = new Drive($client);

            $resp = $drive->files->get($fileId, ['alt' => 'media']); // alt=media → body yra failas
            return $resp->getBody()->getContents();
        });
    }

    function streamImageFromDrive(string $driveUrlOrId)
    {
        $fileId = $this->extractDriveFileId($driveUrlOrId);

        abort_if(!$fileId, 400, 'Blogas Drive URL/ID');

        $bytes = $this->downloadDriveFileBytes($fileId);

        // jei nori tiksliai MIME, gali dar paimti metadata su $drive->files->get($fileId, ['fields' => 'mimeType,name'])
        return Response::make($bytes, 200, [
            'Content-Type' => 'image/jpeg', // arba nustatyk dinamiškai
            'Cache-Control' => 'public, max-age=3600',
        ]);
    }
}
