<?php

namespace App\Http\Controllers;

use App\Constants\Status;
use App\Lib\CurlRequest;
use App\Models\CronJob;
use App\Models\CronJobLog;
use App\Models\GenerateWebsite;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Support\Facades\Http;

class CronController extends Controller {
    public function cron() {
        $general            = gs();
        $general->last_cron = now();
        $general->save();

        $crons = CronJob::with('schedule');

        if (request()->alias) {
            $crons->where('alias', request()->alias);
        } else {
            $crons->where('next_run', '<', now())->where('is_running', Status::YES);
        }
        $crons = $crons->get();
        foreach ($crons as $cron) {
            $cronLog              = new CronJobLog();
            $cronLog->cron_job_id = $cron->id;
            $cronLog->start_at    = now();
            if ($cron->is_default) {
                $controller = new $cron->action[0];
                try {
                    $method = $cron->action[1];
                    $controller->$method();
                } catch (\Exception $e) {
                    $cronLog->error = $e->getMessage();
                }
            } else {
                try {
                    CurlRequest::curlContent($cron->url);
                } catch (\Exception $e) {
                    $cronLog->error = $e->getMessage();
                }
            }
            $cron->last_run = now();
            $cron->next_run = now()->addSeconds((int) $cron->schedule->interval);
            $cron->save();

            $cronLog->end_at = $cron->last_run;

            $startTime         = Carbon::parse($cronLog->start_at);
            $endTime           = Carbon::parse($cronLog->end_at);
            $diffInSeconds     = $startTime->diffInSeconds($endTime);
            $cronLog->duration = $diffInSeconds;
            $cronLog->save();
        }
        if (request()->target == 'all') {
            $notify[] = ['success', 'Cron executed successfully'];
            return back()->withNotify($notify);
        }
        if (request()->alias) {
            $notify[] = ['success', keyToTitle(request()->alias) . ' executed successfully'];
            return back()->withNotify($notify);
        }
    }

    public function planExpired() {
        $users = User::where('expired_date', '<', now())->limit(50)->get();
        foreach ($users as $user) {
            $user->expired_date  = null;
            $user->plan_id       = 0;
            $user->website_limit = 0;
            $user->max_page      = 0;
            $user->max_sections  = 0;
            $user->save();
        }
    }

    public function generateWebsite() {
        $generateWebsite = GenerateWebsite::with('websiteType')->withWhereHas('websiteInformation', function ($q) {
            $q->where('status', Status::WEBSITE_PENDING);
        })->where('status', Status::WEBSITE_PENDING)->limit(3)->get();

        foreach ($generateWebsite as $website) {

            $websiteInfo = $website->websiteInformation()->where('status', Status::WEBSITE_PENDING)->first();
            if (!$websiteInfo) {
                continue;
            }

            if(gs('default_engine') == Status::GEMINI_MODEL) {
                $apiToken = gs('gemini_api_key');
                if (!$apiToken) {
                    return responseError('missing_api_token', 'API key is missing for the selected engine.');
                }

                $createPage = $this->geminiApi($website, $websiteInfo);

            }else{
                $apiToken = gs('openai_api_key');
                if (!$apiToken) {
                    return responseError('missing_api_token', 'API key is missing for the selected engine.');
                }

                $createPage = $this->openaiApi($website, $websiteInfo);
            }

            if (isset($createPage['status']) && $createPage['status'] == 'error') {
                continue;
            }

            $generatedText = $createPage['content'];
            $files         = $this->extractFilesFromResponse($generatedText);

            $basePath = getFilePath('websites') . '/' . $website->folder_name;
            foreach ($files as $fileName => $content) {
                file_put_contents($basePath . '/' . $fileName, $content);

                if ($website->total_page == $website->page_remain) {
                    $firstFile   = getImage($basePath . '/' . $fileName);
                    $pathToImage = $basePath . '/screenshot.png';

                    $apiUrl = 'https://api.apiflash.com/v1/urltoimage'
                    . '?access_key=' . gs('api_flash_access_key')
                    . '&wait_until=page_loaded'
                    . '&url=' . urlencode($firstFile);

                    $image = file_get_contents($apiUrl);

                    if (!file_exists(dirname($pathToImage))) {
                        mkdir(dirname($pathToImage), 0755, true);
                    }
                    file_put_contents($pathToImage, $image);
                }

            }

            $websiteInfo->response = $generatedText;
            $websiteInfo->status   = Status::WEBSITE_GENERATED;
            $websiteInfo->save();

            $website->page_remain -= 1;
            if ($website->page_remain <= 0) {
                $website->status              = Status::WEBSITE_GENERATED;
                $website->complete_percentage = 100;
                $website->save();

                notify($website->user, 'WEBSITE_GENERATED', [
                    'website_type' => $website->websiteType->name,
                    'link'         => route('user.website.preview', $website->folder_name),
                ]);

            } else {
                $website->complete_percentage = round((($website->total_page - $website->page_remain) / $website->total_page) * 100);
                $website->save();
            }
        }
    }

    private function extractFilesFromResponse($responseText) {
        $pattern = '/====START_FILE:\s*(.*?)====(.*?)====END_FILE====/s';
        preg_match_all($pattern, $responseText, $matches, PREG_SET_ORDER);

        $files = [];
        foreach ($matches as $match) {
            $fileName         = trim($match[1]);
            $content          = trim($match[2]);
            $files[$fileName] = $content;
        }
        return $files;
    }


    private function openaiApi($website, $websiteInfo) {

        try {
            $pageName     = $websiteInfo?->details?->name;
            $pageSlug     = $websiteInfo?->details?->filename;
            $sectionsList = implode(', ', $websiteInfo?->details?->sections);

            $instruction = <<<PROMPT
You are an expert web designer and front-end developer.
Generate a **modern, professional, mobile-first, FULLY RESPONSIVE website** based on the following user preferences.

**Website Type:** {$website?->websiteType?->name}
**Page Name:** {$pageName}
**File Name:** {$pageSlug}

**ONLY generate this ONE page**
**Allowed Sections ONLY:** {$sectionsList}

**Page Structure & Sections:**

**CRITICAL INSTRUCTIONS:**
- Generate ONLY the pages listed above
- Each page MUST contain ONLY the sections specified for that page
- Do NOT add any extra pages or sections that are not mentioned
- Each section should be fully designed and functional
- ALL CSS must be in <style> tags inside each HTML file
- ALL JavaScript must be in <script> tags inside each HTML file
- NO separate CSS or JS files

**CRITICAL: FULL RESPONSIVENESS REQUIREMENTS**
- **Mobile-First Approach**: Design for mobile screens first (320px+), then scale up
- **Breakpoints**:
  - Mobile: 320px - 767px (single column, stacked elements)
  - Tablet: 768px - 1023px (2-column layouts where appropriate)
  - Desktop: 1024px+ (full multi-column layouts)
- **Responsive Navigation**:
  - Mobile: Hamburger menu with slide-in/slide-out sidebar
  - Desktop: Horizontal navigation bar
- **Touch-Friendly**: Minimum 44px touch targets on mobile
- **Responsive Typography**: Use clamp() or responsive font sizes
- **Responsive Cards/Grids**:
  - 1 column on mobile
  - 2 columns on tablet
  - 3-4 columns on desktop

**Design & Styling:**
- Primary Color: {$website->color}
- Accent Color: #0ABAB5 (teal)
- Background: #FFFFFF
- Muted Gray: #F3F6F9
- Text Dark: #0F172A
- Font: "{$website->font_family}" (use Google Fonts)
- Use **TailwindCSS via CDN** with responsive utility classes (sm:, md:, lg:, xl:)
- Add custom CSS in <style> tag for animations, hover effects, and custom styles

**HTML Structure for Each Page:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Title - {$website?->websiteType?->name}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family={$website->font_family}:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* All custom CSS here */
        /* Responsive styles */
        /* Animations */
        /* Hover effects */
    </style>
</head>
<body>
    <!-- Header/Navigation -->
    <!-- Main Content with Sections -->
    <!-- Footer -->

    <script>
        // All JavaScript here
        // Mobile menu toggle
        // Smooth scrolling
        // Animations
        // Form validation
    </script>
</body>
</html>
```

**Animations & Interactivity (in <script> tag):**
- Mobile hamburger menu toggle with smooth animations
- Fade-in reveal for sections using IntersectionObserver
- Smooth scroll for navigation links
- Modal/lightbox functionality
- Form validation with error messages
- Card hover effects

**Output Format - VERY IMPORTANT:**
Generate each file using EXACTLY this format:

====START_FILE: filename.html====
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Head content -->
    <style>
        /* CSS here */
    </style>
</head>
<body>
    <!-- Body content -->
    <script>
        // JavaScript here
    </script>
</body>
</html>
====END_FILE====

**Do NOT use:**
- HTML comment markers like <!-- FILE: filename.html -->
- Markdown code blocks like \`\`\`html
- Any other format

**Use ONLY:**
- ====START_FILE: filename.html====
- [complete HTML content]
- ====END_FILE====


**REMEMBER:**
- Each HTML file must be complete and standalone
- All CSS inside <style> tags
- All JavaScript inside <script> tags
- NO separate asset files
- Use ====START_FILE: and ====END_FILE==== markers
- Generate ONLY selected pages with their sections
- Fully responsive design
- Professional, modern UI
PROMPT;

            $apiKey   = gs('openai_api_key');
            $model    = gs('openai_api_model') ?? 'gpt-4o-mini';


            $openaiResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type'  => 'application/json',
            ])->timeout(300)->post('https://api.openai.com/v1/chat/completions', [
                'model'       => $model,
                'messages' => [
                    [
                        'role' => 'system',
                        'content' => 'You are a strict HTML code generator. Follow instructions exactly.',
                    ],
                    [
                        'role' => 'user',
                        'content' => $instruction,
                    ],
                ],
                'max_tokens'  => 6000,
                'temperature' => 0.7,
            ]);

            if ($openaiResponse->failed()) {
                $data = json_decode($openaiResponse->body(), true);

                return [
                    'status'  => 'error',
                    'message' => 'Error from OpenAI: ' . $data['error']['message'],
                ];
            }

            $content       = $openaiResponse->json();
            $generatedText = $content['choices'][0]['message']['content'] ?? null;

            if (!$generatedText) {
                return ['status' => 'error', 'message' => 'No content generated.'];
            }

            return ['status' => 'success', 'content' => $generatedText];
        } catch (\Throwable $th) {
            return ['status' => 'error', 'message' => 'An error occurred during content generation: ' . $th->getMessage()];
        }
    }


    private function geminiApi($website, $websiteInfo) {

        try {
            $pageName     = $websiteInfo?->details?->name;
            $pageSlug     = $websiteInfo?->details?->filename;
            $sectionsList = implode(', ', $websiteInfo?->details?->sections);

            $instruction = <<<PROMPT
You are an expert web designer and front-end developer.
Generate a **modern, professional, mobile-first, FULLY RESPONSIVE website** based on the following user preferences.

**Website Type:** {$website?->websiteType?->name}
**Page Name:** {$pageName}
**File Name:** {$pageSlug}

**ONLY generate this ONE page**
**Allowed Sections ONLY:** {$sectionsList}

**Page Structure & Sections:**

**CRITICAL INSTRUCTIONS:**
- Generate ONLY the pages listed above
- Each page MUST contain ONLY the sections specified for that page
- Do NOT add any extra pages or sections that are not mentioned
- Each section should be fully designed and functional
- ALL CSS must be in <style> tags inside each HTML file
- ALL JavaScript must be in <script> tags inside each HTML file
- NO separate CSS or JS files

**CRITICAL: FULL RESPONSIVENESS REQUIREMENTS**
- **Mobile-First Approach**: Design for mobile screens first (320px+), then scale up
- **Breakpoints**:
  - Mobile: 320px - 767px (single column, stacked elements)
  - Tablet: 768px - 1023px (2-column layouts where appropriate)
  - Desktop: 1024px+ (full multi-column layouts)
- **Responsive Navigation**:
  - Mobile: Hamburger menu with slide-in/slide-out sidebar
  - Desktop: Horizontal navigation bar
- **Touch-Friendly**: Minimum 44px touch targets on mobile
- **Responsive Typography**: Use clamp() or responsive font sizes
- **Responsive Cards/Grids**:
  - 1 column on mobile
  - 2 columns on tablet
  - 3-4 columns on desktop

**Design & Styling:**
- Primary Color: {$website->color}
- Accent Color: #0ABAB5 (teal)
- Background: #FFFFFF
- Muted Gray: #F3F6F9
- Text Dark: #0F172A
- Font: "{$website->font_family}" (use Google Fonts)
- Use **TailwindCSS via CDN** with responsive utility classes (sm:, md:, lg:, xl:)
- Add custom CSS in <style> tag for animations, hover effects, and custom styles

**HTML Structure for Each Page:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Page Title - {$website?->websiteType?->name}</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family={$website->font_family}:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        /* All custom CSS here */
        /* Responsive styles */
        /* Animations */
        /* Hover effects */
    </style>
</head>
<body>
    <!-- Header/Navigation -->
    <!-- Main Content with Sections -->
    <!-- Footer -->

    <script>
        // All JavaScript here
        // Mobile menu toggle
        // Smooth scrolling
        // Animations
        // Form validation
    </script>
</body>
</html>
```

**Animations & Interactivity (in <script> tag):**
- Mobile hamburger menu toggle with smooth animations
- Fade-in reveal for sections using IntersectionObserver
- Smooth scroll for navigation links
- Modal/lightbox functionality
- Form validation with error messages
- Card hover effects

**Output Format - VERY IMPORTANT:**
Generate each file using EXACTLY this format:

====START_FILE: filename.html====
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Head content -->
    <style>
        /* CSS here */
    </style>
</head>
<body>
    <!-- Body content -->
    <script>
        // JavaScript here
    </script>
</body>
</html>
====END_FILE====

**Do NOT use:**
- HTML comment markers like <!-- FILE: filename.html -->
- Markdown code blocks like \`\`\`html
- Any other format

**Use ONLY:**
- ====START_FILE: filename.html====
- [complete HTML content]
- ====END_FILE====


**REMEMBER:**
- Each HTML file must be complete and standalone
- All CSS inside <style> tags
- All JavaScript inside <script> tags
- NO separate asset files
- Use ====START_FILE: and ====END_FILE==== markers
- Generate ONLY selected pages with their sections
- Fully responsive design
- Professional, modern UI
PROMPT;

            $apiKey         = gs('gemini_api_key');
            $geminiResponse = Http::withHeaders([
                'Content-Type'   => 'application/json',
                'x-goog-api-key' => $apiKey,
            ])->timeout(300)->post(
                'https://generativelanguage.googleapis.com/v1beta/models/gemini-3-pro-preview:generateContent',
                [
                    'contents'         => [
                        ['parts' => [['text' => $instruction]]],
                    ],
                    'generationConfig' => [
                        'temperature'     => 0.7,
                        'maxOutputTokens' => 80000,
                    ],
                ]
            );

            if (!$geminiResponse->successful()) {
                return ['status' => 'error', 'message' => 'Failed to generate website content.'];
            }

            $content       = $geminiResponse->json();
            $generatedText = $content['candidates'][0]['content']['parts'][0]['text'] ?? null;

            if (!$generatedText) {
                return ['status' => 'error', 'message' => 'No content generated.'];
            }

            return ['status' => 'success', 'content' => $generatedText];
        } catch (\Throwable $th) {
            return ['status' => 'error', 'message' => 'An error occurred during content generation: ' . $th->getMessage()];
        }
    }
}
