<?php

namespace App\Core\Service;

use App\Core\Repository\PropertyWeb\PropertyWebMetaRepository;
use App\Core\Repository\PropertyWeb\PropertyWebMetaTagRepository;
use App\Core\Repository\PropertyWeb\PropertyWebMetaMappingRepository;
use Exception;
use Illuminate\Support\Facades\Log;
use App\Exceptions\ApiErrorException;

class PropertyWebMetaService
{
    private $propertyWebMetaRepository;
    private $propertyWebMetaTagRepository;
    private $propertyWebMetaMappingRepository;

    public function __construct(
        PropertyWebMetaRepository $propertyWebMetaRepository,
        PropertyWebMetaTagRepository $propertyWebMetaTagRepository,
        PropertyWebMetaMappingRepository $propertyWebMetaMappingRepository
    ) {
        $this->propertyWebMetaRepository = $propertyWebMetaRepository;
        $this->propertyWebMetaTagRepository = $propertyWebMetaTagRepository;
        $this->propertyWebMetaMappingRepository = $propertyWebMetaMappingRepository;
    }

    public function select($params = [], $column = ['*'])
    {
        $response = ['status' => true, 'message' => '', 'data' => null];

        try {
            $data = $this->propertyWebMetaRepository->findByCriteria($params, $column);
            $response = [
                'status' => 1,
                'data' => $data,
            ];
        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['status'] = -1;
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function selectTag($param = [], $column = ['*'])
    {
        $response = ['status' => true, 'message' => '', 'data' => null];

        try {
            $data = $this->propertyWebMetaTagRepository->findByCriteria($param, $column);
            $response = [
                'status' => 1,
                'data' => $data,
            ];
        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['status'] = -1;
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function selectMapping($params = [], $column = ['*'])
    {
        $response = ['status' => true, 'message' => '', 'data' => null];

        try {
            $propertyId = $params['property_id'] ?? null;
            if ($propertyId) {
                $params['criteria'][] = ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId];
            }

            $filter = $params['filter'] ?? null;
            if ($filter) {
                if (isset($filter['property_web_meta_id'])) {
                    $params['criteria'][] = ['field' => 'property_web_meta_id', 'condition' => '=', 'value' => $filter['property_web_meta_id']];
                }
                if (isset($filter['property_web_meta_tag_id'])) {
                    $params['criteria'][] = ['field' => 'property_web_meta_tag_id', 'condition' => '=', 'value' => $filter['property_web_meta_tag_id']];
                }
                if (isset($filter['code'])) {
                    $params['criteria'][] = ['field' => 'code', 'condition' => '=', 'value' => $filter['code']];
                }
            }

            $params['with'] = ['propertyWebMeta:id,name,language_key,order_number', 'propertyWebMetaTag:id,name,language_key,order_number'];
            $data = $this->propertyWebMetaMappingRepository->findByCriteria($params, $column);
            $response = [
                'status' => 1,
                'data' => $data,
            ];
        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['status'] = -1;
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }

    public function syncTag($params = [])
    {
        $response = ['status' => true, 'message' => '', 'data' => null];

        try {
            $propertyId = $params['property_id'] ?? null;
            $propertyWebId = $params['property_web_id'] ?? null;
            $propertyWebMetaTagId = $params['property_web_meta_tag_id'] ?? null;
            $propertyWebMetaId = $params['property_web_meta_id'] ?? null;
            $code = $params['code'] ?? null;
            $text = $params['text'] ?? null;

            $criteria = [
                'criteria' => [
                    ['field' => 'property_id', 'condition' => '=', 'value' => $propertyId],
                    ['field' => 'property_web_id', 'condition' => '=', 'value' => $propertyWebId],
                    ['field' => 'property_web_meta_tag_id', 'condition' => '=', 'value' => $propertyWebMetaTagId],
                    ['field' => 'property_web_meta_id', 'condition' => '=', 'value' => $propertyWebMetaId],
                    ['field' => 'code', 'condition' => '=', 'value' => $code],
                ],
                'firstRow' => 1
            ];

            // Önce kayıt var mı kontrol ediyoruz
            $existing = $this->propertyWebMetaMappingRepository->findByCriteria($criteria);

            if (!empty($existing)) {
                // Kayıt var
                if (is_null($text)) {
                    // Text boş ise silme
                    $id = $existing['id'];
                    $deleteResult = $this->propertyWebMetaMappingRepository->destroy([$id]);
                    if ($deleteResult['status'] != 'success') {
                        throw new Exception($deleteResult['message']);
                    }
                    $response = [
                        'status' => 1,
                        'message' => 'Record deleted successfully.',
                        'data' => null,
                    ];
                } else {
                    // Text dolu ise güncelleme
                    $id = $existing['id'];
                    $data = [
                        'code' => $code,
                        'text' => is_array($text) ? json_encode($text) : $text,
                        'status' => true,
                        'updated_at' => time()
                    ];
                    $updateResult = $this->propertyWebMetaMappingRepository->update($id, $data);
                    if ($updateResult['status'] != 'success') {
                        throw new Exception($updateResult['message']);
                    }
                    $response = [
                        'status' => 1,
                        'message' => 'Record updated successfully.',
                        'data' => $data,
                    ];
                }
            } else {
                // Kayıt yok
                if (!is_null($text)) {
                    // Text dolu ise oluşturma
                    $data = [
                        'property_id' => $propertyId,
                        'property_web_id' => $propertyWebId,
                        'property_web_meta_tag_id' => $propertyWebMetaTagId,
                        'property_web_meta_id' => $propertyWebMetaId,
                        'code' => $code,
                        'text' => is_array($text) ? json_encode($text) : $text,
                        'status' => true,
                        "created_by" => fillOnUndefined($params, "user_id"),
                        "updated_by" => fillOnUndefined($params, "user_id")
                    ];

                    $createResult = $this->propertyWebMetaMappingRepository->create($data);
                    if ($createResult['status'] != 'success') {
                        throw new Exception($createResult['message']);
                    }

                    $response = [
                        'status' => 1,
                        'message' => 'Record created successfully.',
                        'data' => $data,
                    ];
                } else {
                    // Kayıt yok ve text de null ise işlem yapmaya gerek yok (veya başarılı dönülebilir)
                    $response = [
                        'status' => 1,
                        'message' => 'Record not found and text is null, no action taken.',
                        'data' => null,
                    ];
                }
            }
        } catch (ApiErrorException $e) {
            $response['status'] = 0;
            $response['message'] = $e->getMessage();
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['status'] = -1;
            $response['message'] = $e->getMessage();
        }

        return output($response);
    }
}
