<?php

namespace App\Http\Controllers;

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

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

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

       
        $existingLessons = DB::table('LESSONS')
                             ->where('UnitID', $data['unit_id'])
                             ->get(['LessonContent']);

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

        
        $titleBold = $data['title_bold'] ?? [];
        $titleItalic = $data['title_italic'] ?? [];
        $titleUnderline = $data['title_underline'] ?? [];
        $textBold = $data['text_bold'] ?? [];
        $textItalic = $data['text_italic'] ?? [];
        $textUnderline = $data['text_underline'] ?? [];

      
        $combinedContent = [];

       
        if (isset($data['titles'])) {
            foreach ($data['titles'] as $index => $title) {
                $combinedContent[] = [
                    'bold' => in_array($index, $titleBold),
                    'size' => $data['title_sizes'][$index] ?? '',
                    'type' => 'title',
                    'color' => $data['title_colors'][$index] ?? 'black',
                    'italic' => in_array($index, $titleItalic),
                    'content' => $title,
                    'underline' => in_array($index, $titleUnderline),
                    'ordernumber' => ++$maxOrderNumber,
                ];
            }
        }

       
        if (isset($data['texts'])) {
            foreach ($data['texts'] as $index => $text) {
                $combinedContent[] = [
                    'bold' => in_array($index, $textBold),
                    'size' => $data['text_sizes'][$index] ?? '',
                    'type' => 'text',
                    'color' => $data['text_colors'][$index] ?? 'black',
                    'italic' => in_array($index, $textItalic),
                    'content' => $text,
                    'underline' => in_array($index, $textUnderline),
                    'ordernumber' => ++$maxOrderNumber,
                ];
            }
        }

        
      if ($request->hasFile('images')) {
    foreach ($request->file('images') as $index => $file) {
        $timestamp = Carbon::now()->format('Ymd_His');
        $originalFilename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $filename = pathinfo($originalFilename, PATHINFO_FILENAME) . '_' . $timestamp . '.' . $extension;

        $destinationPath = public_path('uploads/lessons_photos/');
        $file->move($destinationPath, $filename);

        $filePath = 'uploads/lessons_photos/' . $filename;

        $combinedContent[] = [
            'type' => 'image',
            'content' => $filePath,
            'ordernumber' => ++$maxOrderNumber,
        ];
    }
}

if ($request->hasFile('videos')) {
    foreach ($request->file('videos') as $index => $file) {
        $timestamp = Carbon::now()->format('Ymd_His');
        $originalFilename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $filename = pathinfo($originalFilename, PATHINFO_FILENAME) . '_' . $timestamp . '.' . $extension;

        $destinationPath = public_path('uploads/lessons_videos/');
        $file->move($destinationPath, $filename);

        $filePath = 'uploads/lessons_videos/' . $filename;

        $combinedContent[] = [
            'type' => 'video',
            'content' => $filePath,
            'ordernumber' => ++$maxOrderNumber,
        ];
    }
}


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

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

        return redirect()->back()->with('success', 'Lesson created successfully!');
    }
}
