<?php

namespace App\Http\Controllers;

use App\Models\C1EssStatus;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class EssController extends Controller
{
    /**
     * Display a listing of the ESS Tracker with summary stats.
     */
    public function index()
    {
        $stats = C1EssStatus::select('ess_code', 'status', DB::raw('COUNT(*) as count'))
            ->groupBy('ess_code', 'status')
            ->get()
            ->groupBy('ess_code')
            ->map(fn($group) => $group->pluck('count', 'status')->toArray())
            ->toArray();

        // Paginate detailed entries (10 per page)
        $entries = C1EssStatus::latest()->paginate(10);

        // Overall stats
        $overallStats = C1EssStatus::select('status', DB::raw('COUNT(*) as count'))
            ->groupBy('status')
            ->pluck('count', 'status')
            ->toArray();

        // Per organization stats
        $orgStats = C1EssStatus::select('organization', 'status', DB::raw('COUNT(*) as count'))
            ->groupBy('organization', 'status')
            ->get()
            ->groupBy('organization')
            ->map(fn($group) => $group->pluck('count', 'status')->toArray())
            ->toArray();

        // Heatmap data preparation
        $activities = C1EssStatus::select('activity_key')
        ->distinct()
        ->orderBy('activity_key')
        ->pluck('activity_key')
        ->toArray();

        $orgSubs = C1EssStatus::select(DB::raw("CONCAT(organization, '_', sub_org) as org_sub"))
            ->distinct()
            ->orderBy('org_sub')
            ->pluck('org_sub')
            ->toArray();

        // Status value mapping for color intensity (higher = better)
        $statusValues = [
            'completed'    => 5,
            'ongoing'      => 3,
            'delayed'      => 1,
            'not_started'  => 0,
            'cancelled'    => -1,
        ];

        $heatmapData = [];
        $heatmapBackgrounds = [];

        foreach ($activities as $act) {
            $rowData = [];
            $rowColors = [];
            foreach ($orgSubs as $orgSub) {
                $record = C1EssStatus::where('activity_key', $act)
                    ->whereRaw("CONCAT(organization, '_', sub_org) = ?", [$orgSub])
                    ->first();

                $status = $record ? $record->status : 'not_started';
                $value = $statusValues[$status] ?? 0;

                $rowData[] = $value;
                // Color scale: green → yellow → red
                $rowColors[] = match ($status) {
                    'completed'    => 'rgba(40, 167, 69, 0.8)',
                    'ongoing'      => 'rgba(13, 110, 253, 0.7)',
                    'delayed'      => 'rgba(255, 193, 7, 0.8)',
                    'not_started'  => 'rgba(108, 117, 125, 0.6)',
                    'cancelled'    => 'rgba(220, 53, 69, 0.8)',
                    default        => 'rgba(200, 200, 200, 0.5)',
                };
            }
            $heatmapData[] = $rowData;
            $heatmapBackgrounds[] = $rowColors;
        }

        return view('ess.index', compact(
            'stats', 'entries', 'overallStats', 'orgStats',
            'activities', 'orgSubs', 'heatmapData', 'heatmapBackgrounds'
        ));

        // return view('ess.index', compact('stats', 'entries', 'overallStats', 'orgStats'));
    }

    /**
     * Show the form for creating a new ESS entry.
     */
    public function create()
    {
        return view('ess.create');
    }

    /**
     * Store a newly created ESS entry in storage.
     */
    public function store(Request $request)
    {
        // Basic validation (you can make it more strict if needed)
        $validator = Validator::make($request->all(), [
            'status' => 'required|array',
            'status.*.*.*' => 'required|in:completed,ongoing,delayed,not_started,cancelled',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $statusData = $request->input('status', []);

        DB::transaction(function () use ($statusData) {
            foreach ($statusData as $essCode => $activities) {
                foreach ($activities as $activityKey => $orgs) {
                    foreach ($orgs as $orgSubKey => $status) {
                        // Parse org_sub into organization & sub_org
                        [$organization, $sub_org] = explode('_', $orgSubKey, 2);

                        // Update or create record
                        C1EssStatus::updateOrCreate(
                            [
                                'ess_code'     => $essCode,
                                'activity_key' => $activityKey,
                                'organization' => $organization,
                                'sub_org'      => $sub_org,
                            ],
                            [
                                'status' => $status,
                            ]
                        );
                    }
                }
            }
        });

        return redirect()->route('ess.index')
            ->with('success', 'ESS Tracker entry saved successfully!');
    }

    /**
     * Show the form for editing an existing ESS entry.
     * (This is optional — you can edit everything at once via create-like form)
     */
    public function edit()
    {
        // For simplicity, we reuse the create form but prefill current values
        $currentStatuses = C1EssStatus::all()->keyBy(function ($item) {
            return "{$item->ess_code}.{$item->activity_key}.{$item->organization}_{$item->sub_org}";
        });

        return view('ess.create', compact('currentStatuses'));
    }

    /**
     * Update the entire ESS tracker (same logic as store, but can be called from edit).
     */
    public function update(Request $request)
    {
        return $this->store($request); // Reuse store logic
    }

    /**
     * Remove a specific ESS record (optional).
     */
    public function destroy($id)
    {
        $record = C1EssStatus::findOrFail($id);
        $record->delete();

        return redirect()->route('ess.index')
            ->with('success', 'ESS record deleted successfully.');
    }

    /**
     * Optional helper method: Reset all ESS statuses to "Not Started"
     */
    public function reset()
    {
        C1EssStatus::query()->update(['status' => 'not_started']);

        return redirect()->route('ess.index')
            ->with('success', 'All ESS statuses have been reset to Not Started.');
    }
}