<?php

namespace App\Http\Controllers;

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

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

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

       
        $existingrecordings = DB::table('RECORDINGS')
                             ->where('UnitID', $data['unit_id'])
                             ->get(['RecordingContent']);

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


      
        $combinedContent = [];

  
     
       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/recordings_videos/');
        
   
        $file->move($destinationPath, $filename);

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

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


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

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

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