<?php

namespace Bot;


class FileHandler
{
    private string $filePath;


    public function __construct()
    {

        $this->filePath = __DIR__ . '/../parent_ids.json';
    }
    public function saveState($chatId, $state)
    {
        $data = $this->getAllData();
        $data[$chatId]['state'] = $state;
        $success = $this->saveAllData($data);
        if (!$success) {
            error_log("❌ FileHandler: Failed to save state for chatId: $chatId");
        }
        return $success;
    }


    public function clearUserData($chatId)
    {
        $data = $this->getAllData();
        if (isset($data[$chatId])) {
            $data[$chatId] = [];
            return $this->saveAllData($data);
        }
        return true;
    }

    public function getState($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['state'] ?? NULL;
    }

    public function clearState($chatId)
    {
        $data = $this->getAllData();
        if (isset($data[$chatId]['state'])) {
            unset($data[$chatId]['state']);
            error_log("Cleared state for chatId: $chatId");
            return $this->saveAllData($data);
        }
        error_log("No state to clear for chatId: $chatId");
        return true;
    }

    private function getAllData()
    {
        $content = file_get_contents($this->filePath);
        $data = json_decode($content, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("JSON decode error: " . json_last_error_msg());
            return [];
        }
        return $data ?? [];
    }

    private function saveAllData($data)
    {
        $jsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        if ($jsonData === false) {
            error_log("❌ FileHandler: JSON encode failed: " . json_last_error_msg());
            return false;
        }
        $file = fopen($this->filePath, 'c+');
        if ($file === false) {
            error_log("❌ FileHandler: Cannot open {$this->filePath} for writing.");
            return false;
        }
        if (flock($file, LOCK_EX)) {
            ftruncate($file, 0);
            fwrite($file, $jsonData);
            fflush($file);
            flock($file, LOCK_UN);
        } else {
            error_log("❌ FileHandler: Cannot lock {$this->filePath}.");
            fclose($file);
            return false;
        }
        fclose($file);
        return true;
    }
    public function addMessageId($chatId, $messageId)
    {
        $data = $this->getAllData();
        if (!isset($data[$chatId]['message_ids'])) {
            $data[$chatId]['message_ids'] = [];
        }
        $data[$chatId]['message_ids'][] = $messageId;
        $this->saveAllData($data);
    }

    public function getMessageIds($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['message_ids'] ?? [];
    }

    public function clearMessageIds($chatId)
    {
        $data = $this->getAllData();
        if (isset($data[$chatId]['message_ids'])) {
            unset($data[$chatId]['message_ids']);
        }
        $this->saveAllData($data);
    }

    public function saveMessageId($chatId, $messageId)
    {
        $data = $this->getAllData();
        $data[$chatId]['message_id'] = $messageId;
        $this->saveAllData($data);
    }

    public function getMessageId($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['message_id'] ?? null;
    }


    public function setNickname($chatId, $nickname)
    {
        $all = $this->getTempData($chatId);
        $all['nick_name'] = $nickname;
        $this->setTempData($chatId, $all);
    }

    public function setTempData($chatId, array $data): void
    {
        $all = $this->getAllData();

        if (!isset($all[$chatId])) {
            $all[$chatId] = [];
        }

        $all[$chatId]['temp'] = $data;

        $this->saveAllData($all);
    }
    public function getTempData($chatId): array
    {
        $all = $this->getAllData();
        return $all[$chatId]['temp'] ?? [];
    }
    public function getUserName($chatId)
    {
        $data = $this->getTempData($chatId);
        return $data['first_name'] . ' ' . $data['last_name'] ?? NULL;
    }
    public function getFirstName($chatId)
    {
        $data = $this->getTempData($chatId);
        return $data['first_name'] ?? NULL;
    }
    public function getLastName($chatId)
    {
        $data = $this->getTempData($chatId);
        return $data['last_name'] ?? NULL;
    }
    public function getNickName($chatId)
    {
        $data = $this->getTempData($chatId);
        return $data['nick_name'] ?? NULL;
    }
    public function clearTempData($chatId): void
    {
        $all = $this->getAllData();
        if (isset($all[$chatId]['temp'])) {
            unset($all[$chatId]['temp']);
            $this->saveAllData($all);
        }
    }


    public function setLeaderData($chatId, array $data): void
    {
        $all = $this->getAllData();

        if (!isset($all[$chatId])) {
            $all[$chatId] = [];
        }

        // ترکیب داده جدید با داده قبلی
        $existingTour = $all[$chatId]['leader'] ?? [];
        $all[$chatId]['leader'] = array_merge($existingTour, $data);

        $this->saveAllData($all);
    }
    public function getLeaderData($chatId): array
    {
        $all = $this->getAllData();
        return $all[$chatId]['leader'] ?? [];
    }
    public function clearLeaderData($chatId): void
    {
        $all = $this->getAllData();
        if (isset($all[$chatId]['leader'])) {
            unset($all[$chatId]['leader']);
            $this->saveAllData($all);
        }
    }

    public function getLeaderName($chatId)
    {
        $data = $this->getLeaderData($chatId);
        return $data['first_name'] . ' ' . $data['last_name'] ?? NULL;
    }
    public function setLeaderNickname($chatId, $nickname)
    {
        $all = $this->getLeaderData($chatId);
        $all['nick_name'] = $nickname;
        $this->setLeaderData($chatId, $all);
    }


    //    public function setTourData($chatId, array $data): void {
    //        $all = $this->getAllData();
    //
    //        if (!isset($all[$chatId])) {
    //            $all[$chatId] = [];
    //        }
    //
    //        $all[$chatId]['tour'] = $data;
    //
    //        $this->saveAllData($all);
    //    }

    public function setTourData($chatId, array $data): void
    {
        $all = $this->getAllData();

        if (!isset($all[$chatId])) {
            $all[$chatId] = [];
        }

        // ترکیب داده جدید با داده قبلی
        $existingTour = $all[$chatId]['tour'] ?? [];
        $all[$chatId]['tour'] = array_merge($existingTour, $data);

        $this->saveAllData($all);
    }

    public function getTourData($chatId): array
    {
        $all = $this->getAllData();
        return $all[$chatId]['tour'] ?? [];
    }
    public function clearTourData($chatId): void
    {
        $all = $this->getAllData();
        if (isset($all[$chatId]['tour'])) {
            unset($all[$chatId]['tour']);
            $this->saveAllData($all);
        }
    }
    public function saveTourId($chatId, $tourId)
    {
        $data = $this->getAllData();
        $data[$chatId]['tour_id'] = $tourId;
        $this->saveAllData($data);
    }
    public function getTourId($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['tour_id'] ?? null;
    }
    public function saveDiscountCode($chatId, $code): void
    {
        $data = $this->getAllData();
        $data[$chatId]['discount_code'] = $code;
        $this->saveAllData($data);
    }
    public function saveDiscountType($chatId, $type)
    {
        $data = $this->getAllData();
        $data[$chatId]['discount_type'] = $type;
        $this->saveAllData($data);
    }

    public function saveDiscountValue($chatId, $value)
    {
        $data = $this->getAllData();
        $data[$chatId]['discount_value'] = $value;
        $this->saveAllData($data);
    }
    public function saveMaxUses($chatId, $maxUses)
    {
        $data = $this->getAllData();
        $data[$chatId]['max_uses'] = $maxUses;
        $this->saveAllData($data);
    }

    public function getDiscountData($chatId)
    {
        $data = $this->getAllData();
        return [
            'code' => $data[$chatId]['discount_code'] ?? null,
            'type' => $data[$chatId]['discount_type'] ?? null,
            'value' => $data[$chatId]['discount_value'] ?? null,
            'max_uses' => $data[$chatId]['max_uses'] ?? null,
        ];
    }
    public function clearDiscountData($chatId)
    {
        $data = $this->getAllData();
        unset($data[$chatId]['discount_code']);
        unset($data[$chatId]['discount_type']);
        unset($data[$chatId]['discount_value']);
        unset($data[$chatId]['max_uses']);
        $this->saveAllData($data);
    }


    public function saveFinalAmount($chatId, $amount)
    {
        $data = $this->getAllData();
        $data[$chatId]['final_amount'] = $amount;
        $this->saveAllData($data);
    }

    public function getFinalAmount($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['final_amount'] ?? null;
    }



    public function getLeaderFirstName($chatId)
    {
        $data = $this->getLeaderData($chatId);
        return $data['first_name'] ?? NULL;
    }
    public function getLeaderLastName($chatId)
    {
        $data = $this->getLeaderData($chatId);
        return $data['last_name'] ?? NULL;
    }
    public function getLeaderNickName($chatId)
    {
        $data = $this->getLeaderData($chatId);
        return $data['nick_name'] ?? NULL;
    }


    public function saveTemporaryData($chatId, $key, $value)
    {
        $data = $this->getAllData();

        if (!isset($data[$chatId]['temp_guide_data']) || !is_array($data[$chatId]['temp_guide_data'])) {
            $data[$chatId]['temp_guide_data'] = [];
        }
        $data[$chatId]['temp_guide_data'][$key] = $value;
        $this->saveAllData($data);
    }

    public function getTemporaryData($chatId): ?array
    {
        $data = $this->getAllData();
        return $data[$chatId]['temp_guide_data'] ?? null;
    }

    public function clearTemporaryData($chatId): void
    {
        $data = $this->getAllData();

        if (isset($data[$chatId]['temp_guide_data'])) {
            unset($data[$chatId]['temp_guide_data']);
            $this->saveAllData($data);
        }
    }
    public function saveManualWithdrawalContext($chatId, $context): void
    {
        $data = $this->getAllData();
        $data[$chatId]['manual_withdrawal_context'] = $context;
        $this->saveAllData($data);
    }
    public function getManualWithdrawalContext($chatId)
    {
        $data = $this->getAllData();
        return $data[$chatId]['manual_withdrawal_context'] ?? null;
    }
    public function clearManualWithdrawalContext($chatId): void
    {
        $data = $this->getAllData();

        if (isset($data[$chatId]['manual_withdrawal_context'])) {
            unset($data[$chatId]['manual_withdrawal_context']);
            $this->saveAllData($data);
        }
    }
   

}
