<?php

namespace App\Http\Controllers\Api\V1\Backend\System;

use App\Http\Controllers\Api\V1\Backend\ResponseController;
use App\Http\Controllers\Controller;
use App\Models\Backend\Catalog\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class UserController extends ResponseController
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        try {
            $users = User::all();
            if ($users->isEmpty()) {
                return $this->sendError('No users found.', 404);
            }
            return $this->sendResponse($users, 'Users retrieved successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to retrieve users: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'user_group_id' => 'required|integer',
            'username' => 'required|string|max:255',
            'firstname' => 'required|string|max:255',
            'lastname' => 'required|string|max:255',
            'status' => 'required|integer|in:0,1',
            'email' => 'required|string|email|max:255|unique:oc_user',
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@])[A-Za-z\d@#$%^&*!]+$/',
                'confirmed'
            ]
        ]);

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

            $salt = bin2hex(random_bytes(4));
            $hashedPassword = sha1($salt . sha1($salt . sha1($request->password)));
            $image = '';
            if ($request->hasFile('image')) {
                $dir = 'system/users';

                if (!Storage::disk('public')->exists($dir)) {
                    Storage::disk('public')->makeDirectory($dir);
                }

                $path = $request->file('image')->store($dir, 'public');
                $image = Storage::url($path);
            }
            // dd($hashedPassword, $salt);
            $user = User::create([
                'user_group_id' => $request->user_group_id,
                'username' => $request->username,
                'firstname' => $request->firstname,
                'lastname' => $request->lastname,
                'email' => $request->email,
                'ip' => $request->ip(),
                'status' => $request->status,
                'date_added' => now(),
                'password' => $hashedPassword,
                'salt' => $salt,
                'image' => $image,
                'code' => $request->code ?? ''
            ]);

            return $this->sendResponse($user, 'User created successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to create user: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        try {
            $user = User::findOrFail($id);
            return $this->sendResponse($user, 'User retrieved successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to retrieve user: ' . $e->getMessage(), 404);
        }
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        try {
            $user = User::findOrFail($id);
            return $this->sendResponse($user, 'User retrieved successfully for editing.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to retrieve user for editing: ' . $e->getMessage(), 404);
        }
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        $validator = Validator::make($request->all(), [
            'user_group_id' => 'required|integer',
            'username' => 'required|string|max:255',
            'firstname' => 'required|string|max:255',
            'lastname' => 'required|string|max:255',
            'status' => 'required|integer|in:0,1',
            'email' => 'required|string|email|max:255',
            'password' => [
                'required',
                'string',
                'min:8',
                'regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@])[A-Za-z\d@#$%^&*!]+$/',
                'confirmed'
            ]
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors(), 422);
        }
        try {
            $user = User::findOrFail($id);

            $salt = bin2hex(random_bytes(4));
            $hashedPassword = sha1($salt . sha1($salt . sha1($request->password)));
            $image = $user->image;

            if ($request->hasFile('image')) {
                $dir = 'system/users';

                if (!Storage::disk('public')->exists($dir)) {
                    Storage::disk('public')->makeDirectory($dir);
                }

                $path = $request->file('image')->store($dir, 'public');
                $image = Storage::url($path);
            }

            $user->update([
                'user_group_id' => $request->user_group_id,
                'username' => $request->username,
                'firstname' => $request->firstname,
                'lastname' => $request->lastname,
                'email' => $request->email,
                'ip' => $request->ip(),
                'status' => $request->status,
                'password' => $hashedPassword,
                'salt' => $salt,
                'image' => $image,
                'code' => $request->code ?? ''
            ]);

            return $this->sendResponse($user, 'User updated successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to update user: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
