<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\SyncTable;
use App\Models\Table;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class SyncTableController extends Controller
{
    public function onlineSync(Request $request){
        $models = $request->models;
        $modelIds = $request->modelIds;
        $modelClassName = $request->modelName;
        $modelName = app()->getNamespace() . 'Models\\'.$modelClassName;
        $modelIds = array_map('intval', $modelIds);
        try {
            if(isset($models) && count($models) > 0){
                foreach ($models as $model) {
                    $updateData = [];
                    foreach ($model as $key => $value) {
                        $updateData[$key] = $value;
                    }
                    $existingModel = $modelName::find($model['id']);
                    // $datas = DB::table($request->tableName)->get();
                    // return response()->json(['message' => $datas, "id"=>$model["id"], "model"=>$modelIds], 200);
                    if ($existingModel) {
                         DB::table($request->tableName)->where('id', $updateData['id'])->update($updateData);
                        // $existingModel->update($updateData);
                    } else {
                        // return response()->json(['message' => $models], 200);
                        // $modelName::create($updateData);
                        DB::table($request->tableName)->insert($updateData);
                    }
                }
            }

            if(count($modelIds) > 0){
                $modelName::whereNotIn('id', $modelIds)->delete();
            }
            
            return response()->json(['message' => 'Data synchronized successfully'], 200);
        } catch (\Exception $e) {
            return response()->json(['message' => $e->getMessage()], 500);
        }
    }
}
