<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use App\Traits\ApiResponseTrait;

class CommonController extends Controller
{
    use ApiResponseTrait;

    public function updateRecord(Request $request)
    {
        $request->validate([
            'table_name'  => 'required|string',
            'column_name' => 'required|string',
            'value'       => 'required',
            'where_column' => 'required|string',
            'where_value'  => 'required'
        ]);

        $table = $request->table_name;
        $column = $request->column_name;
        $value = $request->value;
        $whereColumn = $request->where_column;
        $whereValue = $request->where_value;

        // Check table exists
        if (!Schema::hasTable($table)) {
            return $this->errorResponse('Invalid table name', null, 404);
        }

        // Check column exists
        if (!Schema::hasColumn($table, $column)) {
            return $this->errorResponse('Invalid column name', null, 404);
        }

        if (!Schema::hasColumn($table, $whereColumn)) {
            return $this->errorResponse('Invalid where column', null, 404);
        }

        // Update
        $updated = DB::table($table)
            ->where($whereColumn, $whereValue)
            ->update([$column => $value]);


        return $this->successResponse('Records updated successfully');
    }
}
