<?php

namespace Core\App\Models;

use PDO;

class ShippingIntegrationModel
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = \db();
    }

    /* ============================
       Get all integrations indexed by provider
    ============================ */
    public function getAllIndexed(): array
    {
        $stmt = $this->db->query(
            "SELECT * FROM shipping_integrations"
        );

        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $indexed = [];

        foreach ($rows as $row) {
            $indexed[$row['provider']] = $row;
        }

        return $indexed;
    }

    /* ============================
       Get single integration by provider
    ============================ */
    public function getByProvider(string $provider): ?array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM shipping_integrations
             WHERE provider = :provider
             LIMIT 1"
        );

        $stmt->execute([
            ':provider' => $provider
        ]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    /* ============================
       Save or Update integration
    ============================ */
    public function save(
        string $provider,
        string $displayName,
        ?string $apiId,
        ?string $apiToken,
        int $isActive,
        string $countryCode = 'DZ'
    ): void {
        $exists = $this->getByProvider($provider);

        if ($exists) {
            $stmt = $this->db->prepare(
                "UPDATE shipping_integrations SET
                    display_name = :display_name,
                    api_id       = :api_id,
                    api_token    = :api_token,
                    is_active    = :is_active,
                    country_code = :country_code
                 WHERE provider = :provider"
            );
        } else {
            $stmt = $this->db->prepare(
                "INSERT INTO shipping_integrations
                    (provider, display_name, api_id, api_token, is_active, country_code)
                 VALUES
                    (:provider, :display_name, :api_id, :api_token, :is_active, :country_code)"
            );
        }

        $stmt->execute([
            ':provider'      => $provider,
            ':display_name'  => $displayName,
            ':api_id'        => $apiId,
            ':api_token'     => $apiToken,
            ':is_active'     => $isActive,
            ':country_code'  => $countryCode,
        ]);
    }

    /* ============================
       Toggle activation status
    ============================ */
    public function toggle(string $provider): void
    {
        $stmt = $this->db->prepare(
            "UPDATE shipping_integrations
             SET is_active = IF(is_active = 1, 0, 1)
             WHERE provider = :provider"
        );

        $stmt->execute([
            ':provider' => $provider
        ]);
    }
}
