<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\DashboardProject;
use App\Models\Setting;
use App\Support\DefaultDashboardProjects;
use App\Support\ProjectTutorialVideo;
use Illuminate\Http\Request;

class DashboardProjectController extends Controller
{
    public function index()
    {
        DefaultDashboardProjects::ensureDefaults();

        $projects = DashboardProject::orderBy('sort_order')->orderBy('id', 'desc')->get();
        $inactiveGlobalAllow = (int) (Setting::query()
            ->where('key', $this->inactiveGlobalKey())
            ->orderByDesc('id')
            ->value('value') ?? 0) === 1;

        return view('admin.dashboard-projects.index', compact('projects', 'inactiveGlobalAllow'));
    }

    public function create()
    {
        $project = new DashboardProject([
            'is_active' => 1,
            'allowed_for_inactive' => 0,
            'off_popup_title' => 'Update in progress',
            'off_popup_message' => null,
            'inactive_popup_title' => 'Sorry',
            'inactive_popup_message' => null,
            'blocked_popup_title' => 'Access restricted',
            'blocked_popup_message' => null,
        ]);
        $project->off_popup_telegram_link = '';
        $project->tutorial_video_link = '';

        return view('admin.dashboard-projects.form', compact('project'));
    }

    public function store(Request $request)
    {
        $data = $this->rules($request);
        $telegramLink = trim((string) ($data['off_popup_telegram_link'] ?? ''));
        $tutorialVideoLink = trim((string) ($data['tutorial_video_link'] ?? ''));
        unset($data['off_popup_telegram_link']);
        unset($data['tutorial_video_link']);

        $project = DashboardProject::create($data);
        $this->saveOffTelegramLink((int) $project->id, $telegramLink);
        $this->saveTutorialVideoLink((int) $project->id, $tutorialVideoLink);

        return redirect()->route('admin.dashboard-projects.index')->with('success', 'Project created.');
    }

    public function edit(DashboardProject $dashboard_project)
    {
        $project = $dashboard_project;
        $project->off_popup_telegram_link = $this->getOffTelegramLink((int) $project->id);
        $project->tutorial_video_link = $this->getTutorialVideoLink((int) $project->id);
        return view('admin.dashboard-projects.form', compact('project'));
    }

    public function update(Request $request, DashboardProject $dashboard_project)
    {
        $data = $this->rules($request);
        $telegramLink = trim((string) ($data['off_popup_telegram_link'] ?? ''));
        $tutorialVideoLink = trim((string) ($data['tutorial_video_link'] ?? ''));
        unset($data['off_popup_telegram_link']);
        unset($data['tutorial_video_link']);

        $dashboard_project->update($data);
        $this->saveOffTelegramLink((int) $dashboard_project->id, $telegramLink);
        $this->saveTutorialVideoLink((int) $dashboard_project->id, $tutorialVideoLink);

        return redirect()->route('admin.dashboard-projects.index')->with('success', 'Project updated.');
    }

    public function destroy(DashboardProject $dashboard_project)
    {
        Setting::query()->where('key', $this->offTelegramKey((int) $dashboard_project->id))->delete();
        Setting::query()->where('key', $this->tutorialVideoKey((int) $dashboard_project->id))->delete();
        $dashboard_project->delete();
        return redirect()->route('admin.dashboard-projects.index')->with('success', 'Project deleted.');
    }

    public function toggle(DashboardProject $dashboard_project)
    {
        $dashboard_project->is_active = !$dashboard_project->is_active;
        $dashboard_project->save();

        return back()->with('success', 'Project status toggled.');
    }

    public function updateInactiveGlobal(Request $request)
    {
        $value = $request->boolean('inactive_global_allow') ? '1' : '0';
        $this->saveSettingValue($this->inactiveGlobalKey(), $value);

        return back()->with('success', 'Inactive user global access updated.');
    }

    private function rules(Request $request): array
    {
        $data = $request->validate([
            'title' => 'required|string|max:120',
            'icon' => 'required|string|max:120',
            'start_color' => 'required|string|max:20',
            'end_color' => 'required|string|max:20',
            'link' => 'required|string|max:255',

            'is_active' => 'nullable|boolean',
            'allowed_for_inactive' => 'nullable|boolean',

            'off_popup_title' => 'nullable|string|max:150',
            'off_popup_message' => 'nullable|string',
            'off_popup_telegram_link' => 'nullable|string|max:255',
            'tutorial_video_link' => 'nullable|string|max:2048',

            'inactive_popup_title' => 'nullable|string|max:150',
            'inactive_popup_message' => 'nullable|string',

            'blocked_referrals' => 'nullable|string',
            'blocked_popup_title' => 'nullable|string|max:150',
            'blocked_popup_message' => 'nullable|string',

            'sort_order' => 'nullable|integer|min:0|max:9999',
        ]);

        $data['is_active'] = (int) $request->boolean('is_active');
        $data['allowed_for_inactive'] = (int) $request->boolean('allowed_for_inactive');
        $data['sort_order'] = $data['sort_order'] ?? 0;

        return $data;
    }

    private function offTelegramKey(int $projectId): string
    {
        return 'dashboard_project_off_tg_link_' . $projectId;
    }

    private function tutorialVideoKey(int $projectId): string
    {
        return 'dashboard_project_tutorial_link_' . $projectId;
    }

    private function inactiveGlobalKey(): string
    {
        return 'inactive_global_allow';
    }

    private function saveOffTelegramLink(int $projectId, string $telegramLink): void
    {
        $key = $this->offTelegramKey($projectId);
        $telegramLink = $this->normalizeExternalLink($telegramLink);

        if ($telegramLink === '') {
            Setting::query()->where('key', $key)->delete();
            return;
        }

        // If duplicate keys already exist in settings table, keep all rows in sync
        // so user panel never falls back to an old value.
        $updated = Setting::query()
            ->where('key', $key)
            ->update(['value' => $telegramLink]);

        if ($updated === 0) {
            Setting::query()->create([
                'key' => $key,
                'value' => $telegramLink,
            ]);
        }
    }

    private function saveTutorialVideoLink(int $projectId, string $videoLink): void
    {
        $key = $this->tutorialVideoKey($projectId);
        $videoLink = ProjectTutorialVideo::normalizeLink($videoLink);

        if ($videoLink === '') {
            Setting::query()->where('key', $key)->delete();
            return;
        }

        $updated = Setting::query()
            ->where('key', $key)
            ->update(['value' => $videoLink]);

        if ($updated === 0) {
            Setting::query()->create([
                'key' => $key,
                'value' => $videoLink,
            ]);
        }
    }

    private function saveSettingValue(string $key, string $value): void
    {
        $updated = Setting::query()
            ->where('key', $key)
            ->update(['value' => $value]);

        if ($updated === 0) {
            Setting::query()->create([
                'key' => $key,
                'value' => $value,
            ]);
        }
    }

    private function getOffTelegramLink(int $projectId): string
    {
        return (string) (Setting::query()
            ->where('key', $this->offTelegramKey($projectId))
            ->orderByDesc('id')
            ->value('value') ?? '');
    }

    private function getTutorialVideoLink(int $projectId): string
    {
        return (string) (Setting::query()
            ->where('key', $this->tutorialVideoKey($projectId))
            ->orderByDesc('id')
            ->value('value') ?? '');
            
    }

    private function normalizeExternalLink(string $link): string
    {
        $link = trim($link);
        if ($link === '') {
            return '';
        }

        if (!preg_match('/^https?:\/\//i', $link)) {
            $link = 'https://' . ltrim($link, '/');
        }

        return $link;
    }
}
