<?php

namespace App\Http\Controllers\Api\V1\Frontend;

use App\Http\Controllers\Controller;
use App\Models\Backend\Customers\Address;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Frontend\Customer;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Api\V1\Backend\ResponseController;
use Illuminate\Support\Facades\Hash;
use App\Helpers\OpenCartPassword;

class AuthController extends ResponseController
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'firstname' => 'required|string|max:255',
            'lastname' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:oc_customer',
            'telephone' => 'required|digits_between:10,15',
            'postcode' => [
                'required',
                'regex:/^([A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2})$/i'
            ],
            'company' => 'nullable|string|max:255',
            'address_1' => 'required|string|max:255',
            'address_2' => 'nullable|string|max:255',
            'city' => 'required|string|max:255',
            'country_id' => 'required|integer',
            'zone_id' => 'required|integer',
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@])[A-Za-z\d@#$%^&*!]+$/',
                'confirmed'
            ],
            'password_confirmation' => 'required|string|min:6',
            'newsletter' => 'nullable|in:0,1',
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        try {
            $salt = bin2hex(random_bytes(4));
            $hashedPassword = sha1($salt . sha1($salt . sha1($request->password)));
            // dd($hashedPassword, $salt);
            $user = Customer::create([
                'customer_group_id'=> 1,
                'store_id'=> 0,
                'language_id'=> 0,
                'firstname' => $request->firstname,
                'lastname' => $request->lastname,
                'email' => $request->email,
                'telephone' => $request->telephone,
                'custom_field' => json_encode([]),
                'fax' => $request->fax ?? '',
                'token' => '',
                'ip' => $request->ip(),
                'status' => 1, 
                'approved' => 1,
                'epos_user' => 0,
                'epos_user_backend' => 0,
                'restrict_to_ip' => 0,
                'safe' => 0, 
                'date_added' => now(),
                'password' => $hashedPassword,
                'salt' => $salt,
                'newsletter' => $request->newsletter ?? 0,
            ]);
    
            $address = Address::create([
                'customer_id' => $user->customer_id,
                'firstname' => $request->firstname,
                'lastname' => $request->lastname,
                'company' => $request->company,
                'address_1' => $request->address_1,
                'address_2' => $request->address_2,
                'city' => $request->city,
                'postcode' => $request->postcode,
                'country_id' => $request->country_id,
                'zone_id' => $request->zone_id,
                'custom_field' => json_encode([]), // Assuming custom fields are not used
            ]);
    
            $user->address_id = $address->address_id;
            $user->save();
            // Create a token for the user
            Auth::login($user);
            return $this->sendResponse([
                'user' => $user->load('address'),
                'token' =>  $user->createToken('customer-token')->plainTextToken
            ], 'User registered successfully', 201);

        } catch (\Exception $e) {
            return $this->sendError('Registration failed. Please try again.', [], 500);
        }
    }


    public function login(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'email' => 'required|string|email',
            'password' => 'required|string|min:6',
        ]);
        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }

        try {
            $credentials = $request->only('email', 'password');
            $user = Customer::where('email', $credentials['email'])
                ->first();

            if ($user && OpenCartPassword::verify($credentials['password'], $user->password, $user->salt)) {
                Auth::login($user); // Login manually
                $token = $user->createToken('customer-token')->plainTextToken;
                return $this->sendResponse([
                    'user' => $user->load('address'),
                    'token' => $token
                ], 'Login successful', 200);
            }
            return $this->sendError('Invalid credentials', [], 401);


        } catch (\Exception $e) {
            return $this->sendError('Login failed. Please try again.', [], 500);
        }

    }
}
