<?php



namespace App\Http\Controllers;



use Illuminate\Http\Request;

use App\Models\SamayajewelryDiamond;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;


class ProductImportController extends Controller

{
       // sir

     // Get Shape
     public function getshape($shapename)
     {
         $shape_value = '';
 
         // Get shapes from the database
         $shapes = DB::select('SELECT * FROM tbl_shape_master WHERE status = 1');
 
         foreach ($shapes as $shape) {
             if (strtoupper($shape->name) == strtoupper($shapename)) {
                 $shape_value = $shape->name;
             } else {
                 $shape_arr = explode(',', $shape->ALIAS ?? '');
                 foreach ($shape_arr as $shapedata) {
                     if (strtoupper($shapedata) == strtoupper($shapename)) {
                         $shape_value = $shape->name;
                     }
                 }
             }
         }
 
         return $shape_value;
     }
 
     // Get Color
     public function getcolor($colorname)
     {
         $color_value = '';
 
         // Get colors from the database
         $colors = DB::select('SELECT * FROM tbl_color_master WHERE status = 1');
 
         foreach ($colors as $color) {
             if (strtoupper($color->name) == strtoupper($colorname)) {
                 $color_value = $color->name;
             } else {
                 $color_arr = explode(',', $color->ALIAS ?? '');
                 foreach ($color_arr as $colordata) {
                     if (strtoupper($colordata) == strtoupper($colorname)) {
                         $color_value = $color->name;
                     }
                 }
             }
         }
 
         return $color_value;
     }
 
     // Get Clarity
     public function getclarity($clarityname)
     {
         $clarity_value = '';
 
         // Get clarity from the database
         $clarities = DB::select('SELECT * FROM tbl_clarity_master WHERE status = 1');
 
         foreach ($clarities as $clarity) {
             if (strtoupper($clarity->name) == strtoupper($clarityname)) {
                 $clarity_value = $clarity->name;
             } else {
                 $clarity_arr = explode(',', $clarity->ALIAS ?? '');
                 foreach ($clarity_arr as $claritydata) {
                     if (strtoupper($claritydata) == strtoupper($clarityname)) {
                         $clarity_value = $clarity->name;
                     }
                 }
             }
         }
 
         // Specific clarity conditions
         if ($clarityname == 'NW-7') {
             $clarity_value = 'SI3';
         } elseif (in_array($clarityname, ['NW-8', 'NW-8A', 'NW-8B', 'I1'])) {
             $clarity_value = 'I1';
         } elseif (in_array($clarityname, ['NL-9', 'NL-9A', 'NL-9B'])) {
             $clarity_value = 'I2';
         } elseif (in_array($clarityname, ['N1-10', 'N1-10A', 'N-10B', 'N2-11', 'N3-12'])) {
             $clarity_value = 'I3';
         }
 
         return $clarity_value;
     }
 
     // Get Cut
     public function getcut($cutname)
     {
         $cut_value = '';
 
         // Get cuts from the database
         $cuts = DB::select('SELECT * FROM tbl_cut_master WHERE status = 1');
 
         foreach ($cuts as $cut) {
             if (strtoupper($cut->name) == strtoupper($cutname)) {
                 $cut_value = $cut->name;
             } else {
                 $cut_arr = explode(',', $cut->ALIAS ?? '');
                 foreach ($cut_arr as $cutdata) {
                     if (strtoupper($cutdata) == strtoupper($cutname)) {
                         $cut_value = $cut->name;
                     }
                 }
             }
         }
 
         return $cut_value;
     }
 
     // Get Polish
     public function getpolish($polishname)
     {
         $polish_value = '';
 
         // Get polish from the database
         $polishes = DB::select('SELECT * FROM tbl_polish_master WHERE status = 1');
 
         foreach ($polishes as $polish) {
             if (strtoupper($polish->name) == strtoupper($polishname)) {
                 $polish_value = $polish->name;
             } else {
                 $polish_arr = explode(',', $polish->alias ?? '');
                 foreach ($polish_arr as $polishdata) {
                     if (strtoupper($polishdata) == strtoupper($polishname)) {
                         $polish_value = $polish->name;
                     }
                 }
             }
         }
 
         return $polish_value;
     }
 
     // Get Symmetry
     public function getsymmetry($symmetryname)
     {
         $symmetry_value = '';
 
         // Get symmetry from the database
         $symmetries = DB::select('SELECT * FROM tbl_symmetry_master WHERE status = 1');
 
         foreach ($symmetries as $symmetry) {
             if (strtoupper($symmetry->name) == strtoupper($symmetryname)) {
                 $symmetry_value = $symmetry->name;
             } else {
                 $symmetry_arr = explode(',', $symmetry->alias ?? '');
                 foreach ($symmetry_arr as $symmetrydata) {
                     if (strtoupper($symmetrydata) == strtoupper($symmetryname)) {
                         $symmetry_value = $symmetry->name;
                     }
                 }
             }
         }
 
         return $symmetry_value;
     }
 
     // Check Image Link
     public function checkImagelink($url)
     {
         if (!empty($url)) {
             return $url;
         }
         return str_replace("admin/", "", base_url() . 'assets/no_image.jpg');
     }
 
     // Check Diamond Type
     public function checkDiamondtype($data)
     {
         $diamond_type_value = 1;
 
         if (!empty($data)) {
             if (($data == 'Cert Earth Mined') || ($data == 'Non-Cert Earth Mined')) {
                 $diamond_type_value = 1;
             } elseif (($data == 'Cert Lab Grown') || ($data == 'Non-Cert Lab Grown')) {
                 $diamond_type_value = 2;
             }
         }
 
         return $diamond_type_value;
     }
 
     // Check Availability
     public function checkavailability($data)
     {
         if (!empty($data) && $data > 0) {
             return 'A';
         }
         return 'M';
     }
 
     // Check Interchange Type
     public function checkinterchangetype($data)
     {
         $interchangetype_value = '';
 
         if (!empty($data)) {
             $datarr = explode(' ', $data ?? '');
             foreach ($datarr as $res) {
                 if ($res == 'MP') {
                     $interchangetype_value = 1;
                 } elseif ($res == 'PR-MP') {
                     $interchangetype_value = 1;
                 }
             }
         }
 
         return $interchangetype_value;
     }
 
     // Check Video Link
     public function checkVideoLink($url)
     {
         return !empty($url) ? $url : '';
     }
     public function priceCalculate($price1, $weight)
    { 
        $increasedPrice = $price1 * 1.2; 
        $finalPrice = $increasedPrice * $weight; 

        return $finalPrice; 
    }
 
     // Get Culet
    //  public function getculet($culetname)
    //  {
    //      $culet_value = '';
 
    //      // Get culet from the database
    //      $culets = DB::select('SELECT * FROM tbl_culet_master WHERE status = 1');
 
    //      foreach ($culets as $culet) {
    //          if (strtoupper($culet->name) == strtoupper($culetname)) {
    //              $culet_value = $culet->name;
    //          } else {
    //              $culet_arr = explode(',', $culet->alias ?? '');
    //              foreach ($culet_arr as $culetdata) {
    //                  if (strtoupper($culetdata) == strtoupper($culetname)) {
    //                      $culet_value = $culet->name;
    //                  }
    //              }
    //          }
    //      }
 
    //      return $culet_value;
    //  }

    // Method to fetch data from the API and insert into the database

    public function importDiamonds()
    {
        // Step 1: Get session ID by calling the first API
        $sessionResponse = Http::withHeaders([
            'serial' => 'f6fb30',
            'apikey' => 'pf5osdkFe54gsd5rFD524ds4327',
            'apipassword' => '64fF54441fds8dsds84dFGOeoir8',
            'Content-Type' => 'application/json',
        ])->get('https://gate.rightclick.software/');
    
        // Check if session ID is retrieved successfully
        if ($sessionResponse->failed()) {
            return response()->json(['error' => 'Failed to retrieve session ID'], 500);
        }
    
        $sessionId = $sessionResponse->json()['SessionId'];
    
        // Step 2: Use the session ID to fetch the diamonds data
        $dataResponse = Http::withHeaders([
            'sessionid' => $sessionId,
            'api' => 'Cert',
            'Content-Type' => 'application/json',
            'startdate' => '2000-01-01',
        ])->get('https://gate.rightclick.software/');
    
        // Check if data was retrieved successfully
        if ($dataResponse->failed()) {
            return response()->json(['error' => 'Failed to retrieve data'], 500);
        }
    
        $certificates = $dataResponse->json()['certs'];
    
        // Step 3: Insert each certificate into the database
        foreach ($certificates as $certificate) {
            if ($certificate['onhandweight'] > 0  || $certificate['memooutweight'] > 0 ){
                
            }
            // Transform shape, color, clarity, cut, polish, culet, certification, and type 
            $shape = $this->getshape($certificate['shapecode']);
            $color = $this->getcolor($certificate['colorcode']);
            $clarity = $this->getclarity($certificate['claritycode']);
            $cut = $this->getcut($certificate['cutgrade']);
            $polish = $this->getpolish($certificate['polish']);
            $diamondType = $this->checkDiamondtype($certificate);
            $weight_pr = $certificate['weight'] ?? null;
            $price1_pr = $certificate['price1'] ?? null;
            // $culet = $this->getculet($certificate['culet']);
          if ($certificate['onhandweight'] > 0 || $certificate['memooutweight'] > 0) {   
            // Insert the data into the database
            SamayajewelryDiamond::create([
                'id' => $certificate['id'] ?? null,
                'code' => $certificate['code'] ?? null,
                'setcode' => $certificate['setcode'] ?? null,
                'certificate_no' => $certificate['certificate_no'] ?? null,
                'certificate_date' => $certificate['certificate_date'] ?? null,
                'companycode' => $certificate['companycode'] ?? null,
                'inventorylocationcode' => $certificate['inventorylocationcode'] ?? null,
                'description' => $certificate['description'] ?? null,
                'shapecode' => $shape,  // Transformed shape value
                'colorcode' => $color,  // Transformed color value
                'claritycode' => $clarity,  // Transformed clarity value
                'cutgrade' => $cut,  // Transformed cut value
                'polish' => $polish,  // Transformed polish value
                'culet' => $certificate['culet'] ?? null,
                'is_certified' => $certificate['certificate_no'] ?? null,
                'diamond_type' => $diamondType,  // Transformed diamond type
                'weight' => $certificate['weight'] ?? null,
                'labcode' => $certificate['labcode'] ?? null,
                'sizecode' => $certificate['sizecode'] ?? null,
                'lwd' => $certificate['lwd'] ?? null,
                'length' => $certificate['length'] ?? null,
                'width' => $certificate['width'] ?? null,
                'depth' => $certificate['depth'] ?? null,
                'depth_pct1' => $certificate['depth_pct1'] ?? null,
                'table_pct' => $certificate['table_pct'] ?? null,
                'girdle' => $certificate['girdle'] ?? null,
                'girdle_condition' => $certificate['girdle_condition'] ?? null,
                'girdle_pct' => $certificate['girdle_pct'] ?? null,
                'facet' => $certificate['facet'] ?? null,
                'symmetry' => $certificate['symmetry'] ?? null,
                'fluorescence' => $certificate['fluorescence'] ?? null,
                'fluorescence_color' => $certificate['fluorescence_color'] ?? null,
                'carbon' => $certificate['carbon'] ?? null,
                'crown_angle' => $certificate['crown_angle'] ?? null,
                'crown_height' => $certificate['crown_height'] ?? null,
                'pavilion_angle' => $certificate['pavilion_angle'] ?? null,
                'pavilion_depth' => $certificate['pavilion_depth'] ?? null,
                'star_length' => $certificate['star_length'] ?? null,
                'lower_half' => $certificate['lower_half'] ?? null,
                'painting' => $certificate['painting'] ?? null,
                'proportion' => $certificate['proportion'] ?? null,
                'synthetic' => $certificate['synthetic'] ?? null,
                'inscription' => $certificate['inscription'] ?? null,
                'fancy_color' => $certificate['fancy_color'] ?? null,
                'fancy_color_intensity' => $certificate['fancy_color_intensity'] ?? null,
                'fancy_color_overtone' => $certificate['fancy_color_overtone'] ?? null,
                'shade' => $certificate['shade'] ?? null,
                'eyeclean' => $certificate['eyeclean'] ?? null,
                'bgm' => $certificate['bgm'] ?? null,
                'center_inclusion' => $certificate['center_inclusion'] ?? null,
                'black_inclusion' => $certificate['black_inclusion'] ?? null,
                'hpht' => $certificate['hpht'] ?? null,
                'irradiated' => $certificate['irradiated'] ?? null,
                'laser_drilled' => $certificate['laser_drilled'] ?? null,
                'cost' => $certificate['cost'] ?? null,
                'rapprice' => $certificate['rapprice'] ?? null,
                'markup1' => $certificate['markup1'] ?? null,
                'price1' => $this->priceCalculate($price1_pr, $weight_pr),  // $certificate['price1'] ?? null,
                'simplexdiam_price1' => $certificate['price1'] ?? null,
                'markup2' => $certificate['markup2'] ?? null,
                'price2' => $certificate['price2'] ?? null,
                'markup3' => $certificate['markup3'] ?? null,
                'price3' => $certificate['price3'] ?? null,
                'origin' => $certificate['origin'] ?? null,
                'brand' => $certificate['brand'] ?? null,
                'sarine' => $certificate['sarine'] ?? null,
                'sarine_link' => $certificate['sarine_link'] ?? null,
                'certificate_notes' => $certificate['certificate_notes'] ?? null,
                'other_notes' => $certificate['other_notes'] ?? null,
                'type' => $certificate['type'] ?? null,
                'category' => $certificate['category'] ?? null,
                'salespersoncode' => $certificate['salespersoncode'] ?? null,
                'vendoritem' => $certificate['vendoritem'] ?? null,
                'vendorname' => $certificate['vendorname'] ?? null,
                'startdate' => $certificate['startdate'] ?? null,
                'website' => $certificate['website'] ?? null,
                'video_link' => $certificate['video_link'] ?? null,
                'threed_link' => $certificate['threed_link'] ?? null,
                'notes' => $certificate['notes'] ?? null,
                'onhandweight' => $certificate['onhandweight'] ?? null,
                'ownedweight' => $certificate['ownedweight'] ?? null,
                'historyweight' => $certificate['historyweight'] ?? null,
                'holdweight' => $certificate['holdweight'] ?? null,
                'holdinfo' => $certificate['holdinfo'] ?? null,
                'memooutweight' => $certificate['memooutweight'] ?? null,
                'memooutinfo' => $certificate['memooutinfo'] ?? null,
                'memoinweight' => $certificate['memoinweight'] ?? null,
                'orderweight' => $certificate['orderweight'] ?? null,
                'backorderedweight' => $certificate['backorderedweight'] ?? null,
                'poweight' => $certificate['poweight'] ?? null,
                'injobsweight' => $certificate['injobsweight'] ?? null,
            ]);
        }

       }
    
        return response()->json(['success' => 'Diamonds data successfully inserted']);
    }
    


  

}

//onhandweight 	memooutweight