<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class PracticeHomeFormController extends Controller
{
    public function showPracticeHomeForm() {
        $units = DB::table('UNITS')->get();
        return view('PracticeHomeForm', ['units' => $units]); 
    }

    public function storePracticeHomeForm(Request $request) {
        $data = $request->all();

        $existingPractices = DB::table('PRACTICEHOME')
                                ->where('UnitID', $data['unit_id'])
                                ->get(['PracticeHomeContent']);

        $maxOrderNumber = 0;
        foreach ($existingPractices as $practice) {
            $contentItems = json_decode($practice->PracticeHomeContent, true);
            foreach ($contentItems as $item) {
                if (isset($item['ordernumber']) && $item['ordernumber'] > $maxOrderNumber) {
                    $maxOrderNumber = $item['ordernumber'];
                }
            }
        }

        $combinedContent = [];
        foreach ($data['exercise_titles'] as $index => $title) {
            $type = $data['exercise_types'][$index] ?? null;

            switch ($type) {
                case 'multiple-choice':
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'multiple-choice',
                        'question' => $data['mc_questions'][$index] ?? '',
                        'options' => $data['mc_options'][$index] ?? [],
                        'correct_answers' => $data['mc_correct'][$index] ?? [],
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
                case 'true-false':
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'true-false',
                        'question' => $data['tf_questions'][$index] ?? '',
                        'answer' => $data['tf_answers'][$index] ?? '',
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
                case 'fill-blank':
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'fill-blank',
                        'question' => $data['fb_questions'][$index] ?? '',
                        'answer' => $data['fb_answers'][$index] ?? '',
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
                case 'essay':
                    $essayContent = isset($data['essay_content'][$index]) ? $data['essay_content'][$index] : '';
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'essay',
                        'content' => $essayContent, 
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
                case 'submit-form':
                    $submitContent = isset($data['submit_content'][$index]) ? $data['submit_content'][$index] : '';
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'submit-form',
                        'content' => $submitContent, 
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
                case 'text-only':
                    $combinedContent[] = [
                        'title' => $title,
                        'type' => 'text-only',
                        'content' => $data['text_only_exercises'][$index] ?? '',
                        'ordernumber' => ++$maxOrderNumber,
                    ];
                    break;
            }
        }

        usort($combinedContent, function($a, $b) {
            return $a['ordernumber'] - $b['ordernumber'];
        });

        DB::table('PRACTICEHOME')->insert([
            'UnitID' => $data['unit_id'],
            'PracticeHomeContent' => json_encode($combinedContent)
        ]);

        return redirect()->back()->with('success', 'Practiceat Home saved successfully!');
    }
}
