<?php

namespace App\Http\Controllers\Api\Two;

use App\Http\Controllers\{Controller};
use App\Http\Controllers\Api\Two\{ApiController};
use App\Models\{User, Logs};
use Illuminate\Http\Request;
use Illuminate\Support\Facades\{Validator,Hash, Auth, Http};
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class ApiCustomers extends Controller
{
    /**
     * Register a new user to Ticaga.
     * This method handles the registration of a new user.
     * Billing information is optional. Great for Plugins like Blesta, WHMCS, ClientExec.
     */
    public function register(Request $request)
    {
        $connection = ApiController::connection($request->header("Authorization"));
        if ($connection->content() != '{"result":"true"}') {
            return $connection;
        }

        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:15',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'error' => 'Validation failed',
                'messages' => $validator->errors()
            ], 422);
        }

        $validated = $validator->validated();

        $user = User::create([
            'name' => $validated['name'],
            'email' => $validated['email'],
            'password' => Hash::make($validated['password']),
            'company' => $request->company ?? '',
            'phone_number' => $request->phone_number ?? '',
            'billing_id' => $request->billing_id ?? '',
            'billing_system' => $request->billing_system ?? '',
            'account_manager' => $request->account_manager ?? '0',
            'biography' => $request->biography ?? '',
        ])->assignRole('customer');

        if(config('ticaga.registraton_logs') === true){
            $customer_info = User::find($user->id);
            if($customer_info->billing_system == ''){
                $customer_info->billing_system = 'the API';
            }
            Logs::create([
                'log_type' => 'notice',
                'message' => "User " . $customer_info->name . " has registered via " . ucfirst($customer_info->billing_system) . ".",
                'user_id' => $customer_info->id,
                'customer_id' => $customer_info->id,
                'visible' => '1',
                'ip_address' => app('request')->ip(),
            ]);
        }

        return response()->json(['user' => $user], 201);
    }
    
    public function getUser(Request $request)
    {
        $connection = ApiController::connection($request->header("Authorization"));
        if ($connection->content() != '{"result":"true"}') {
            return $connection;
        }
        
        $user = User::select('*')->where('id', $request->id)->first();

        if (!$user) {
            return response()->json(['error' => 'User not authenticated'], 401);
        } else {
            return response()->json(['user' => $user], 200);
        }
    }

    public function checkEmail(Request $request)
    {
        $connection = ApiController::connection($request->header("Authorization"));
        if ($connection->content() != '{"result":"true"}') {
            return $connection;
        }
        
        $user = User::select('id')->where('email', $request->email_address)->first();

        if (!$user) {
            return response()->json(['error' => 'User not found'], 401);
        } else {
            return response()->json(['user' => $user], 200);
        }
    }

    public function assignUser(Request $request)
    {
        $connection = ApiController::connection($request->header("Authorization"));
        if ($connection->content() != '{"result":"true"}') {
            return $connection;
        }
        
        $user = User::find($request->ticaga_id);
        if (!$user) {
            return response()->json(['error' => 'User not found'], 404);
        }

        $return = $user->update([
            'billing_id' => $request->billing_id,
            'billing_system' => $request->billing_system,
        ]);

        if (!$return) {
            return response()->json(['error' => 'User not authenticated'], 401);
        } else {
            return response()->json(['user' => $return], 200);
        }
    }
}