<?php

namespace App\Service;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MailChimpService
{
    protected $apiKey;
    protected $dataCenter;
    protected $baseUrl;

    public function __construct($apiKey = null)
    {
        $this->apiKey = $apiKey;
        if ($apiKey) {
            $this->dataCenter = substr($apiKey, strpos($apiKey, '-') + 1);
            $this->baseUrl = "https://{$this->dataCenter}.api.mailchimp.com/3.0";
        }
    }

    /**
     * Subscribe a user to a MailChimp list
     */
    public function subscribe($email, $listId, $mergeFields = [])
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'apikey ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->post("{$this->baseUrl}/lists/{$listId}/members", [
                'email_address' => $email,
                'status' => 'subscribed',
                
            ]);

            

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('MailChimp subscribe error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Check if a user is subscribed to a MailChimp list
     */
    public function isSubscribed($email, $listId)
    {
        try {
            $subscriberHash = md5(strtolower($email));
            
            $response = Http::withHeaders([
                'Authorization' => 'apikey ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->get("{$this->baseUrl}/lists/{$listId}/members/{$subscriberHash}");

            if ($response->successful()) {
                $data = $response->json();
                return $data['status'] === 'subscribed';
            }

            return false;
        } catch (\Exception $e) {
            Log::error('MailChimp isSubscribed error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Add tags to a MailChimp subscriber
     */
    public function addTags($email, $listId, $tags)
    {
        try {
            $subscriberHash = md5(strtolower($email));
            
            $tagsData = [];
            foreach ($tags as $tag) {
                $tagsData[] = [
                    'name' => $tag,
                    'status' => 'active'
                ];
            }

            $response = Http::withHeaders([
                'Authorization' => 'apikey ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->post("{$this->baseUrl}/lists/{$listId}/members/{$subscriberHash}/tags", [
                'tags' => $tagsData
            ]);

            

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('MailChimp addTags error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Unsubscribe a user from a MailChimp list
     */
    public function unsubscribe($email, $listId)
    {
        try {
            $subscriberHash = md5(strtolower($email));
            
            $response = Http::withHeaders([
                'Authorization' => 'apikey ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->patch("{$this->baseUrl}/lists/{$listId}/members/{$subscriberHash}", [
                'status' => 'unsubscribed'
            ]);

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('MailChimp unsubscribe error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Delete a user from a MailChimp list
     */
    public function delete($email, $listId)
    {
        try {
            $subscriberHash = md5(strtolower($email));
            
            $response = Http::withHeaders([
                'Authorization' => 'apikey ' . $this->apiKey,
                'Content-Type' => 'application/json'
            ])->delete("{$this->baseUrl}/lists/{$listId}/members/{$subscriberHash}");

            return $response->successful();
        } catch (\Exception $e) {
            Log::error('MailChimp delete error: ' . $e->getMessage());
            return false;
        }
    }
} 