<?php

namespace App\Http\Controllers\V1;

use App\Core\Service\PropertyCompetitorGroupService;
use App\Exceptions\ApiErrorException;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Exception;

class PropertyCompetitorGroupController extends Controller
{

    private $params;
    private $request;
    private $propertyCompetitorGroupService;

    public function __construct(
        Request $request,
        PropertyCompetitorGroupService $propertyCompetitorGroupService
    )
    {
        $this->propertyCompetitorGroupService = $propertyCompetitorGroupService;
        $this->request = $request;
        $this->params = $request->all();
    }

    public function getPropertyCompetitorGroup(Request $request)
    {

        $params = $this->params;

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];

        try {

            $requestSelectCriteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $params['params']['property_id']],
                ]
            ];

            // created_by, updated_by, created_at, updated_at alanları get cevaplarında gizlenir
            $columns = ['id', 'property_id', 'name', 'status'];
            $requestSelectResult = $this->propertyCompetitorGroupService->selectPropertyCompetitorGroup($requestSelectCriteria, $columns);

            if ($requestSelectResult['status'] != 'success') {
                throw new ApiErrorException($requestSelectResult['message']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $requestSelectResult['data']];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }
        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function syncPropertyCompetitorGroup(Request $request)
    {

        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];

        DB::beginTransaction();

        try {

            $requestParams = [
                'id' => $this->params['params']['id'] ?? null,
                'property_id' => $this->params['params']['property_id'] ?? null,
                'name' => $this->params['params']['name'] ?? null,
                'status' => $this->params['params']['status'] ?? 1,
                // Öncelik: auth üzerinden gelen kullanıcı
                'user_id' => ($this->request->auth->id ?? null) ?: ($this->params['params']['user_id'] ?? null),
            ];

            $requestResult = $this->propertyCompetitorGroupService->syncPropertyCompetitorGroup($requestParams);

            if ($requestResult['status'] != 'success') {
                throw new ApiErrorException($requestResult['message']);
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $requestResult['data']];

        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }

        if ($response['status']) {
            DB::commit();
        } else {
            DB::rollBack();
        }

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);

    }

    public function getPropertyCompetitorGroupMapping(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];

        try {
            $requestParams = [
                'property_id' => $this->params['params']['property_id'] ?? null,
                'competitor_group_id' => $this->params['params']['competitor_group_id'] ?? null,
            ];

            $result = $this->propertyCompetitorGroupService->getPropertyCompetitorGroupMapping($requestParams);

            if (($result['status'] ?? false) !== true && ($result['status'] ?? '') !== 'success') {
                throw new ApiErrorException($result['message'] ?? 'unknown_error');
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $result['data'] ?? null];
        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

    public function syncPropertyCompetitorGroupMapping(Request $request)
    {
        $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];

        DB::beginTransaction();
        try {
            $requestParams = [
                'property_id' => $this->params['params']['property_id'] ?? null,
                'competitor_group_id' => $this->params['params']['competitor_group_id'] ?? null,
                'competitor' => $this->params['params']['competitor'] ?? [],
                // Öncelik: auth üzerinden gelen kullanıcı
                'user_id' => ($this->request->auth->id ?? null) ?: ($this->params['params']['user_id'] ?? null),
            ];

            $result = $this->propertyCompetitorGroupService->syncPropertyCompetitorGroupMapping($requestParams);

            if (($result['status'] ?? false) !== true && ($result['status'] ?? '') !== 'success') {
                throw new ApiErrorException($result['message'] ?? 'unknown_error');
            }

            $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $result['data'] ?? null];
        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
            $response['statusCode'] = 400;
        } catch (Exception $e) {
            $message = $e->getFile() . ' ' . $e->getLine() . ' ' . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
            $response['statusCode'] = 500;
        }

        if ($response['status']) {
            DB::commit();
        } else {
            DB::rollBack();
        }

        return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);
    }

}
