<?php

namespace Opencart\Extension\Alsendo\Repositories;

require_once(DIR_EXTENSION . 'alsendo/src/Models/SenderAddressTemplate.php');

use Opencart\Extension\Alsendo\Models\SenderAddressTemplate;

class SenderAddressRepository
{
    private object $db;
    private string $tablePrefix;
    private string $tableName;

    public function __construct(object $db, string $tablePrefix = '')
    {
        $this->db = $db;
        $this->tablePrefix = $tablePrefix ?: (defined('\DB_PREFIX') ? \DB_PREFIX : '');
        $this->tableName = $this->tablePrefix . 'alsendo_sender_address_templates';
    }

    public function getAllTemplates(): array
    {
        if (!$this->tableExists()) {
            return [];
        }
        
        $query = $this->db->query("SELECT * FROM `" . $this->tableName . "` ORDER BY `main` DESC, `company_name` ASC");
        
        $templates = [];
        foreach ($query->rows as $row) {
            $templates[] = $this->createTemplateFromRow($row);
        }
        
        return $templates;
    }

    public function getTemplateById(int $id): ?SenderAddressTemplate
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tableName . "` WHERE `id` = '" . (int)$id . "'");
        
        if (!$query->num_rows) {
            return null;
        }
        
        return $this->createTemplateFromRow($query->row);
    }

    public function getMainTemplate(): ?SenderAddressTemplate
    {
        $query = $this->db->query("SELECT * FROM `" . $this->tableName . "` WHERE `main` = 1 LIMIT 1");
        
        if (!$query->num_rows) {
            return null;
        }
        
        return $this->createTemplateFromRow($query->row);
    }

    public function hasMainTemplate(): bool
    {
        if (!$this->tableExists()) {
            return false;
        }
        
        $query = $this->db->query("SELECT COUNT(*) as count FROM `" . $this->tableName . "` WHERE `main` = 1");
        return $query->row['count'] > 0;
    }

    private function tableExists(): bool
    {
        try {
            $query = $this->db->query("SHOW TABLES LIKE '" . $this->tableName . "'");
            return $query->num_rows > 0;
        } catch (\Exception $e) {
            return false;
        }
    }

    public function saveTemplate(SenderAddressTemplate $template): int
    {
        $this->clearMainFlag();
        $template->setMain(true);

        $sql = "INSERT INTO `" . $this->tableName . "` SET 
            `external_id` = " . ($template->getExternalId() !== null ? "'" . $this->db->escape($template->getExternalId()) . "'" : "NULL") . ",
            `company_name` = '" . $this->db->escape($template->getCompanyName()) . "',
            `first_name` = '" . $this->db->escape($template->getFirstName()) . "',
            `last_name` = '" . $this->db->escape($template->getLastName()) . "',
            `full_name` = '" . $this->db->escape($template->getFullName()) . "',
            `street` = '" . $this->db->escape($template->getStreet() ?: '') . "',
            `building_number` = '" . $this->db->escape($template->getBuildingNumber()) . "',
            `apartment_number` = '" . $this->db->escape($template->getApartmentNumber() ?: '') . "',
            `block` = " . ($template->getBlock() !== null ? "'" . $this->db->escape($template->getBlock()) . "'" : "NULL") . ",
            `entrance` = " . ($template->getEntrance() !== null ? "'" . $this->db->escape($template->getEntrance()) . "'" : "NULL") . ",
            `floor` = " . ($template->getFloor() !== null ? "'" . $this->db->escape($template->getFloor()) . "'" : "NULL") . ",
            `postal_code` = '" . $this->db->escape($template->getPostalCode()) . "',
            `city` = '" . $this->db->escape($template->getCity()) . "',
            `country` = '" . $this->db->escape($template->getCountry()) . "',
            `contact_person` = '" . $this->db->escape($template->getContactPerson()) . "',
            `phone_number` = '" . $this->db->escape($template->getPhoneNumber()) . "',
            `email` = '" . $this->db->escape($template->getEmail()) . "',
            `bank_account_number` = '" . $this->db->escape($template->getBankAccountNumber()) . "',
            `bank_code` = " . ($template->getBankCode() !== null ? "'" . $this->db->escape($template->getBankCode()) . "'" : "NULL") . ",
            `additional_bank_account_number` = " . ($template->getAdditionalBankAccountNumber() !== null ? "'" . $this->db->escape($template->getAdditionalBankAccountNumber()) . "'" : "NULL") . ",
            `main` = '" . (int)$template->isMain() . "'";

        $this->db->query($sql);
        return $this->db->getLastId();
    }

    public function updateTemplate(SenderAddressTemplate $template): void
    {
        $sql = "UPDATE `" . $this->tableName . "` SET 
            `external_id` = " . ($template->getExternalId() !== null ? "'" . $this->db->escape($template->getExternalId()) . "'" : "NULL") . ",
            `company_name` = '" . $this->db->escape($template->getCompanyName()) . "',
            `address_type` = '" . $this->db->escape($template->getAddressType()) . "',
            `first_name` = '" . $this->db->escape($template->getFirstName()) . "',
            `last_name` = '" . $this->db->escape($template->getLastName()) . "',
            `full_name` = '" . $this->db->escape($template->getFullName()) . "',
            `street` = '" . $this->db->escape($template->getStreet() ?: '') . "',
            `building_number` = '" . $this->db->escape($template->getBuildingNumber()) . "',
            `apartment_number` = '" . $this->db->escape($template->getApartmentNumber() ?: '') . "',
            `block` = " . ($template->getBlock() !== null ? "'" . $this->db->escape($template->getBlock()) . "'" : "NULL") . ",
            `entrance` = " . ($template->getEntrance() !== null ? "'" . $this->db->escape($template->getEntrance()) . "'" : "NULL") . ",
            `floor` = " . ($template->getFloor() !== null ? "'" . $this->db->escape($template->getFloor()) . "'" : "NULL") . ",
            `postal_code` = '" . $this->db->escape($template->getPostalCode()) . "',
            `city` = '" . $this->db->escape($template->getCity()) . "',
            `country` = '" . $this->db->escape($template->getCountry()) . "',
            `contact_person` = '" . $this->db->escape($template->getContactPerson()) . "',
            `phone_number` = '" . $this->db->escape($template->getPhoneNumber()) . "',
            `email` = '" . $this->db->escape($template->getEmail()) . "',
            `bank_account_number` = '" . $this->db->escape($template->getBankAccountNumber()) . "',
            `bank_code` = " . ($template->getBankCode() !== null ? "'" . $this->db->escape($template->getBankCode()) . "'" : "NULL") . ",
            `additional_bank_account_number` = " . ($template->getAdditionalBankAccountNumber() !== null ? "'" . $this->db->escape($template->getAdditionalBankAccountNumber()) . "'" : "NULL") . "
            WHERE `id` = '" . (int)$template->getId() . "'";

        $this->db->query($sql);
    }

    public function deleteTemplate(int $id): void
    {
        $this->db->query("DELETE FROM `" . $this->tableName . "` WHERE `id` = '" . (int)$id . "'");
    }

    public function setAsMain(int $id): void
    {
        $this->clearMainFlag();
        $this->db->query("UPDATE `" . $this->tableName . "` SET `main` = 1 WHERE `id` = '" . (int)$id . "'");
    }

    private function clearMainFlag(): void
    {
        $this->db->query("UPDATE `" . $this->tableName . "` SET `main` = 0");
    }

    private function createTemplateFromRow(array $row): SenderAddressTemplate
    {
        return new SenderAddressTemplate(
            (int)$row['id'],
            $row['external_id'] ?? null,
            $row['address_type'],
            $row['company_name'],
            $row['first_name'],
            $row['last_name'],
            $row['full_name'],
            $row['street'] ?: null,
            $row['building_number'],
            $row['apartment_number'] ?: null,
            isset($row['block']) ? ($row['block'] ?: null) : null,
            isset($row['entrance']) ? ($row['entrance'] ?: null) : null,
            isset($row['floor']) ? ($row['floor'] ?: null) : null,
            $row['postal_code'],
            $row['city'],
            $row['country'],
            $row['contact_person'],
            $row['phone_number'],
            $row['email'],
            $row['bank_account_number'],
            $row['bank_code'] ?? null,
            $row['additional_bank_account_number'] ?? null,
            (bool)$row['main'],
            $row['pickup_point'] ?? null,
        );
    }
} 