<?php
defined('BASEPATH') OR exit('No direct script access allowed');

use GuzzleHttp\Client;

class Samaya_products_Video_upload extends CI_Controller {

    private $client;

    public function __construct() {
        parent::__construct();

        // Initialize Guzzle client with Shopify API settings
        $this->client = new Client([
            'base_uri' => 'https://samayajewelry.myshopify.com/',
            'headers' => [
                'X-Shopify-Access-Token' => SHOP_TOKEN,
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ],
            'http_errors' => false // handle errors manually
        ]);
    }

    public function processUploadVideo() {
        // Select products that have not uploaded videos yet
        $products = $this->db->query("SELECT product_id, json_video FROM sh_product WHERE is_video_upload = 0 LIMIT 5")->result();

        foreach ($products as $product) {
            $product_id = $product->product_id;
            $videos = json_decode($product->json_video, true);

            if (empty($videos)) {
                echo "No videos found for product $product_id, skipping.\n";
                continue;
            }

            foreach ($videos as $video) {
                $payload = [
                    'media' => [
                        'media_type' => 'video',
                        'video' => ['url' => $video['src']],
                        'alt' => $video['name'] ?? ''
                    ]
                ];

                try {
                    $response = $this->client->post("admin/api/2025-01/products/{$product_id}/media.json", [
                        'json' => $payload
                    ]);

                    $statusCode = $response->getStatusCode();
                    $body = json_decode($response->getBody(), true);

                    if ($statusCode >= 200 && $statusCode < 300) {
                        echo "Video uploaded for product $product_id: " . ($video['name'] ?? '') . "\n";

                        // Mark this product as uploaded for videos
                        $this->db->update('sh_product', ['is_video_upload' => 1], ['product_id' => $product_id]);

                    } else {
                        echo "Failed to upload video for product $product_id. Status: $statusCode\n";
                        echo "Response: " . json_encode($body) . "\n";

                        // Optionally log the error in your error_log table
                        $this->db->insert('error_log', [
                            'request' => json_encode($payload),
                            'response' => json_encode($body),
                            'method' => 'POST',
                            'endpoint' => "products/{$product_id}/media.json",
                            'added_at' => date('Y-m-d H:i:s')
                        ]);
                    }
                } catch (Exception $e) {
                    echo "Exception uploading video for product $product_id: " . $e->getMessage() . "\n";

                    // Log exception too
                    $this->db->insert('error_log', [
                        'request' => json_encode($payload),
                        'response' => $e->getMessage(),
                        'method' => 'POST',
                        'endpoint' => "products/{$product_id}/media.json",
                        'added_at' => date('Y-m-d H:i:s')
                    ]);
                }
            }
        }

        echo "Video upload process completed.\n";
    }
}
