<?php

namespace App\Http\Controllers;



use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\View;
use App\Models\Diamond;
use App\Models\UserPage;
use App\Models\Jewelry;


class PageController extends Controller

{
    
    public function createPage(Request $request)
    {
       
     $userId = $request->user_id; 
     $user = User::find($userId);

     $bodyHtml = View::make('diamond-page')->render();
     $bodyHtml2 = View::make('diamond-detalis')->render();
     $bodyHtml4 = View::make('diamond-detalis-one')->render();
    //  $jewelry = Jewelry::all();
    // $bodyHtml3 = View::make('rdi_jewelry', compact('jewelry'))->render();
    // $bodyHtml3 = View::make('fancy-color-diamond')->render();
     
    //  ------------------------
    
        $id = 15;
        $item = Jewelry::findOrFail($id);

        $shapeStockMap = Jewelry::whereNotNull('stock_id')
        ->select('shape', 'stock_id')
        ->get()
        ->groupBy('shape');
        $headStyles = Jewelry::select('head_style', 'stock_id')
        ->distinct()
        ->whereNotNull('head_style')
        ->whereNotNull('stock_id')
        ->get()
        ->groupBy('head_style');

        $shankStyles = Jewelry::select('shank_style', 'stock_id')
        ->distinct()
        ->whereNotNull('shank_style')
        ->whereNotNull('stock_id')
        ->get()
        ->groupBy('shank_style');

        $shankMetals = Jewelry::select('shank_metal', 'stock_id')
        ->distinct()
        ->whereNotNull('shank_metal')
        ->whereNotNull('stock_id')
        ->get()
        ->groupBy('shank_metal');

        $metalHeads = Jewelry::select('metal_head', 'stock_id')
        ->distinct()
        ->whereNotNull('metal_head')
        ->whereNotNull('stock_id')
        ->get()
        ->groupBy('metal_head');

         $ring_Sizes = Jewelry::whereNotNull('stock_id')
            ->pluck('size')
            ->unique()
            ->values()
            ->toArray(); // ✅ gives a clean array like ['3', '3.5', '4', '4.5', ...]
        $bodyHtml3 = View::make('rdi_jewelry', compact('item', 'headStyles', 'shankStyles', 'shankMetals', 'metalHeads','shapeStockMap', 'ring_Sizes'))->render();
        // ------------
          $data = [ 'page' => [
        
                        'title' => 'Diamond Product',
                        'body_html' => $bodyHtml,
                         ]
                 ];
          $data2 = [ 'page' => [
    
                    'title' => 'Diamond Details',
                    'body_html' => $bodyHtml2,
                     ]
             ];
         $data3 = [ 'page' => [
    
                'title' => 'custom 360',
                'body_html' => $bodyHtml3,
                 ]
         ];
         $data4 = [ 'page' => [
    
                'title' => 'Diamond Details One',
                'body_html' => $bodyHtml4,
                 ]
         ];
            $userPage_uid = UserPage::where('user_id', $userId)->first();
          
            if(empty($userPage_uid)){
                 $response = $user->api()->rest('POST', '/admin/api/2024-01/pages.json', $data);
                 $response2 = $user->api()->rest('POST', '/admin/api/2024-01/pages.json',  $data2);
                 $response3 = $user->api()->rest('POST', '/admin/api/2024-01/pages.json',  $data3);
                 $response4 = $user->api()->rest('POST', '/admin/api/2024-01/pages.json',  $data4);
                 // dd($response);
                if($response['body']['container']['page']['id'] && $response2['body']['container']['page']['id'] && $response3['body']['container']['page']['id'] ) {
                  
                    $pageId = $response['body']['container']['page']['id'];
                    $pageId2 = $response2['body']['container']['page']['id'];
                    $pageId3 = $response3['body']['container']['page']['id'];
                    $pageId4 = $response4['body']['container']['page']['id'];
                    UserPage::create([
                        'user_id' => $userId,
                        'page_id' => $pageId,  // Save the Shopify page ID
                        'diamond_Detalis_id' => $pageId2,
                        'fancy_color_diamond_id' => $pageId3,
                        'diamondproduct' => $pageId4
                    ]);
            
                    // Return a success response
                    return response()->json('Page created successfully.');
                } else {
                    return response()->json([
                        'error' => 'Failed to create page.',
                        'details' => $response,
                    ], 400);
                }
               }else{
                   $response = $user->api()->rest('PUT', "/admin/api/2024-01/pages/".$userPage_uid->page_id.".json", $data);
                   $response2 = $user->api()->rest('PUT', "/admin/api/2024-01/pages/".$userPage_uid->diamond_Detalis_id.".json", $data2);
                   $response3 = $user->api()->rest('PUT', "/admin/api/2024-01/pages/".$userPage_uid->fancy_color_diamond_id.".json", $data3);
                   $response4 = $user->api()->rest('PUT', "/admin/api/2024-01/pages/".$userPage_uid->diamondproduct.".json", $data4);
                    return response()->json('Page Update successfully.');
               }     
        
    }
       public function deletePage(Request $request)
    {
        //dd($request);
        $userId = $request->user_id;
        $user = User::find($userId);
    
        // Fetch the user's page data from the database
        $userPage = UserPage::where('user_id', $userId)->first();
    
        // Check if the page data exists for the user
        if ($userPage) {
            // Delete the diamond product page
            $response = $user->api()->rest('DELETE', "/admin/api/2024-01/pages/{$userPage->page_id}.json");
            $response3 = $user->api()->rest('DELETE', "/admin/api/2024-01/pages/{$userPage->fancy_color_diamond_id}.json");
            $response4 = $user->api()->rest('DELETE', "/admin/api/2024-01/pages/{$userPage->diamondproduct}.json");
            // Check for the success of the first page deletion
            if ($response['status'] == 200) {
                // If the diamond details page exists, delete it too
                if ($userPage->diamond_Detalis_id) {
                    $response2 = $user->api()->rest('DELETE', "/admin/api/2024-01/pages/{$userPage->diamond_Detalis_id}.json");
    
                    if ($response2['status'] == 200) {
                        // Optionally, remove the reference in your local database
                        $userPage->delete();
    
                        return response()->json('Pages deleted successfully.');
                    } else {
                        return response()->json([
                            'error' => 'Failed to delete diamond details page.',
                            'details' => $response2,
                        ], 400);
                    }
                } else {
                    return response()->json('Diamond details page does not exist.', 400);
                }
            } else {
                return response()->json([
                    'error' => 'Failed to delete diamond product page.',
                    'details' => $response,
                ], 400);
            }
        } else {
            return response()->json('No pages found for this user.', 404);
        }
    }


   public function getDiamonds()
    {
        // die('hello');
        $diamonds = Diamond::paginate(20);
        // $diamonds = Diamond::all(); // Fetch all diamonds
        // return response()->json($diamonds); // Return data as JSON

        return response()->json($diamonds)
        ->header('Access-Control-Allow-Origin', '*') // Allow any origin
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Authorization, Origin');
    }

}



