<?php

namespace App\Http\Controllers;

use App\Models\DepartmentSetupSubmission;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class DepartmentSetupQuestionnaireController extends Controller
{
    public function create()
    {
        return view('workflow.department_setup_questionnaire');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'department_name' => ['required', 'string', 'max:255'],
            'department_heads' => ['nullable', 'string', 'max:255'],
            'primary_contact_email' => ['nullable', 'email', 'max:255'],
            'primary_contact_phone' => ['nullable', 'string', 'max:100'],
            'go_live_priority_notes' => ['nullable', 'string'],
            'completed_by' => ['nullable', 'string', 'max:255'],
            'completed_date' => ['nullable', 'date'],
            'additional_notes' => ['nullable', 'string'],
            'users_json' => ['nullable', 'string'],
            'folders_json' => ['nullable', 'string'],
            'permissions_matrix_json' => ['nullable', 'string'],
            'workflows_json' => ['nullable', 'string'],
        ]);

        $payload = [
            'users' => $this->decodeJson($validated['users_json'] ?? null),
            'folders' => $this->decodeJson($validated['folders_json'] ?? null),
            'permissions_matrix' => $this->decodeJson($validated['permissions_matrix_json'] ?? null),
            'workflows' => $this->decodeJson($validated['workflows_json'] ?? null),
        ];

        DepartmentSetupSubmission::create([
            'department_name' => $validated['department_name'],
            'department_heads' => $validated['department_heads'] ?? null,
            'primary_contact_email' => $validated['primary_contact_email'] ?? null,
            'primary_contact_phone' => $validated['primary_contact_phone'] ?? null,
            'go_live_priority_notes' => $validated['go_live_priority_notes'] ?? null,
            'completed_by' => $validated['completed_by'] ?? null,
            'completed_date' => $validated['completed_date'] ?? null,
            'additional_notes' => $validated['additional_notes'] ?? null,
            'submitted_by_user_id' => auth()->id(),
            'payload' => $payload,
        ]);

        return redirect()
            ->route('workflow.department-setup-questionnaire')
            ->with('message', 'Questionnaire saved successfully.');
    }

    public function index()
    {
        $submissions = DepartmentSetupSubmission::latest()->paginate(20);

        return view('workflow.department_setup_questionnaire_submissions', compact('submissions'));
    }

    public function exportCsv(): StreamedResponse
    {
        $filename = 'department-setup-submissions-' . now()->format('Ymd_His') . '.csv';

        $headers = [
            'Content-Type' => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        return response()->stream(function () {
            $handle = fopen('php://output', 'w');

            fputcsv($handle, [
                'ID',
                'Submitted At',
                'Department Name',
                'Department Heads',
                'Primary Contact Email',
                'Primary Contact Phone',
                'Users Count',
                'Folders Count',
                'Permission Rows Count',
                'Workflows Count',
                'Completed By',
                'Completed Date',
                'Go Live Notes',
                'Additional Notes',
            ]);

            DepartmentSetupSubmission::orderByDesc('id')->chunk(200, function ($rows) use ($handle) {
                foreach ($rows as $row) {
                    $payload = $row->payload ?? [];

                    fputcsv($handle, [
                        $row->id,
                        optional($row->created_at)->format('Y-m-d H:i:s'),
                        $row->department_name,
                        $row->department_heads,
                        $row->primary_contact_email,
                        $row->primary_contact_phone,
                        is_array($payload['users'] ?? null) ? count($payload['users']) : 0,
                        is_array($payload['folders'] ?? null) ? count($payload['folders']) : 0,
                        is_array($payload['permissions_matrix'] ?? null) ? count($payload['permissions_matrix']) : 0,
                        is_array($payload['workflows'] ?? null) ? count($payload['workflows']) : 0,
                        $row->completed_by,
                        optional($row->completed_date)->format('Y-m-d'),
                        $row->go_live_priority_notes,
                        $row->additional_notes,
                    ]);
                }
            });

            fclose($handle);
        }, 200, $headers);
    }

    private function decodeJson(?string $value): array
    {
        if (!$value) {
            return [];
        }

        $decoded = json_decode($value, true);

        return is_array($decoded) ? $decoded : [];
    }
}
