<?php

namespace Modules\Admin\app\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Traits\HasFilterRequest;
use App\Traits\HasOrderByRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use JsonException;
use Modules\Admin\app\Http\Requests\ClientRequest;

class ClientController extends Controller
{
    use HasOrderByRequest;
    use HasFilterRequest;

    public function __construct()
    {
        // module check model exist and table
        if (!class_exists(Client::class)) {
            throw new JsonException("user table not exist");
        }
        ;
    }

    public function get(Request $request)
    {
        $client = new Client;

        // Order by
        $this->orderByRequest($client, $request);

        // Filter
        $this->filterRequest(
            builder: $client,
            request: $request,
            filterKeys: [
                'name' => self::F_TEXT,
                'phone' => self::F_TEXT,
                'email' => self::F_TEXT,
                'company' => self::F_TEXT,
                'status' => self::F_BOOLEAN,
                'subscribe' => self::F_BOOLEAN,
            ]
        );

        $responseData = array_merge(
            $client->paginate($request->get('per_page'))->toArray(),
            ['status' => true]
        );

        return response()->json($responseData);
    }

    public function create(ClientRequest $request)
    {
        $payload = $request->all();

        $client = new Client;

        $client->name = $request->get('name');
        $client->password = bcrypt($request->get('password', Client::DEFAULT_PASSWORD));
        $client->email = $request->get('email', '');
        $client->email_verified_at = now();
        $client->phone = $request->get('phone', '');
        $client->country_code = $request->get('country_code', 'AU');
        $client->company = $request->get('company', '');
        $client->save();

        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $filename = $client->id . '.' . $file->getClientOriginalExtension();
            $path = Client::PATH_AVATAR . "/$filename";

            Storage::disk('public')->put($path, $file->get());

            $client->avatar = $path;
            $client->save();
        }

        return response()->json([
            'data' => $client,
            'status' => true
        ]);
    }

    public function update(ClientRequest $request)
    {
        $id = $request->get('id');

        $client = Client::find($id);

        if ($request->has('name')) {
            $client->name = $request->get('name');
        }
        if ($request->has('password') && !empty($request->get('password'))) {
            $client->password = bcrypt($request->get('password'));
        }
        if ($request->has('email')) {
            $client->email = $request->get('email');
        }
        if ($request->has('phone')) {
            $client->phone = $request->get('phone');
        }
        if ($request->has('company')) {
            $client->company = $request->get('company');
        }
        if ($request->has('country_code')) {
            $client->country_code = $request->get('country_code');
        }
        if ($request->has('status')) {
            $client->status = ($request->get('status') == 'true' || $request->get('status') == '1') ? 1 : 0;
        }
        $client->save();

        if ($request->hasFile('avatar')) {
            $file = $request->file('avatar');
            $filename = $client->id . '.' . $file->getClientOriginalExtension();
            $path = Client::PATH_AVATAR . "/$filename";
            $avatarOld = Storage::disk('public')->exists($client->avatar);

            if ($avatarOld) {
                Storage::disk('public')->delete($client->avatar);
            }

            Storage::disk('public')->put($path, $file->get());
            $client->update([
                'avatar' => $path
            ]);

        }

        return response()->json([
            'data' => $client,
            'status' => true
        ]);
    }

    public function delete(ClientRequest $request)
    {
        $id = $request->get('id');

        Client::destroy($id);
        return response()->json([
            'status' => true
        ]);
    }

    // Delete multiple clients
    public function deletes(ClientRequest $request)
    {
        $clients = $request->get('clients');
        $ids = collect($clients)->pluck('id');
        Client::whereIn('id', $ids)->delete();
        return response()->json([
            'data' => $ids,
            'status' => true
        ]);
    }

    // Update multiple clients
    public function updates(ClientRequest $request)
    {
        $clients = $request->get('clients');
        $ids = collect($clients)->pluck('id');

        foreach ($clients as $ClientRequest) {
            // convert to object|array to array
            $ClientRequest = collect($ClientRequest)->toArray();
            // handle array
            $client = Client::find($ClientRequest['id']);
            if ($client) {
                // exclude id field
                unset($client['id']);

                $client->update($ClientRequest);
            }
        }
        return response()->json([
            'data' => Client::whereIn('id', $ids)->get(),
            'status' => true
        ]);
    }
}
