<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\AppUser;
use Illuminate\Support\Facades\Validator;
use App\Models\VotersData;
use Illuminate\Support\Facades\DB;


class AppUserController extends Controller
{
    
    public function register(Request $request)
{
    try {
    $validated = $request->validate([
        'name' => 'required',
        'email' => 'required|email|unique:app_users',
        'password' => 'required',
        'status' => 'nullable',
    ]);

    $validated['password'] = bcrypt($validated['password']);
     $validated['status'] = 'pending';
    $user = AppUser::create($validated);
    
     // Return a successful JSON response
        return response()->json(['user' => $user, 'message' => 'Registration successful'], 201);
        
    } catch (\Illuminate\Validation\ValidationException $e) {
        // Catch validation errors
        return response()->json([
            'errors' => $e->errors(),
            'message' => 'Validation failed'
        ], 422);

    } catch (\Exception $e) {
        // Catch any other errors
        return response()->json([
            'message' => 'An unexpected error occurred during registration. Please try again later.',
            'error' => $e->getMessage() // Optionally include this for debugging purposes
        ], 500);
    }

    return response()->json(['user' => $user], 200);
}
public function login(Request $request)
{
    try {
        $credentials = $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
        ]);

        $user = AppUser::where('email', $credentials['email'])->first();
   
        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message' => 'Invalid email or password'], 401);
        }
        
         // Check if the user is active
        if ($user->status !== 'active') {
            return response()->json([
                'success' =>false,
                'message' => 'Your account is not approved. Please contact the administrator.'
            ], 403);
        }
         return response()->json([
             'success' => true,
            'message' => 'Login successful',
            'appUser' => $user,
          
        ], 200);
    
        // Generate a token using the custom app_user guard
        // $token = $user->createToken('app_auth_token', [], 'app_user')->plainTextToken;
   
    
    } catch (\Illuminate\Validation\ValidationException $e) {
        return response()->json([
            'errors' => $e->errors(),
            'message' => 'Validation failed'
        ], 422);
    } catch (\Exception $e) {
        return response()->json([
            'message' => 'An unexpected error occurred during login.'
        ], 500);
    }
    
}

    public function userManagement()
{
    $users = AppUser::all(); // Fetch all users
    return view('admin.user_management', compact('users'));
}

public function changeUserStatus($id)
{
    $user = AppUser::findOrFail($id);

    // Set status to 'active' if it is currently 'pending'
    if ($user->status === 'pending') {
        $user->status = 'active';
    } else {
        $user->status = 'pending';
    }

    $user->save();

    return redirect()->route('userManagement')->with('success', 'User status updated successfully.');
}
public function searchWithCnic($cnic)
{
    ///Count the hits t track the how many times api calls//
    $hit = DB::table('api_hits')->first();
        if (!$hit) {
            DB::table('api_hits')->insert(['hit_count' => 0]);
            $hit = DB::table('api_hits')->first();
        }

        // Increment the count in the database
        DB::table('api_hits')->where('id', $hit->id)->increment('hit_count');

        // Get the updated hit count
        $updatedHitCount = DB::table('api_hits')->where('id', $hit->id)->value('hit_count');
        
    //   // Normalize the input CNIC by removing dashes
    //     $normalizedCnic = str_replace('-', '', $cnic);
        
    //     // Find records where CNIC (without dashes) matches the normalized input CNIC
    //     $voterData = VotersData::whereRaw('REPLACE(cnic, "-", "") = ?', [$normalizedCnic])->get();
    
            // Normalize the input CNIC by removing dashes
        $normalizedCnic = str_replace('-', '', $cnic);
        
        // Find the record with the matching CNIC
        $voterData = VotersData::whereRaw('REPLACE(cnic, "-", "") = ?', [$normalizedCnic])->first();
        
        if ($voterData) {
            // Get the gharana_number and block_code of the matched record
            $gharanaNumber = $voterData->gharana_number;
            $blockCode = $voterData->block_code;
        
            // Find all records with the same gharana_number and block_code
            $relatedVoterData = VotersData::where('gharana_number', $gharanaNumber)
                                           ->where('block_code', $blockCode)
                                           ->get();
        
            // Display or process the related records
         return response()->json([
             'success' => true,
            'message' => 'Data Fetched',
            'UserData' => $voterData,
            'OtherFamilyMemberData' => $relatedVoterData,
          
        ], 200);  
        } else {
            dd("No record found with this CNIC.");
        }
                
       
         
   
}

public function update(Request $request)
{
    $user = AppUser::find($request->user_id);
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = bcrypt($request->password);
    $user->save();

    return redirect()->route('userManagement')->with('success', 'User updated successfully.');
}
public function destroy($id)
{
    $user = AppUser::findOrFail($id);
    $user->delete();

    return redirect()->route('userManagement')->with('success', 'User deleted successfully.');
}






}