<?php 

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Twilio\Rest\Client;
use Illuminate\Support\Facades\Log;
use App\Models\SmsProductlog;

class SmsController extends Controller
{
    private $shopifyStoreUrl;
    private $shopifyAccessToken;
    private $twilioSid;
    private $twilioAuthToken;
    private $twilioPhoneNumber;

    public function __construct()
    {
        $this->shopifyStoreUrl = env('SHOPIFY_STORE_URL');
        $this->shopifyAccessToken = env('SHOPIFY_ACCESS_TOKEN');
        $this->twilioSid = env('TWILIO_SID');
        $this->twilioAuthToken = env('TWILIO_AUTH_TOKEN');
        $this->twilioPhoneNumber = env('TWILIO_PHONE_NUMBER');
    }

    /**
     * Sends MMS to subscribed customers with jewelry product details.
     */
      public function sendDailyJewelryMessages()
    {
        $customers = $this->getSubscribedCustomers();
        $products = $this->getJewelryProducts();
        $twilio = new Client($this->twilioSid, $this->twilioAuthToken);

        $totalSent = 0;
        $totalFailed = 0;

        foreach ($customers as $customer) {
          // if (!empty($customer['phone']) && $customer['phone'] == '+916266353732') { 
             if (!empty($customer['phone'])) {
                try {
                    $inexpensive = $products['inexpensive'];
                    $expensive = $products['expensive'];

                    // Prepare MMS messages with images if available
                    // if (!empty($inexpensive['image']['src']) && strpos($inexpensive['image']['src'], 'no-image') === false) {
                        $messageInexpensive = "New Jewelry Arrivals! \n\n" .
                            "{$inexpensive['title']}\n" .
                            "Price: $" . $inexpensive['price'] . "\n" .
                            "Buy Now: https://bfriesian.com/products/{$inexpensive['handle']}\n\n";
                        
                        // Send MMS with images
                        $twilio->messages->create(
                         $customer['phone'],
                            [
                                'from' => $this->twilioPhoneNumber,
                                'body' => $messageInexpensive,
                              //  'mediaUrl' => [$inexpensive['image']['src']]
                            ]
                        );
                    // }

                    // if (!empty($expensive['image']['src']) && strpos($expensive['image']['src'], 'no-image') === false) {
                        $messageExpensive = "New Jewelry Arrivals! \n\n" .
                            "{$expensive['title']}\n" .
                            "Price: $" . $expensive['price'] . "\n" .
                            "Buy Now: https://bfriesian.com/products/{$expensive['handle']}\n\n";
                        
                        $twilio->messages->create(
                          $customer['phone'],
                            [
                                'from' => $this->twilioPhoneNumber,
                                'body' => $messageExpensive,
                              //'mediaUrl' => [$expensive['image']['src']]
                            ]
                        );
                    // }

                    $totalSent++;
                    // Optional: Add a delay to avoid hitting rate limits (e.g., 1 second per message)
                    sleep(1);
                } catch (\Exception $e) {
                    Log::error("Twilio SMS Error: " . $e->getMessage());
                    $totalFailed++;
                }
            }
        }

        return response()->json([
            'message' => 'SMS sent successfully!',
            'total_sent' => $totalSent,
            'total_failed' => $totalFailed
        ], 200);
    }


    /**
     * Retrieves all subscribed customers from Shopify.
     */
    private function getSubscribedCustomers()
    {
        $customers = [];
        $url = "https://{$this->shopifyStoreUrl}/admin/api/2023-01/customers.json?fields=email,phone,tags,notes&accepts_marketing=true&limit=250";

        do {
            $response = Http::withHeaders([
                'X-Shopify-Access-Token' => $this->shopifyAccessToken,
            ])->get($url);

            if ($response->failed()) {
                Log::error("Shopify API Error: " . $response->body());
                return [];
            }

            $data = $response->json();
            $customers = array_merge($customers, $data['customers'] ?? []);

            // Get the "next" page URL from the response headers
            $linkHeader = $response->header('Link');
            $url = $this->getNextPageUrl($linkHeader);
        } while ($url); // Continue pagination if more pages exist

        return $customers;
    }

    /**
     * Extracts the "next" page URL from Shopify's Link header.
     */
    private function getNextPageUrl($linkHeader)
    {
        if (!$linkHeader) {
            return null;
        }

        preg_match('/<(.*?)>; rel="next"/', $linkHeader, $matches);
        return $matches[1] ?? null;
    }

    /**
     * Fetches jewelry products from Shopify and selects random inexpensive & expensive ones.
     */
    // private function getJewelryProducts()
    // {
    //     $response = Http::withHeaders([
    //         'X-Shopify-Access-Token' => $this->shopifyAccessToken,
    //     ])->get("https://{$this->shopifyStoreUrl}/admin/api/2023-01/products.json", [
    //         'status' => 'active',
    //     ]);

    //     if ($response->failed()) {
    //         Log::error("Shopify API Error: " . $response->body());
    //         return ['inexpensive' => null, 'expensive' => null];
    //     }

    //     $products = collect($response->json()['products'] ?? [])
    //         ->map(function ($product) {
    //             $product['price'] = isset($product['variants'][0]['price']) ? (float) $product['variants'][0]['price'] : 0;
    //             return $product;
    //         })
    //         ->sortBy('price')
    //         ->values();

    //     // Select random inexpensive and expensive products
    //     return [
    //         'inexpensive' => $products->take((int)ceil($products->count() * 0.2))->random(),
    //         'expensive' => $products->take(-1 * (int)ceil($products->count() * 0.2))->random(),
    //     ];
    // }
    private function getJewelryProducts()
{
    $allProducts = collect(); // Laravel collection
    $endpoint = "https://{$this->shopifyStoreUrl}/admin/api/2023-01/products.json?limit=250";
    $headers = [
        'X-Shopify-Access-Token' => env('SHOPIFY_ACCESS_TOKEN'),
    ];

    do {
        $response = Http::withHeaders($headers)->get($endpoint);

        $products = collect($response->json()['products'] ?? []);
        $allProducts = $allProducts->merge($products);

        // Handle pagination with Link header
        $linkHeader = $response->header('Link');
        $nextPage = null;

        if ($linkHeader && str_contains($linkHeader, 'rel="next"')) {
            preg_match('/<([^>]+)>; rel="next"/', $linkHeader, $matches);
            $nextPage = $matches[1] ?? null;
            $endpoint = $nextPage;
        } else {
            $nextPage = null;
        }
    } while ($nextPage);

    // Clean and filter products
    $cleanedProducts = $allProducts->map(function ($product) {
        $product['price'] = isset($product['variants'][0]['price']) ? (float) $product['variants'][0]['price'] : 0;
        $product['image_src'] = $product['image']['src'] ?? null;
        return $product;
    })->filter(function ($product) {
        return isset($product['image_src']) && !str_contains($product['image_src'], '(no-image)');
    })->sortBy('price')->values();

    // 20% low and high price products
    $inexpensivePool = $cleanedProducts->take((int)ceil($cleanedProducts->count() * 0.2));
    $expensivePool = $cleanedProducts->take(-1 * (int)ceil($cleanedProducts->count() * 0.2));

    // Exclude already used
    $usedInexpensive = SmsProductlog::where('type', 'inexpensive')->pluck('product_id')->toArray();
    $usedExpensive = SmsProductlog::where('type', 'expensive')->pluck('product_id')->toArray();

    $availableInexpensive = $inexpensivePool->reject(function ($product) use ($usedInexpensive) {
        return in_array($product['id'], $usedInexpensive);
    });

    $availableExpensive = $expensivePool->reject(function ($product) use ($usedExpensive) {
        return in_array($product['id'], $usedExpensive);
    });

    $inexpensiveProduct = $availableInexpensive->isNotEmpty() ? $availableInexpensive->random() : null;
    $expensiveProduct = $availableExpensive->isNotEmpty() ? $availableExpensive->random() : null;

    // Save to DB
    if ($inexpensiveProduct) {
        SmsProductlog::firstOrCreate(
            ['product_id' => $inexpensiveProduct['id']],
            ['type' => 'inexpensive', 'sms_status' => 1]
        );
    }

    if ($expensiveProduct) {
        SmsProductlog::firstOrCreate(
            ['product_id' => $expensiveProduct['id']],
            ['type' => 'expensive', 'sms_status' => 1]
        );
    }

    // Return data
    return [
        'inexpensive' => $inexpensiveProduct,
        'expensive' => $expensiveProduct,
    ];
}
}
