<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class SettingsController extends Controller
{
    public function index()
    {
        $company = Company::all();
        $theme = $this->themeForUser(Auth::id());
        $themeTemplates = $this->themeTemplates();
        return view('settings.index')->with(['company' => $company, 'theme' => $theme, 'themeTemplates' => $themeTemplates]);
    }

    public function resources()
    {
        $resources = Document::where('is_deleted', '=', '0')->get();
        return view('resources.index', compact('resources'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:150'],
            'appname' => ['required', 'string', 'max:150'],
            'contactperson' => ['nullable', 'string', 'max:150'],
            'phone' => ['nullable', 'string', 'max:50', 'regex:/^[0-9+\-\s()]+$/'],
            'email' => ['nullable', 'email', 'max:150'],
            'address' => ['nullable', 'string', 'max:500'],
            'details' => ['nullable', 'string', 'max:5000'],
        ]);

        Company::updateOrCreate(['id' => 1], [
            'name' => $validated['name'],
            'appname' => $validated['appname'],
            'contactperson' => $validated['contactperson'] ?? null,
            'phone' => $validated['phone'] ?? null,
            'email' => $validated['email'] ?? null,
            'address' => $validated['address'] ?? null,
            'details' => $validated['details'] ?? null,
        ]);

        return redirect('/settings/')->with('message', 'Settings updated successfully.');
    }

    public function saveTheme(Request $request)
    {
        $validated = $request->validate([
            'theme_template' => ['nullable', 'string', 'max:60'],
            'primary' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'sidebar' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'topbar' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'background' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
            'surface' => ['nullable', 'regex:/^#[0-9A-Fa-f]{6}$/'],
        ]);

        $template = $validated['theme_template'] ?? null;
        $templates = $this->themeTemplates();
        $theme = $templates[$template] ?? [];
        $theme = array_merge($theme, array_filter(array_intersect_key($validated, array_flip(['primary','sidebar','topbar','background','surface'])), function ($value) {
            return $value !== null && $value !== '';
        }));
        $this->saveThemeForUser(Auth::id(), $theme);
        return back()->with('message', 'Theme preference saved successfully.');
    }

    public function resetTheme()
    {
        $themes = $this->allThemes();
        unset($themes[Auth::id()]);
        Storage::put('ngbvd_user_themes.json', json_encode($themes, JSON_PRETTY_PRINT));
        return back()->with('message', 'Theme preference reset to the default.');
    }

    private function allThemes(): array
    {
        if (!Storage::exists('ngbvd_user_themes.json')) {
            return [];
        }
        $themes = json_decode(Storage::get('ngbvd_user_themes.json'), true);
        return is_array($themes) ? $themes : [];
    }

    private function themeForUser($userId): array
    {
        $themes = $this->allThemes();
        return $themes[$userId] ?? $this->themeTemplates()['government_gold'];
    }

    private function saveThemeForUser($userId, array $theme): void
    {
        $themes = $this->allThemes();
        $themes[$userId] = $theme;
        Storage::put('ngbvd_user_themes.json', json_encode($themes, JSON_PRETTY_PRINT));
    }

    private function themeTemplates(): array
    {
        return [
            'government_gold' => ['name' => 'Government Gold', 'primary' => '#ffb000', 'sidebar' => '#07142b', 'topbar' => '#ffffff', 'background' => '#f3f6fb', 'surface' => '#ffffff'],
            'ministry_blue' => ['name' => 'Ministry Blue', 'primary' => '#1f5eff', 'sidebar' => '#0b1f45', 'topbar' => '#ffffff', 'background' => '#eef4ff', 'surface' => '#ffffff'],
            'uganda_flag' => ['name' => 'Uganda Flag', 'primary' => '#f5b301', 'sidebar' => '#111111', 'topbar' => '#f5b301', 'background' => '#f8f8f8', 'surface' => '#ffffff'],
            'referral_green' => ['name' => 'Referral Green', 'primary' => '#16a34a', 'sidebar' => '#052e1a', 'topbar' => '#ffffff', 'background' => '#f0fdf4', 'surface' => '#ffffff'],
            'high_contrast' => ['name' => 'High Contrast', 'primary' => '#111827', 'sidebar' => '#000000', 'topbar' => '#ffffff', 'background' => '#ffffff', 'surface' => '#ffffff'],
        ];
    }

    public function postresource(Request $request)
    {
        $request->validate([
            'id' => ['nullable', 'string', 'max:255'],
            'name' => ['required', 'string', 'max:180'],
            'category' => ['nullable', 'string', 'max:120'],
            'notes' => ['nullable', 'string', 'max:3000'],
            'attachment' => ['required_without:id', 'file', 'mimes:pdf,doc,docx,xls,xlsx,csv,png,jpg,jpeg,webp,txt', 'max:10240'],
        ]);

        $document = new Document();
        $userid = Auth::id();
        $now = date_create('now', timezone_open('Africa/Kampala'))->format('Y-m-d H:i:s');
        $postresource = $document->postdata($request, $now, $userid);
        return back()->with(isset($postresource['success_message']) ? 'success_message' : 'error_message', $postresource['success_message'] ?? $postresource['error_message']);
    }

    public function downloadFile(Request $request, $resourceID)
    {
        $resourceid = decrypt($resourceID);
        abort_unless(is_numeric($resourceid), 404);

        $resource = new Document();
        $filedetail = $resource->getFileByID((int) $resourceid);
        abort_if(empty($filedetail['content']), 404);

        $fileContent = base64_decode($filedetail['content']);
        $filename = Str::slug(pathinfo($filedetail['name'] ?? 'resource', PATHINFO_FILENAME)) ?: 'resource';
        $extension = pathinfo($filedetail['file_name'] ?? '', PATHINFO_EXTENSION);
        $downloadName = $filename . ($extension ? '.'.$extension : '');

        return response()->streamDownload(function () use ($fileContent) {
            echo $fileContent;
        }, $downloadName, ['Content-Type' => 'application/octet-stream']);
    }

    public function deleteEvidence(Request $request, $evidenceId)
    {
        $evidenceid = base64_decode(base64_decode($evidenceId));
        $informant = new Document();
        $userid = Auth::user()->id;
        $now = date_create('now', timezone_open('Africa/Kampala'))->format('Y-m-d H:i:s');
        $deleteentry = $informant->deleteentry($evidenceid, $now, $userid);
        return back()->with(isset($deleteentry['success_message']) ? 'success_message' : 'error_message', $deleteentry['success_message'] ?? $deleteentry['error_message']);
    }
}
