<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use App\Models\AshaUser;
use Tymon\JWTAuth\Facades\JWTAuth;

class AshaController extends Controller
{
    // GET: /asha
    public function login(Request $request)
    {
        $credentials = $request->only('email', 'password');
    
        try {
            // Set temporary DB connection
            Config::set('database.connections.pg_temp', [
                'driver' => 'pgsql',
                'host' => '127.0.0.1',
                'port' => '5432',
                'database' => 'asha_health_portal',
                'username' => 'postgres',
                'password' => 'bluAI-eamms317',
                'charset' => 'utf8',
                'prefix' => '',
                'schema' => 'public',
            ]);
    
            // Temporarily set connection
            app('config')->set('database.default', 'pg_temp');
    
            // Fetch user via Eloquent model
            $user = AshaUser::where('email', $credentials['email'])->first();
    
            if (!$user || !password_verify($credentials['password'], $user->password)) {
                return response()->json(['error' => 'Invalid credentials'], 401);
            }
    
            // Generate JWT token
            $token = JWTAuth::fromUser($user);
    
            return response()->json([
                'message' => 'Login successful',
                'token' => $token,
                'user' => [
                    'id' => $user->id,
                    'email' => $user->email,
                    'username' => $user->username,
                ]
            ]);
    
        } catch (Exception $e) {
            return response()->json([
                'error' => 'Could not create token',
                'details' => $e->getMessage()
            ], 500);
        }
    } 

    public function store(Request $request)
    {
        // ✅ Validate request
        $data = $request->validate([
            'fullName' => 'required|string|max:255',
            'email' => 'required|email',
            'password' => 'required|min:6',
        ]);
    
        try {
            // ✅ Manually set database connection config
            Config::set('database.connections.pg_temp', [
                'driver' => 'pgsql',
                'host' => '127.0.0.1',
                'port' => '5432',
                'database' => 'asha_health_portal',
                'username' => 'postgres',
                'password' => 'bluAI-eamms317',
                'charset' => 'utf8',
                'prefix' => '',
                'schema' => 'public',
            ]);
    
            // ✅ Insert into users table using the pg_temp connection
            DB::connection('pg_temp')->table('users')->insert([
                'username'   => $data['fullName'],
                'email'      => $data['email'],
                'password'   => bcrypt($data['password']),
                'role_id'    => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
    
            return response()->json([
                'message' => 'User registered successfully',
                'user'    => $data['fullName'],
            ]);
    
        } catch (Exception $e) {
            // Log the actual error for debugging
            Log::error('User Registration Error: ' . $e->getMessage());
    
            // Return safe error response
            return response()->json([
                'message' => 'Something went wrong while registering the user.',
                'error'   => $e->getMessage(), // optional: remove in production
            ], 500);
        }
    
}


public function getAllUsers()
{
    try {
        // ✅ Setup dynamic PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Fetch all users
        $users = DB::connection('pg_temp')->table('users')
            ->select('id', 'username', 'email', 'role_id', 'created_at')
            ->orderBy('username')
            ->get();

        return response()->json([
            'message' => 'Users fetched successfully ✅',
            'data'    => $users,
        ]);

    } catch (\Exception $e) {
        Log::error('Get Users Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch users.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function supervisorStore(Request $request)
{ 
    // ✅ Validate request
    $data = $request->validate([
        'user_id'         => 'required',
        'email'            => 'required|email',
        'first_name'       => 'required|string|max:100',
        'last_name'        => 'required|string|max:100',
        'contact_number'   => 'required|string|max:15',
        'health_center_id' => 'nullable|integer',
        'date_of_joining'  => 'nullable|date',
    ]);
 
    try {
        // ✅ Set temporary PostgreSQL DB config
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Start DB transaction
        DB::connection('pg_temp')->beginTransaction();
        // ✅ Insert into supervisors table
        DB::connection('pg_temp')->table('supervisors')->insert([
            'user_id'         => $data['user_id'], 
            'first_name'      => $data['first_name'],
            'last_name'       => $data['last_name'],
            'health_center_id'=> $data['health_center_id'],
            'contact_number'  => $data['contact_number'],
            'email'           => $data['email'],
            'date_of_joining' => $data['date_of_joining'],
            'created_at'      => now(),
            'updated_at'      => now(),
        ]);

        DB::connection('pg_temp')->commit();

        return response()->json([
            'message' => 'Supervisor registered successfully',
            'user'    => $data['user_id'],
        ]); 

    } catch (Exception $e) {
        DB::connection('pg_temp')->rollBack();
        Log::error('Supervisor Registration Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while registering the supervisor.',
            'error'   => $e->getMessage(), // remove in production if needed
        ], 500);
    }
} 


public function getAllSupervisors()
{
    try {
        // Set temporary PostgreSQL DB config
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Fetch all supervisors
        $supervisors = DB::connection('pg_temp')
            ->table('supervisors')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'message' => 'Supervisors fetched successfully',
            'data'    => $supervisors,
        ]);
    } catch (\Exception $e) {
        Log::error('Get Supervisors Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch supervisors.',
            'error'   => $e->getMessage(), // Optional: remove in prod
        ], 500);
    }
}


public function villageStore(Request $request)
{
    // ✅ Validate request to match actual DB columns
    $data = $request->validate([
        'name'       => 'required|string|max:255',
        'block_id'   => 'nullable|integer',
        'population' => 'nullable|integer|min:0',
        'latitude'   => 'nullable|numeric',
        'longitude'  => 'nullable|numeric',
        'code'       => 'nullable|string|max:255',
    ]);

    try {
        // ✅ Setup PostgreSQL connection dynamically
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Insert using correct field mappings
        DB::connection('pg_temp')->table('villages')->insert([
            'name'        => $data['name'],
            'block_id'    => $data['block_id'],
            'population'  => $data['population'],
            'latitude'    => $data['latitude'],
            'longitude'   => $data['longitude'],
            'code'        => $data['code'],
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        return response()->json([
            'message' => 'Village added successfully',
            'village' => $data['name'],
        ]);

    } catch (\Exception $e) {
        Log::error('Village Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while adding the village.',
            'error'   => $e->getMessage(), // Remove this in production
        ], 500);
    }
}

public function getAllVillage()
{
    try {
        // ✅ Dynamic PostgreSQL connection (same as in store)
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Fetch all villages
        $villages = DB::connection('pg_temp')->table('villages')->get();

        return response()->json([
            'message' => 'Village fetched successfully ✅',
            'data'    => $villages
        ]); 
    } catch (\Exception $e) {
        Log::error('Village Fetch Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch villages.',
            'error'   => $e->getMessage(), // Remove in production
        ], 500);
    }
}


public function stateStore(Request $request)
{
    // ✅ Validate incoming request data
    $data = $request->validate([
        'name' => 'required|string',
        'code' => 'nullable',
    ]);

    try { 
        // ✅ Setup dynamic PostgreSQL connection (same as villageStore)
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Insert into the "states" table
        DB::connection('pg_temp')->table('states')->insert([
            'name'       => $data['name'],
            'code'       => $data['code'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'State added successfully ✅',
            'state'   => $data['name'],
        ]);

    } catch (\Exception $e) {
        Log::error('State Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while adding the state.',
            'error'   => $e->getMessage(), // Optional: Remove in production
        ], 500);
    }
}

public function healthCenterTypeStore(Request $request)
{
   
 
    try {
        // ✅ Setup dynamic PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]); 

        // ✅ Insert into the "health_center_types" table
        DB::connection('pg_temp')->table('health_center_types')->insert([
            'name'        => $data['name'],
            'description' => $data['description'] ?? null,
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        return response()->json([
            'message' => 'Health Center Type added successfully ✅',
            'data'    => $data,
        ]);
        
    } catch (\Exception $e) {
        Log::error('Health Center Type Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while adding the health center type.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}

public function getAllHealthCenterType()
{
    try {
        // ✅ Setup dynamic PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Fetch all health center types
        $centerTypes = DB::connection('pg_temp')
            ->table('health_center_types')
            ->orderBy('name')
            ->get();

        return response()->json([ 
            'message' => 'health center types fetched successfully ✅',
            'data'    => $centerTypes
        ]);
    } catch (\Exception $e) {
        Log::error('Fetch Health Center Types Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch health center types.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}



public function healthCenterStore(Request $request)
{
    // ✅ Validate incoming data
    $data = $request->validate([
        'name'            => 'required|string|max:200',
        'center_type_id'  => 'required|integer',
        'address'         => 'nullable|string',
        'village_id'      => 'nullable|integer',
        'block_id'        => 'required|integer',
        'latitude'        => 'nullable|numeric',
        'longitude'       => 'nullable|numeric',
        'contact_number'  => 'nullable|string|max:15',
        'email'           => 'nullable|email|max:100',
    ]);

    try {
        // ✅ Dynamic DB connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);  

        // ✅ Insert
        DB::connection('pg_temp')->table('health_centers')->insert([
            ...$data,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'Health Center added successfully ✅',
            'data'    => $data,
        ]);

    } catch (\Exception $e) {
        Log::error('Health Center Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while adding the health center.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function getAllHealthCenters()
{
    try {
        // Set up the same dynamic PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Fetch all health centers
        $centers = DB::connection('pg_temp')
            ->table('health_centers')
            ->orderBy('name')
            ->get();

        return response()->json([
            'message' => 'Health centers fetched successfully ✅',
            'data'    => $centers,
        ]);
    } catch (\Exception $e) {
        Log::error('Fetch Health Centers Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch health centers.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function ashaWorkerStore(Request $request)
{
    // Validate incoming data

     // Check if the file exists
     if ($request->hasFile('profile_image')) {
        $file = $request->file('profile_image');
        // Handle the file as needed
        return response()->json(['file_name' => $file->getClientOriginalName()]);
    }

    return response()->json(['error' => 'No file uploaded'], 400);
    $data = $request->validate([
        'user_id'             => 'required',
        'first_name'          => 'required|string|max:100',
        'last_name'           => 'required|string|max:100',
        'date_of_birth'       => 'nullable|date',
        'asha_id'             => 'nullable',
        'contact_number'      => 'required|string|max:15',
        'alternative_contact' => 'nullable|string|max:15',
        'village_id'          => 'required|integer',
        'health_center_id'    => 'nullable|integer',
        'supervisor_id'       => 'nullable|integer',
        'date_of_joining'     => 'nullable|date',
        'education_level'     => 'nullable|string|max:50',
        'address'             => 'nullable|string',
        'profile_image'       => 'nullable|image|mimes:jpeg,png,jpg,gif', // Validate image type
    ]);

    try {
        // Handle profile image upload if file exists
        if ($request->hasFile('profile_image')) {
            $path = $request->file('profile_image')->store('asha_profiles', 'public');
            $data['profile_image'] = $path;  // Save the path in the database
        }

        // Insert data into the database
        $id = DB::connection('pg_temp')->table('asha_workers')->insertGetId([
            ...$data,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $data['id'] = $id;

        // Return success message with the image URL
        if (isset($data['profile_image'])) {
            $data['profile_image_url'] = asset('storage/' . $data['profile_image']);
        }

        return response()->json([
            'message' => 'ASHA Worker added successfully ✅',
            'data'    => $data,
        ]);
    } catch (\Exception $e) {
        Log::error('ASHA Worker Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while adding the ASHA worker.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}

 
public function getAllAshaWorkers()
{
    try {

        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $workers = DB::connection('pg_temp')->table('asha_workers')->get();

     
 
        return response()->json([
            'message' => 'ASHA Workers fetched successfully ✅',
            'data'    => $workers,
        ]);
    } catch (\Exception $e) {
        Log::error('ASHA Worker Fetch Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch ASHA workers.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}





public function getAllStates()
{
    try {
        // ✅ Setup dynamic PostgreSQL connection (same as stateStore)
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Fetch all states
        $states = DB::connection('pg_temp')->table('states')->get();

        return response()->json([
            'message' => 'States fetched successfully ✅',
            'data'    => $states,
        ]);

    } catch (\Exception $e) {
        Log::error('Fetch States Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while fetching states.',
            'error'   => $e->getMessage(),
        ], 500);
    }
}


// Laravel controller method to store block
public function blockStore(Request $request)
{
    $data = $request->validate([
        'name'        => 'required|string|max:100',
        'district_id' => 'required|integer',
        'code'        => 'nullable|string|max:10',
    ]);

    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);
        DB::connection('pg_temp')->table('blocks')->insert([
            'name'        => $data['name'],
            'district_id' => $data['district_id'],
            'code'        => $data['code'],
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        return response()->json(['message' => 'Block added successfully ✅']);

    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    }
}


public function storeHousehold(Request $request)
{
    // Validate the incoming request
    $data = $request->validate([
        'household_id'          => 'required|string|max:50',
        'village_id'            => 'required|integer',
        'asha_worker_id'        => 'required|integer',
        'head_of_household'     => 'nullable|string|max:100',
        'address'               => 'nullable|string',
        'socioeconomic_status'  => 'nullable|string|max:50',
        'total_members'         => 'required|integer|min:1',
        'has_toilet'            => 'boolean',
        'has_electricity'       => 'boolean', 
        'has_water_supply'      => 'boolean',
        'latitude'              => 'required',
        'longitude'             => 'required|',
    ]);

    try {

        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Insert into households table
        $id = DB::connection('pg_temp')->table('households')->insertGetId([
            ...$data,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'Household added successfully ✅',
            'data'    => array_merge($data, ['id' => $id]),
        ]);

    } catch (\Exception $e) {
        Log::error('Household Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to add household.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function getAllHouseholds()
{
    try {
        // Set up temporary PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Fetch all household records
        $households = DB::connection('pg_temp')
                        ->table('households')
                        ->orderBy('id', 'desc')
                        ->get();

        return response()->json([
            'message' => 'All households fetched successfully ✅',
            'data'    => $households
        ]);
        
    } catch (\Exception $e) {
        Log::error('Fetch Households Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch households.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}




public function storePatient(Request $request)
{
    $data = $request->validate([
        'household_id'           => 'required|integer',
        'first_name'             => 'required|string|max:100',
        'last_name'              => 'required|string|max:100',
        'date_of_birth'          => 'required|date',
        'gender'                 => 'required|string|max:10',
        'aadhaar_number'         => 'nullable|string|max:20',
        'contact_number'         => 'required|string|max:15',
        'blood_group'            => 'nullable|string|max:5',
        'marital_status'         => 'nullable|string|max:20',
        'occupation'             => 'nullable|string|max:100',
        'is_head_of_household'   => 'boolean',
        'relationship_to_head'   => 'nullable|string|max:50',
        'is_pregnant'            => 'boolean',
        'is_lactating'           => 'boolean',
        'has_disabilities'       => 'boolean',
        'disabilities_details'   => 'nullable|string|max:255',
    ]);

    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $id = DB::connection('pg_temp')->table('patients')->insertGetId([
            ...$data,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'Patient added successfully ✅',
            'id'      => $id
        ]);

    } catch (\Exception $e) {
        Log::error('Patient Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to add patient.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function programEnrollmentStore(Request $request)
{
    $validated = $request->validate([
        'patient_id'       => 'required',
        'program_id'       => 'required',
        'enrollment_date'  => 'required|date',
        'status'           => 'required|string|in:active,completed,inactive',
        'notes'            => 'nullable|string|max:500',
        'enrolled_by'      => 'required',
    ]);

    try {

        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Use the pg_temp connection for program_enrollments table
        $id = DB::connection('pg_temp')->table('program_enrollments')->insertGetId([
            'patient_id'      => $validated['patient_id'],
            'program_id'      => $validated['program_id'],
            'enrollment_date' => $validated['enrollment_date'],
            'status'          => $validated['status'],
            'notes'           => $validated['notes'] ?? null,
            'enrolled_by'     => $validated['enrolled_by'],
            'created_at'      => now(),
            'updated_at'      => now(),
        ]);

        return response()->json([
            'message' => 'Patient enrolled successfully ✅',
            'id' => $id,
        ]);
    } catch (\Exception $e) {
        Log::error('Program Enrollment Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to enroll patient',
            'error' => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function TaskCategoriesStore(Request $request)
{
    // Validate the incoming request data
    $validated = $request->validate([
        'name'        => 'required|string|max:255',
        'description' => 'nullable|string|max:500',
    ]);

    try {
        // Set the database connection dynamically
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Log the current database connection being used
        Log::info('Using database connection:', config('database.connections.pg_temp'));
        
        // Log the request data being inserted
        Log::info('Inserting Task Category data:', $validated);

        // Insert the task category into the database
        $id = DB::connection('pg_temp')->table('task_categories')->insertGetId([
            'name'        => $validated['name'],
            'description' => $validated['description'] ?? null,
            'created_at'  => now(),
            'updated_at'  => now(),
        ]);

        // Return a successful response
        return response()->json([
            'message' => 'Task Category added successfully ✅',
            'id' => $id,
        ]);

    } catch (\Exception $e) {
        // Log the error message
        Log::error('Task Category Store Error: ' . $e->getMessage());

        // Return an error response with details
        return response()->json([
            'message' => 'Failed to add Task Category',
            'error' => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}

public function getAllTaskCategories()
{
    try {
        // Set the database connection dynamically
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // Log the current database connection being used
        Log::info('Using database connection:', config('database.connections.pg_temp'));

        // Fetch all task categories from the database
        $taskCategories = DB::connection('pg_temp')->table('task_categories')->get();

        // Return the list of task categories
        return response()->json([
            'task_categories' => $taskCategories,
        ]);

    } catch (\Exception $e) {
        // Log the error message
        Log::error('Get All Task Categories Error: ' . $e->getMessage());

        // Return an error response with details
        return response()->json([
            'message' => 'Failed to fetch Task Categories',
            'error' => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function getAllPatients()
{
    try {
        // Dynamic PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $patients = DB::connection('pg_temp')->table('patients')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'message' => 'Patients fetched successfully ✅',
            'data'    => $patients
        ]);
    } catch (\Exception $e) {
        Log::error('Fetch Patients Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch patients.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}



public function storeHealthProgram(Request $request)
{
    $data = $request->validate([
        'name'         => 'required|string|max:255',
        'description'  => 'nullable|string',
        'start_date'   => 'required|date',
        'end_date'     => 'nullable|date|after_or_equal:start_date',
        'is_active'    => 'required|boolean',
    ]);
 
    try {
        // Dynamic database connection (same as in your patient method)
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $id = DB::connection('pg_temp')->table('health_programs')->insertGetId([
            ...$data,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json([
            'message' => 'Health Program added successfully ✅',
            'id'      => $id
        ]);

    } catch (\Exception $e) {
        Log::error('Health Program Insert Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to add Health Program.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function getAllHealthPrograms()
{
    try {
        // Use the same dynamic DB connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $programs = DB::connection('pg_temp')->table('health_programs')
            ->orderBy('created_at', 'desc')
            ->get();

        return response()->json([
            'message' => 'Health Programs fetched successfully ✅',
            'data'    => $programs
        ]);
    } catch (\Exception $e) {
        Log::error('Fetch Health Programs Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch Health Programs.',
            'error'   => app()->isLocal() ? $e->getMessage() : null,
        ], 500);
    }
}


public function getAllBlocks()
{
    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $blocks = DB::connection('pg_temp')->table('blocks')->get();

        return response()->json([
            'message' => 'Blocks fetched successfully ✅',
            'data'    => $blocks
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'message' => 'Failed to fetch blocks ❌',
            'error'   => $e->getMessage()
        ], 500);
    }
}




public function districtStore(Request $request)
{
    $data = $request->validate([
        'name'     => 'required|string|max:100',
        'state_id' => 'required|integer',
        'code'     => 'nullable|string|max:10',
    ]); 

    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);
        DB::connection('pg_temp')->table('districts')->insert([
            'name'       => $data['name'],
            'state_id'   => $data['state_id'],
            'code'       => $data['code'],
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return response()->json(['message' => 'District added successfully ✅']);

    } catch (\Exception $e) {
        return response()->json(['error' => $e->getMessage()], 500);
    }
}
 
public function getAllDistricts()
{
    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health_portal',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $districts = DB::connection('pg_temp')->table('districts')->get();

        return response()->json([
            'message' => 'Districts fetched successfully ✅',
            'data'    => $districts
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'message' => 'Failed to fetch districts ❌',
            'error'   => $e->getMessage()
        ], 500);
    }
}

 

 
public function storeHomeVisit(Request $request)
{
    // ✅ Validate incoming request
    $data = $request->validate([
        'beneficiary_id'    => 'required',
        'asha_id'           => 'required',
        'visit_datetime'    => 'required|date',
        'visit_purpose'     => 'required|string',
        'health_status'     => 'nullable|string',
        'actions_taken'     => 'nullable|string', // JSON string
        'follow_up_needed'  => 'required|boolean',
        'next_visit_date'   => 'nullable|date',
    ]);

    try {
        // ✅ Set temporary PostgreSQL DB config
      Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);
    DB::connection('pg_temp')->table('home_visit')->insert([
    'beneficiary_id'    => $data['beneficiary_id'],
    'asha_id'           => $data['asha_id'],
    'visit_datetime'    => $data['visit_datetime'],
    'visit_purpose'     => $data['visit_purpose'],
    'health_status'     => $data['health_status'],
    'actions_taken'     => json_encode($data['actions_taken']),
    'follow_up_needed'  => $data['follow_up_needed'],
    'next_visit_date'   => $data['next_visit_date'],
    'created_at'        => now(),
    'updated_at'        => now(),
]);  


        return response()->json([
            'message' => 'Home visit saved successfully',
            'beneficiary' => $data['beneficiary_id'],
        ]);

    } catch (\Exception $e) {
        DB::connection('pg_temp')->rollBack();
        Log::error('Home Visit Save Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while saving the home visit.',
            'error'   => $e->getMessage(), // remove or hide in production
        ], 500);
    } 
}
 


public function storeReferral(Request $request)
{

    $data = $request->validate([
        'beneficiary_id'      => 'required|integer',
        'asha_id'             => 'required|integer',
        'referral_datetime'   => 'required|date',
        'referred_to'         => 'required|string|max:100',
        'reason'              => 'required|string',
        'urgency_level'       => 'required', // Assuming enum values
        'transport_arranged'  => 'boolean',
        'completed'           => 'boolean',
        'outcome'             => 'nullable|string',
    ]);

    try {
        // ✅ Temporary PostgreSQL connection
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        // ✅ Insert data
        DB::connection('pg_temp')->table('referral')->insert([
            'beneficiary_id'     => $data['beneficiary_id'],
            'asha_id'            => $data['asha_id'],
            'referral_datetime'  => $data['referral_datetime'],
            'referred_to'        => $data['referred_to'],
            'reason'             => $data['reason'],
            'urgency_level'      => $data['urgency_level'],
            'transport_arranged' => $data['transport_arranged'] ?? false,
            'completed'          => $data['completed'] ?? false,
            'outcome'            => $data['outcome'],
            'created_at'         => now(),
            'updated_at'         => now(),
        ]);

        return response()->json([
            'message' => 'Referral saved successfully',
            'beneficiary_id' => $data['beneficiary_id'],
        ]);
    } catch (\Exception $e) {
        Log::error('Referral Save Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while saving the referral.',
            'error' => $e->getMessage(), // Hide this in production
        ], 500);
    }
   
}  


public function storeHomeVisit1(Request $request)  
{
    return "dedefefrfrfr";
}
public function getAllHomeVisits(Request $request)  
{
    try {
        // Set PostgreSQL DB config dynamically
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

     $perPage = $request->query('per_page', 10);
    $page = $request->query('page', 1);

    $offset = ($page - 1) * $perPage;

    $visits = DB::connection('pg_temp')
    ->table('home_visit as hv')
    ->join('beneficiary as b', 'hv.beneficiary_id', '=', 'b.beneficiary_id')
    ->join('village as v', 'b.village_id', '=', 'v.village_id') // 👈 Join village table
    ->join('asha_worker as a', 'hv.asha_id', '=', 'a.asha_id')
    ->select(
        'hv.*',
        'b.name as beneficiary_name',
        'b.date_of_birth as beneficiary_age',
        'b.category as beneficiary_category',
        'b.gender as beneficiary_gender',
        'a.name as asha_name',
        'v.village_name as village_name' // 👈 Add village name in select
    )
    ->orderBy('hv.visit_datetime', 'desc')
    ->offset($offset)
    ->limit($perPage)
    ->get();


    $total = DB::connection('pg_temp')->table('home_visit')->count();

    return response()->json([
        'message' => 'All home visits fetched successfully ✅',
        'data' => $visits,
        'meta' => [
            'total' => $total,
            'per_page' => (int)$perPage,
            'current_page' => (int)$page,
            'last_page' => ceil($total / $perPage)
        ]
    ]);

    } catch (\Exception $e) {
        Log::error('Get Home Visits Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Something went wrong while fetching home visits.',
            'error'   => $e->getMessage(),
        ], 500);
    }
}

     

public function getAllBeneficiaries()
{
    try {
        Config::set('database.connections.pg_temp', [
            'driver'   => 'pgsql',
            'host'     => '127.0.0.1',
            'port'     => '5432',
            'database' => 'asha_health',
            'username' => 'postgres',
            'password' => 'bluAI-eamms317',
            'charset'  => 'utf8',
            'prefix'   => '',
            'schema'   => 'public',
        ]);

        $beneficiaries = DB::connection('pg_temp')
            ->table('beneficiary as b')
            ->join('village as v', 'b.village_id', '=', 'v.village_id')
            ->select(
                'b.beneficiary_id',
                'b.name',
                'b.gender',
                'b.date_of_birth',
                DB::raw("DATE_PART('year', AGE(b.date_of_birth)) AS age"), // 👈 Age calculation
                'b.contact_number',
                'b.category',
                'b.aadhar_number',
                'b.household_id',
                'b.active_status',
                'b.created_at',
                'b.updated_at',
                'v.village_name'
            )
            ->get();

        return response()->json([
            'message' => 'All beneficiaries fetched successfully ✅',
            'data' => $beneficiaries
        ]);
    } catch (\Exception $e) {
        Log::error('Get Beneficiaries Error: ' . $e->getMessage());

        return response()->json([
            'message' => 'Failed to fetch beneficiaries.',
            'error' => $e->getMessage()
        ], 500);
    }
}
 
 


public function requestOtp(Request $request)
{
    
    try {
        $response = Http::timeout(60) 
        ->connectTimeout(60)
            ->withHeaders([
                'Content-Type' => 'application/json',
                'REQUEST-ID' => (string) Str::uuid(),
                'TIMESTAMP' => now()->toIso8601ZuluString(),
                'Authorization' => 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJBbFJiNVdDbThUbTlFSl9JZk85ejA2ajlvQ3Y1MXBLS0ZrbkdiX1RCdkswIn0.eyJleHAiOjE3NDU0MDEwMTEsImlhdCI6MTc0NTM5OTgxMSwianRpIjoiNmMyZTljNWYtOWQ2Yi00OGZmLThkZDMtM2U1YjcwMGMwMGMzIiwiaXNzIjoiaHR0cHM6Ly9kZXYubmRobS5nb3YuaW4vYXV0aC9yZWFsbXMvY2VudHJhbC1yZWdpc3RyeSIsInN1YiI6IjlmMzQ5ZGIzLTU1MjItNDJhNC05NTY2LWI1MWZjM2FjYjAxMiIsInR5cCI6IkJlYXJlciIsImF6cCI6IlNCWElEXzAwOTU1MCIsInNlc3Npb25fc3RhdGUiOiIxOTc4OGZlMy0yY2ZiLTQyMDMtOGUyNi1iZjM4YjI0MzdlZTMiLCJhY3IiOiIxIiwiYWxsb3dlZC1vcmlnaW5zIjpbImh0dHA6Ly9sb2NhbGhvc3Q6OTAwNyJdLCJyZXNvdXJjZV9hY2Nlc3MiOnsiU0JYSURfMDA5NTUwIjp7InJvbGVzIjpbInVtYV9wcm90ZWN0aW9uIl19fSwic2NvcGUiOiJvcGVuaWQgZW1haWwgcHJvZmlsZSIsImNsaWVudElkIjoiU0JYSURfMDA5NTUwIiwiY2xpZW50SG9zdCI6IjEwMC42NS4xNjAuMjAzIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJzZXJ2aWNlLWFjY291bnQtc2J4aWRfMDA5NTUwIiwiY2xpZW50QWRkcmVzcyI6IjEwMC42NS4xNjAuMjAzIn0.D1qaeSSzsAb9zXygmjILx4195q2A-i1FJ34ubuBcdYgAjiVC1C__UDXmzjZVSaIMlcuC8dKfUUi44Zjnw5mCpLUuUI43nSIe7OncvhS58AqYa6UZLY6F-RMksjFq9NxB1Sfxgl1Dhc6ybk-2JGx-9sSmigglIxbmSBIQDSSyUS6l5KVPrx20tPfIlXho575gmM4o8tXvc5kmKM_cOjM22vmuEDp27bNmI4iJtZO-At9uxDAACKfPpFjYAqycEKMpNsN1y9fIWxODXb5RfnAmxVpwDMURkG6kNPMjBfC819Sso6StTNWGV1HFGaNFtzSe9jDBJ-5P5MGdQDhwfkr3SA',
            ]) 
            ->post('https://abhasbx.abdm.gov.in/abha/api/v3/enrollment/request/otp', [
                'txnId' => '',
                'scope' => ['abha-enrol'],
                'loginHint' => 'aadhaar',
                'loginId' => 'DaiD+A4vVu/2BJqy/VHHpdWo5PXUvTceKibe+b70svfgtMQWTOg5agXKD7rIY43pUXyhSqeTnVhJfoKxq7JFJsEbVqdQBuMCtcDEabYFI8FceAGOwwAagfTbbNiiY/t/38un3JU4KL28TBZnFpDQchGUHGUQJWGDK8vADs9IGAr8bYK33w9xZ2Qvy/oy8bS264SRP+sBz21U0cSh+N4m9TK8QeSLclGBxIdiISDT9IfqWJmiKrgPjnLX4RDDS/kxgDJEzEMsQAE1bVjdS7nLz3yQj1ojRvOLe4PymD90AhXWaPyVNrcHyvBtJpmF1rfE3txaMs8nI5hFHImSTUqJNakb9t1Cx/TXjOipSPrFB3AdDD5XEkqZ7DmsZr7yjDIG/FhN70H7yixbsMA83mUoq8iMeb/yK5bQ5J2EU6lRA5PGqxugXd1o/xS2Swmadm3h3LDaDny4Dgwf2j8tienF9G7JTvuVLKCHDmm8/4W3SHlqzRWEFQ3oLa5EXQ0SPrTxwxA5JcrRUEX3WICUNrOct2z/RKKfSBx2YcUosJ6B/ted4qza5b4uIvpTL0VjYLZGq+MgJRHT4oigdUJsXCB3nJydwv2bz12VP2waZM+QKVa8eUMOmMpaJ4v1bkb0pZjBXlb7Ipa4ICgRh/2bSl1uEiDmKsiKNsyjTyOLQZ42OxY=', // dynamically passed or validated
                'otpSystem' => 'aadhaar',
            ]);

          
     
        if ($response->successful()) {
            return $response->json();
        }
    
        Log::error('ABHA OTP Request Failed', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);
    
        return 'OTP Request Failed: ' . $response->body();
    
    } catch (\Exception $e) {
        Log::error('Exception while requesting OTP', ['error' => $e->getMessage()]);
        return 'Exception while requesting OTP: ' . $e->getMessage();
    }
}

}
