<?php

namespace Osiset\ShopifyApp\Messaging\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Osiset\ShopifyApp\Actions\CancelCurrentPlan;
use Osiset\ShopifyApp\Contracts\Commands\Shop as IShopCommand;
use Osiset\ShopifyApp\Contracts\Queries\Shop as IShopQuery;
use Osiset\ShopifyApp\Objects\Values\ShopDomain;
use Osiset\ShopifyApp\Util;
use stdClass;
use App\Models\UserPage;  
/**
 * Webhook job responsible for handling when the app is uninstalled.
 */
class AppUninstalledJob implements ShouldQueue
{ 
    
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * The shop domain.
     *
     * @var ShopDomain|string
     */
    protected $domain;

    /**
     * The webhook data.
     *
     * @var object
     */
    protected $data;

    /**
     * Create a new job instance.
     *
     * @param string   $domain The shop domain.
     * @param stdClass $data   The webhook data (JSON decoded).
     *
     * @return void
     */
    public function __construct(string $domain, stdClass $data)
    {

        $this->domain = $domain;
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @param IShopCommand      $shopCommand             The commands for shops.
     * @param IShopQuery        $shopQuery               The querier for shops.
     * @param CancelCurrentPlan $cancelCurrentPlanAction The action for cancelling the current plan.
     *
     * @return bool
     */
    public function handle(
        IShopCommand $shopCommand,
        IShopQuery $shopQuery,
        CancelCurrentPlan $cancelCurrentPlanAction
    ): bool {
      
        \Log::info('AppUninstalledJob2');
       // die(11);
        // Convert the domain
        $this->domain = ShopDomain::fromNative($this->domain);

        // Get the shop
        $shop = $shopQuery->getByDomain($this->domain);
        $shopId = $shop->getId();

        // Cancel the current plan
        $cancelCurrentPlanAction($shopId);

        // Purge shop of token, plan, etc.
        $shopCommand->clean($shopId);

        // Check freemium mode
        $freemium = Util::getShopifyConfig('billing_freemium_enabled');
        if ($freemium === true) {
            // Add the freemium flag to the shop
            $shopCommand->setAsFreemium($shopId);
        }

        // Soft delete the shop.
        $shopCommand->softDelete($shopId);
          \Log::info('user_id:'.$shopId);
        // 1. Delete UserPage records associated with the shop
         $this->deletePages($shopId);
        
        return true;
    }

    /**
     * Delete UserPage records associated with the given shopId.
     *
     * @param int $shopId
     * @return void
     */
     protected function deletePages(int $shopId): void
    {
        // Fetch the UserPage associated with the shopId
        $userPage = UserPage::where('user_id', $shopId)->first();

        // Check if the user has associated pages
        if ($userPage) {
            // Delete the diamond product page
            $response = $this->deleteShopifyPage($shopId, $userPage->page_id);

            // If the diamond product page was deleted, delete the diamond details page
            if ($response['status'] == 200) {
                if ($userPage->diamond_Detalis_id) {
                    $response2 = $this->deleteShopifyPage($shopId, $userPage->diamond_Detalis_id);

                    if ($response2['status'] == 200) {
                        // Successfully deleted both pages, remove UserPage entry
                        $userPage->delete();
                        \Log::info('UserPage records deleted for shopId: ' . $shopId);
                    } else {
                        \Log::error('Failed to delete diamond details page. Response: ' . json_encode($response2));
                    }
                }
            } else {
                \Log::error('Failed to delete diamond product page. Response: ' . json_encode($response));
            }
        } else {
            \Log::info('No UserPage found for shopId: ' . $shopId);
        }
    }

    /**
     * Helper method to delete a page on Shopify.
     *
     * @param int    $shopId     The shop ID
     * @param string $pageId     The page ID to delete
     * @return array             The response from Shopify API
     */
    protected function deleteShopifyPage(int $shopId, string $pageId): array
    {
        // Get the user object to make Shopify API requests
        $user = User::find($shopId);
        
        // Make the API request to delete the page
        $response = $user->api()->rest('DELETE', "/admin/api/2024-01/pages/{$pageId}.json");

        return $response;
    }
}
