<?php

namespace App\Http\Controllers;

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


class SyncController extends Controller
{
    public function syncData(Request $request, $table)
    {
        try {
            // Validate JSON data
            $data = $request->json()->all();
            if (!$data || !is_array($data)) {
                return response()->json(['message' => 'Invalid JSON data'], 400);
            }

            foreach ($data as $row) {
                // Check if primary key exists
                $primaryKey = DB::getSchemaBuilder()->getColumnListing($table)[0]; // Assumes first column is the primary key

                // Insert or update using upsert
                DB::table($table)->updateOrInsert(
                    [$primaryKey => $row[$primaryKey]], // Search by primary key
                    $row // Update or insert
                );
            }

            return response()->json(['message' => "Data synchronized successfully for $table"], 200);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }
}
