<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\RequestModel as CustomerRequest;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

class UserRequestController extends Controller
{
    // Show all requests
    public function index()
    {
        $requests = CustomerRequest::orderBy('id', 'desc')->get();
        return view('admin.requests', compact('requests'));
    }

    // Approve user request
    public function approve($id)
    {
        $requestData = CustomerRequest::findOrFail($id);

        DB::beginTransaction();
        try {
            // Generate unique Customer ID
            $latestUser = User::orderBy('id', 'desc')->first();
            $nextId = $latestUser ? $latestUser->id + 1 : 1;
            $customerId = 'CID-' . date('Y') . '-' . str_pad($nextId, 6, '0', STR_PAD_LEFT);

            // Create user record
            $user = new User();
            $user->customer_id = $customerId;
            $user->customer_name = $requestData->customer_name;
            $user->company_name = $requestData->company_name;
            $user->designation = $requestData->designation;
            $user->email = $requestData->email;
            $user->mobile_no = $requestData->mobile_no;
            $user->address = $requestData->address;
            $user->pincode = $requestData->pincode;
            $user->date = now()->format('Y-m-d');
            $user->password = Hash::make('123456'); // default password (you can change logic)
            $user->save();

            // Update request status
            $requestData->status = 'approved';
            $requestData->save();

            DB::commit();
            return redirect()->back()->with('success', 'Request approved and user created successfully.');
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->with('error', 'Something went wrong: ' . $e->getMessage());
        }
    }

    // Reject request
    public function reject($id)
    {
        $requestData = CustomerRequest::findOrFail($id);
        $requestData->status = 'rejected';
        $requestData->save();

        return redirect()->back()->with('info', 'Request rejected successfully.');
    }
}
