<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Helpers\ApiHelper;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Facades\Excel;

class ImportController extends Controller
{
    // public function importUsers(Request $request)
    // {
    //     try {

    //         $validator = Validator::make($request->all(), [
    //             'file' => 'required|mimes:xlsx,xls,csv'
    //         ]);

    //         if ($validator->fails()) {

    //             return ApiHelper::validationError(
    //                 $validator->errors()->first(),
    //                 $validator->errors()
    //             );
    //         }

    //         // Read Excel File
    //         $rows = Excel::toArray([], $request->file('file'));

    //         // First Sheet Data
    //         $excelData = $rows[0];

    //         // Remove Header Row
    //         unset($excelData[0]);

    //         $insertedUsers = [];
    //         $skippedUsers = [];

    //         foreach ($excelData as $row) {

    //             /*
    //         Excel Format:
    //         0 => name
    //         1 => email
    //         2 => phone
    //         */

    //             $name = $row[0] ?? null;
    //             $email = $row[1] ?? null;
    //             $phone = $row[2] ?? null;

    //             // Skip Empty Rows
    //             if (!$email) {

    //                 $skippedUsers[] = [
    //                     'email' => null,
    //                     'reason' => 'Email missing'
    //                 ];

    //                 continue;
    //             }

    //             // Check Duplicate User
    //             $exists = User::where('email', $email)->exists();

    //             if ($exists) {

    //                 $skippedUsers[] = [
    //                     'email' => $email,
    //                     'reason' => 'User already exists'
    //                 ];

    //                 continue;
    //             }

    //             // Create User
    //             $user = User::create([
    //                 'name' => $name,
    //                 'email' => $email,
    //                 'phone' => $phone,
    //                 'password' => Hash::make('Password@2026'),
    //                 'role_id' => 3,
    //             ]);

    //             $insertedUsers[] = $user;
    //         }

    //         return ApiHelper::success(
    //             'Users imported successfully',
    //             [
    //                 'total_imported' => count($insertedUsers),
    //                 'total_skipped' => count($skippedUsers),
    //                 'skipped_users' => $skippedUsers
    //             ]
    //         );
    //     } catch (\Exception $e) {

    //         return ApiHelper::error(
    //             'IMPORT_USERS_01',
    //             'Something went wrong during user import',
    //             $e
    //         );
    //     }
    // }

    public function importUsers(Request $request)
    {
        try {

            if (($access = ApiHelper::checkRoleAccess([1])) !== true) {
                return $access;
            }

            $validator = Validator::make($request->all(), [
                'file' => 'required|mimes:xlsx,xls,csv'
            ]);

            if ($validator->fails()) {

                return ApiHelper::validationError(
                    $validator->errors()->first(),
                    $validator->errors()
                );
            }

            /*
        |--------------------------------------------------------------------------
        | Read Excel File
        |--------------------------------------------------------------------------
        */

            $rows = Excel::toArray([], $request->file('file'));

            $excelData = $rows[0];

            /*
        |--------------------------------------------------------------------------
        | Remove Header Row
        |--------------------------------------------------------------------------
        */

            unset($excelData[0]);

            $insertedUsers = [];

            $updatedUsers = [];

            $skippedUsers = [];

            foreach ($excelData as $row) {

                /*
            |--------------------------------------------------------------------------
            | Excel Columns
            |--------------------------------------------------------------------------
            |
            | 0 => name
            | 1 => email
            | 2 => phone
            |
            */

                $name = $row[0] ?? null;

                $email = $row[1] ?? null;

                $phone = $row[2] ?? null;

                /*
            |--------------------------------------------------------------------------
            | Skip Empty Email
            |--------------------------------------------------------------------------
            */

                if (
                    empty($name) ||
                    empty($email) ||
                    empty($phone)
                ) {

                    $skippedUsers[] = [

                        'name' => $name,

                        'email' => $email,

                        'phone' => $phone,

                        'reason' => 'Name, email or phone missing'
                    ];

                    continue;
                }

                if (
                    empty($name) &&
                    empty($email) &&
                    empty($phone)
                ) {

                    $skippedUsers[] = [

                        'row' => $row,

                        'reason' => 'Empty row'
                    ];

                    continue;
                }

                /*
            |--------------------------------------------------------------------------
            | Check Existing User
            |--------------------------------------------------------------------------
            */

                $user = User::where(
                    'email',
                    $email
                )->first();

                /*
            |--------------------------------------------------------------------------
            | Update Existing User
            |--------------------------------------------------------------------------
            */

                if ($user) {

                    $user->update([

                        'name' => $name,

                        'phone' => $phone,
                    ]);

                    $updatedUsers[] = [
                        'id' => $user->id,
                        'email' => $user->email
                    ];

                    continue;
                }

                /*
            |--------------------------------------------------------------------------
            | Create New User
            |--------------------------------------------------------------------------
            */

                $newUser = User::create([

                    'name' => $name,

                    'email' => $email,

                    'phone' => $phone,

                    'password' => Hash::make('Password@2026'),

                    'role_id' => 3,
                ]);

                $insertedUsers[] = [
                    'id' => $newUser->id,
                    'email' => $newUser->email
                ];
            }

            /*
        |--------------------------------------------------------------------------
        | Response
        |--------------------------------------------------------------------------
        */

            return ApiHelper::success(
                'Users imported successfully',
                [

                    'total_inserted' => count($insertedUsers),

                    'total_updated' => count($updatedUsers),

                    'total_skipped' => count($skippedUsers),

                    // 'inserted_users' => $insertedUsers,

                    // 'updated_users' => $updatedUsers,

                    // 'skipped_users' => $skippedUsers,
                ]
            );
        } catch (\Exception $e) {

            return ApiHelper::error(
                'IMPORT_USERS_01',
                'Something went wrong during user import',
                $e
            );
        }
    }

    public function fetchUsers(Request $request)
    {
        try {

            if (($access = ApiHelper::checkRoleAccess([1])) !== true) {
                return $access;
            }

            $validator = Validator::make($request->all(), [

                'search' => 'nullable|string',

                'per_page_count' => 'nullable|integer|min:1',

                'curr_page' => 'nullable|integer|min:1',
            ]);

            if ($validator->fails()) {

                return ApiHelper::validationError(
                    $validator->errors()->first(),
                    $validator->errors()
                );
            }

            /*
        |--------------------------------------------------------------------------
        | Base Query
        |--------------------------------------------------------------------------
        */

            $query = User::query()

                ->where('role_id', 3)

                ->latest();

            if ($request->filled('search')) {

                $search = $request->search;

                $query->where(function ($q) use ($search) {

                    $q->where('name', 'LIKE', '%' . $search . '%')

                        ->orWhere('email', 'LIKE', '%' . $search . '%')

                        ->orWhere('phone', 'LIKE', '%' . $search . '%');
                });
            }

            /*
        |--------------------------------------------------------------------------
        | Pagination
        |--------------------------------------------------------------------------
        */

            $perPage = $request->per_page_count ?? 10;

            $currentPage = $request->curr_page ?? 1;

            $users = $query->paginate(
                $perPage,
                ['*'],
                'curr_page',
                $currentPage
            );

            /*
        |--------------------------------------------------------------------------
        | Format Response Data
        |--------------------------------------------------------------------------
        */

            $users->getCollection()->transform(function ($item) {

                $item->formatted_created_at =
                    ApiHelper::formatDateTime(
                        $item->created_at
                    );

                return $item;
            });

            /*
        |--------------------------------------------------------------------------
        | Custom Response
        |--------------------------------------------------------------------------
        */

            $response = [

                'users' => $users->items(),

                'pagination' => [

                    'current_page' => $users->currentPage(),

                    'last_page' => $users->lastPage(),

                    'per_page' => $users->perPage(),

                    'total' => $users->total(),

                    'from' => $users->firstItem(),

                    'to' => $users->lastItem(),

                    'has_more_pages' => $users->hasMorePages(),
                ]
            ];

            return ApiHelper::success(
                'Users fetched successfully',
                $response
            );
        } catch (\Exception $e) {

            return ApiHelper::error(
                'FETCH_USERS_01',
                'Something went wrong while fetching users',
                $e
            );
        }
    }

    public function deleteUser($id)
    {
        try {

            if (($access = ApiHelper::checkRoleAccess([1])) !== true) {
                return $access;
            }

            $user = User::find($id);

            if (!$user) {

                return ApiHelper::error(
                    'DELETE_USER_01',
                    'User not found',
                    null,
                    404
                );
            }

            $user->delete();

            return ApiHelper::success(
                'User deleted successfully'
            );
        } catch (\Exception $e) {

            return ApiHelper::error(
                'DELETE_USER_02',
                'Something went wrong while deleting user',
                $e
            );
        }
    }

    public function showUser($id)
    {
        try {
            if (($access = ApiHelper::checkRoleAccess([1])) !== true) {
                return $access;
            }

            /*
        |--------------------------------------------------------------------------
        | Find User
        |--------------------------------------------------------------------------
        */

            $user = User::select('id', 'name', 'email', 'phone')->where('role_id', 3)->find($id);

            if (!$user) {

                return ApiHelper::error(
                    'EDIT_USER_01',
                    'User not found',
                    null,
                    404
                );
            }

            /*
        |--------------------------------------------------------------------------
        | Format Data
        |--------------------------------------------------------------------------
        */

            return ApiHelper::success(
                'User fetched successfully',
                $user
            );
        } catch (\Exception $e) {

            return ApiHelper::error(
                'EDIT_USER_02',
                'Something went wrong while fetching user',
                $e
            );
        }
    }

    public function updateUser(Request $request)
    {
        try {

            if (($access = ApiHelper::checkRoleAccess([1])) !== true) {
                return $access;
            }

            $validator = Validator::make($request->all(), [

                'id' => 'required|exists:users,id',

                'name' => 'required|string|max:255',

                'email' => 'required|email|unique:users,email,' . $request->id,

                'phone' => 'required|string|max:20',
            ]);

            if ($validator->fails()) {

                return ApiHelper::validationError(
                    $validator->errors()->first(),
                    $validator->errors()
                );
            }

            /*
        |--------------------------------------------------------------------------
        | Find User
        |--------------------------------------------------------------------------
        */

            $user = User::find($request->id);

            if (!$user) {

                return ApiHelper::error(
                    'UPDATE_USER_01',
                    'User not found',
                    null,
                    404
                );
            }

            /*
        |--------------------------------------------------------------------------
        | Update User
        |--------------------------------------------------------------------------
        */

            $user->update([

                'name' => $request->name,

                'email' => $request->email,

                'phone' => $request->phone,
            ]);

            return ApiHelper::success(
                'User updated successfully',
                $user->fresh()
            );
        } catch (\Exception $e) {

            return ApiHelper::error(
                'UPDATE_USER_02',
                'Something went wrong while updating user',
                $e
            );
        }
    }
}
