Advertisement
Guest User

search controller

a guest
Aug 23rd, 2018
410
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 336.50 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Thanatos\Modules\Search\Http\Controllers;
  4.  
  5. use Illuminate\Http\Request;
  6.  
  7. use Illuminate\Support\Facades\Auth;
  8. use Illuminate\Support\Facades\Cookie;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\URL;
  11. use Session;
  12. use Thanatos\Http\Controllers\Controller;
  13. use LaravelLocalization;
  14. use Thanatos\Modules\Insurance\Http\Controllers\AdditionalController;
  15. use Thanatos\Modules\Insurance\Http\Controllers\FeatureController;
  16. use Thanatos\Modules\Insurance\Http\Controllers\RateController;
  17. use Thanatos\Modules\Insurance\Models\Insurance_Features_Additional_Prices;
  18. use Thanatos\Modules\Insurance\Models\Insurance_Product;
  19. use Thanatos\Modules\Insurance\Models\Insurance_Product_Detail;
  20. use Thanatos\Modules\Insurance\Models\Insurance_Product_Meta;
  21. use Thanatos\Modules\Insurance\Models\Insurance_Product_View;
  22. use Thanatos\Modules\Insurance\Models\Insurance_Provider;
  23. use Thanatos\Modules\Insurance\Models\Insurance_Provider_Detail;
  24. use Thanatos\Modules\Insurance\Models\InsuranceProductReview;
  25. use Thanatos\Modules\Insurance\Models\InsuranceProductPartner;
  26. use Thanatos\Modules\Insurance\Models\Zone_Territory_Car;
  27. use Thanatos\Modules\Insurance\Models\Zone_Territory_Earthquake;
  28. use Thanatos\Modules\Insurance\Models\Zone_Territory_Motorcycle;
  29. use Thanatos\Modules\Search\Models\Search_Record;
  30. use Thanatos\User;
  31. use App;
  32. use Carbon\Carbon;
  33.  
  34. class SearchController extends Controller
  35. {
  36.     public function __construct()
  37.     {
  38.         DB::enableQueryLog();
  39.     }
  40.  
  41.     public function generateCompareHistory()
  42.     {
  43.  
  44.     }
  45.  
  46.     public function getCompareQuery(Request $request){
  47.         if ($request->has('compare')) {
  48.             $in = '';
  49.             $request = $request->all();
  50.             $type = $request['type'];
  51.             $compare = json_decode($request['compare'], true);
  52.  
  53.             $sql = 'SELECT product.*, features.*, ib.*, product_detail.*, product_meta.*, iprov.provider_name, iprov.provider_slug FROM insurance_product ip ';
  54.             $sql .= 'LEFT JOIN (SELECT id, name as provider_name, slug as provider_slug FROM insurance_provider) iprov ON iprov.id = product.provider_id ';
  55.             $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) ipd ON product_detail.product_id = product.id ';
  56.             $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) ipm ON product_meta.product_id = product.id ';
  57.  
  58.             switch ($type) {
  59.                 case 'property':
  60.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_property) ifeat ON ifeat.product_id = product.id ';
  61.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_benefit_property) ib ON ib.product_id = product.id ';
  62.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_features_additional_prices) ifap ON ifap.product_id = product.id';
  63.                     $sql .= 'WHERE ';
  64.  
  65.                     foreach ($compare as $key => $value) {
  66.                         $in .= '"' . $value . '"';
  67.                         if ($key < count($compare) - 1) {
  68.                             $in .= ',';
  69.                         }
  70.                     }
  71.                     $sql .= 'product.slug IN (' . $in . ') AND product.type = "' . $type . '"';
  72.                     break;
  73.                 case 'car':
  74.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_car) ifeat ON features.product_id = product.id ';
  75.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_benefit_car) ib ON ib.product_id = product.id ';
  76.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_features_additional_prices) ifap ON ifap.product_id = product.id';
  77.                     $sql .= 'WHERE ';
  78.  
  79.                     foreach ($compare as $key => $value) {
  80.                         $in .= '"' . $value . '"';
  81.                         if ($key < count($compare) - 1) {
  82.                             $in .= ',';
  83.                         }
  84.                     }
  85.                     $sql .= 'product.slug IN (' . $in . ') AND product.type = "' . $type . '"';
  86.                     break;
  87.                 case 'motorcycle':
  88.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_motorcycle) ifeat ON features.product_id = product.id ';
  89.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_benefit_motorcycle) ib ON ib.product_id = product.id ';
  90.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_features_additional_prices) ifap ON ifap.product_id = product.id';
  91.                     $sql .= 'WHERE ';
  92.  
  93.                     foreach ($compare as $key => $value) {
  94.                         $in .= '"' . $value . '"';
  95.                         if ($key < count($compare) - 1) {
  96.                             $in .= ',';
  97.                         }
  98.                     }
  99.                     $sql .= 'product.slug IN (' . $in . ') AND product.type = "' . $type . '"';
  100.                     break;
  101.             }
  102.  
  103.             $sql .= 'GROUP BY product.name ';
  104.             $database = DB::select($sql);
  105.             if (count($database) > 1) {
  106.                 $previous = json_decode(file_get_contents(app_path('DatabaseJSON/compare.json')), true);
  107.                 $dumped = $previous;
  108.                 $comparer = array('on' => date('Y-m-d H:i:s'), 'between' => $database);
  109.                 $email = 'kzulfazriawan@gmail.com';
  110.  
  111.                 if (count($previous) > 0) {
  112.                     foreach ($previous as $k => $v) {
  113.                         if ($k == $email) {
  114.                             array_push($dumped[$k], $comparer);
  115.                         } else {
  116.                             $dumped[$k] = array($comparer);
  117.                         }
  118.                     }
  119.                 } else {
  120.                     $dumped[$email] = array($comparer);
  121.                 }
  122.                 $product = json_encode($dumped);
  123.                 file_put_contents(app_path('DatabaseJSON/compare.json'), $product);
  124.  
  125.                 return $database;
  126.             }
  127.  
  128.             return [];
  129.         }
  130.     }
  131.  
  132.     public function snapshotIt(Request $request)
  133.     {
  134.         // clean the array first before processing
  135.         $clone_data = $request->data;
  136.         if (is_array($clone_data)) {
  137.             foreach ($clone_data as $k => $v) {
  138.                 foreach ($v as $kEy => $vAl) {
  139.                     if (strpos($kEy, '@') !== false || strpos($kEy, '(') !== false) {
  140.                         unset($clone_data[$k][$kEy]);
  141.                     }
  142.                 }
  143.             }
  144.         }
  145.         $request->data = $clone_data;
  146.         if (Auth::check()) {
  147.             $user = Auth::user()->id;
  148.         } else {
  149.             $user = 0;
  150.         }
  151.  
  152.         /* yang gua butuhin itu
  153.          * - bypass, name,
  154.          *
  155.          */
  156.  
  157.  
  158.  
  159.  
  160. //      if(!file_exists(app_path('DatabaseJSON/searches-of-'.$user.'.json'))){
  161. //          fopen(app_path('DatabaseJSON/searches-of-'.$user.'.json'), 'w');
  162. //      }
  163.  
  164.         if (count($request->data) > 1 and !is_null($user)) {
  165.             $dumped = array();
  166. //          $previous = json_decode(file_get_contents(app_path('DatabaseJSON/searches-of-'.$user.'.json')), true);
  167. //          $dumped   = $previous;
  168.  
  169. //          if(count($previous) > 0) {
  170. //              foreach ($previous as $k => $v) {
  171. //                  $dumped[date('Y-m-d H:i:s')] = $request->data;
  172. //              }
  173. //          } else {
  174.             $id = generateSS();
  175.             $tmp = $request->data;
  176.             foreach($request->data as $key => $data) {
  177.                 if(isset($tmp[$key]['brief_id'])) {
  178.                     unset($tmp[$key]['brief_id']);
  179.                 }
  180.                 if(isset($tmp[$key]['brief_en'])){
  181.                     unset($tmp[$key]['brief_en']);
  182.                 }
  183.  
  184.                 unset($tmp[$key]['affiliate_url']);
  185.                 unset($tmp[$key]['promo_url']);
  186.                 unset($tmp[$key]['promo']);
  187.                 unset($tmp[$key]['partner']);
  188.                 unset($tmp[$key]['features']);
  189.                 unset($tmp[$key]['is_active']);
  190.                 unset($tmp[$key]['last_login']);
  191.             }
  192.             $request->data = $tmp;
  193.  
  194.             $dumped = $request->data;
  195. //          }
  196.  
  197. //          $product  = json_encode($dumped);
  198.  
  199.             $search_record = new Search_Record;
  200.             if(isset($search_record->datas)){
  201.                 unset($search_record->datas);
  202.             }
  203.             $search_record->id = $id;
  204.             $search_record->user_id = $user;
  205.             $search_record->datas = $dumped;
  206.             $search_record->type = $request->data[0]['type'];
  207.             $search_record->bypass = $request->data[0]['bypass'];
  208.             $search_record->questionnaire = $request->data[0]['questionnaire'];
  209.  
  210.             // remove quesetionnaire array in every request->data
  211.             foreach($request->data as $index => $none){
  212.                 unset($request->data[$index]['questionnaire']);
  213.             }
  214.  
  215.             if ($search_record->save()) {
  216.                 return 'oke';
  217.             } else {
  218.                 return 'oce';
  219.             }
  220.         }
  221.     }
  222.  
  223.     /**
  224.      * @param \Illuminate\Http\Request                                          $request
  225.      * @param null                                                              $exclude
  226.      * @param \Thanatos\Modules\Insurance\Http\Controllers\FeatureController    $featureController
  227.      * @param \Thanatos\Modules\Insurance\Http\Controllers\AdditionalController $additionalController
  228.      * @param \Thanatos\Modules\Insurance\Http\Controllers\RateController       $rateController
  229.      *
  230.      * @return array
  231.      */
  232.     public function getSearchQuery(Request $request, $exclude = null, FeatureController $featureController, AdditionalController $additionalController, RateController $rateController)
  233.     {
  234.         if ($request->has('type') and $request->has('query')) {
  235.             App::setLocale($request->language);
  236.             $request              = $request->all();
  237.             $absolute             = ' ';
  238.             $counter              = 0;
  239.             $type                 = $request['type'];
  240.             $factor               = $request['factor'];
  241.             $query                = json_decode($request['query'], true);
  242.             $setcook              = $query;
  243.             $requests_additional  = [];
  244.             $amount_features      = '';
  245.             $percentages_features = '';
  246.  
  247.             // START BEGIN THE MOST COMPLICATED QUERY EVER !!!
  248.             $sql = 'SELECT product.*,
  249.                                product_detail.*,
  250.                                product_meta.*,
  251.                                features.*,
  252.                                features.count as count,
  253.                                coverages.*,
  254.                                questionnaires.*,
  255.                                additional_coverages.*,
  256.                                zone_territory.*, ';
  257.             /**
  258.              * ini buat nge-get features berdasarkan keys tertentu, dan juga tipe tertentu yang nantinya akan masuk ke perhitungan data.
  259.              * kaya perhitungan value dan juga perhitungan premi, yang nantinya diakumulasi kembali.
  260.              * PLEASE BE CAREFUL !!
  261.              */
  262.  
  263.             if (isset($request['feature'])) {
  264.                 $request_features       = json_decode($request['feature'], true);
  265.                 $count_request_features = count($request_features);
  266.  
  267.                 if (!empty($request_features) and $count_request_features > 0) {
  268.                     $setcook['feature']     = $request_features;
  269.                     $setcook['additionals'] = $requests_additional;
  270.                     $absolute               = 'AND ';
  271.                     $in                     = '';
  272.  
  273.                     foreach ($request_features as $keys => $vals) {
  274.                         // special condition for some
  275.                         switch($vals){
  276.                             case 'pre_existing_condition':
  277.                                 $vals = 'pre-existing_condition';
  278.                                 break;
  279.                             case 'post_travel_medical_expenses':
  280.                                 $vals = 'post-travel_medical_expenses';
  281.                                 break;
  282.                         }
  283.                         $in       .= ' \'' . $vals . '\' ';
  284.                         $absolute .= 'features.' . '`'.$vals.'`' . ' IS NOT NULL ';
  285.                         if ($keys < $count_request_features - 1) {
  286.                             $in       .= ',';
  287.                             $absolute .= 'AND ';
  288.                         }
  289.                     }
  290.  
  291.                     // get amount price yang diakumulasi untuk perhitungan premi langsung.
  292.                     // -------------------------------------------------------------------
  293.                     $amount_features .= '(CASE WHEN EXISTS(SELECT NULL FROM insurance_features_additional_prices WHERE type=\'amount\' AND insurance_features_additional_prices.key IN (' . $in . ') AND product_id=product.id) ';
  294.                     $amount_features .= 'THEN @amount_price:=(SELECT SUM(`value`) FROM insurance_features_additional_prices WHERE type=\'amount\' AND (insurance_features_additional_prices.key IN (' . $in . ') AND product_id=product.id)) ';
  295.                     $amount_features .= 'ELSE @amount_price:=NULL ';
  296.                     $amount_features .= 'END), ';
  297.  
  298.                     // get percentages prices yang diakumulasi untuk perhitungan value assets dari barang yang diasuransikan.
  299.                     // -------------------------------------------------------------------
  300.                     $percentages_features .= '(CASE WHEN EXISTS(SELECT NULL FROM insurance_features_additional_prices WHERE type=\'percentages\' AND insurance_features_additional_prices.key IN (' . $in . ') AND product_id=product.id) ';
  301.                     $percentages_features .= 'THEN @percentages_price:=(SELECT SUM(`value`) FROM insurance_features_additional_prices WHERE type=\'percentages\' AND (insurance_features_additional_prices.key IN (' . $in . ') AND product_id=product.id)) ';
  302.                     $percentages_features .= 'ELSE @percentages_price:=NULL ';
  303.                     $percentages_features .= 'END), ';
  304.                 }
  305.             }
  306.  
  307.             // buat biaya tambahan
  308.             $additional_fee_admin = '@admin_fee:=(CASE WHEN questionnaires.admin_fee < 100
  309.                                             THEN (@premi/100)*questionnaires.admin_fee
  310.                                         ELSE questionnaires.admin_fee END), ';
  311.             $additional_fee_admin.= '@admin_fee:=IF(@admin_fee=NULL, 0, @admin_fee), ';
  312.  
  313.             $additional_fee_materai = '@materai_fee:=(CASE WHEN questionnaires.materai_fee < 100
  314.                                             THEN (@premi/100)*questionnaires.materai_fee
  315.                                         ELSE questionnaires.materai_fee END), ';
  316.             $additional_fee_materai.= '@materai_fee:=IF(@materai_fee=NULL, 0, @materai_fee), ';
  317.  
  318.             switch ($type) {
  319.                 case 'car':
  320.                     /**
  321.                      * bikin variable khususnya terlebih dahulu,
  322.                      */
  323.                     $gap_age = date('Y') - (integer)$query['car_year'];
  324.                     $flood = '';
  325.                     $earthquake = '';
  326.                     $liability = '';
  327.                     $sort = [1 => 'one', 2 => 'two', 3 => 'three'];
  328.  
  329.                     if ($query['level_of_insurance'] == 'comprehensive') {
  330.                         $additioning = $additionalController->comprehensive;
  331.                         $rationing = $rateController->comprehensive['car'];
  332.                     } else {
  333.                         $additioning = $additionalController->total_loss_only;
  334.                         $rationing = $rateController->total_loss_only['car'];
  335.                     }
  336.  
  337.                     // SHOW ALL
  338.                     $variable = [1 => 125000000, 2 => 200000000, 3 => 400000000, 4 => 800000000, 5 => 800000000];
  339.                     $classer = [1 => 'zone_one', 2 => 'zone_two', 3 => 'zone_three'];
  340.  
  341.                     $case_off = '';
  342.                     foreach ($classer as $k => $v) {
  343.                         $case_off .= '@' . $v . '_top:=(CASE ';
  344.  
  345.                         foreach ($variable as $key => $value) {
  346.                             if ($key == 5) {
  347.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>' . $variable[$key] . '
  348.                                             THEN ' . $rationing[$key][$k]['top'] . ' ';
  349.                             } elseif ($key == 1) {
  350.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>=0 AND questionnaires.car_premi_calc<' . $variable[$key] . '
  351.                                             THEN ' . $rationing[$key][$k]['top'] . ' ';
  352.                             } else {
  353.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>=' . $variable[$key - 1] . ' AND questionnaires.car_premi_calc<' . $variable[$key] . '
  354.                                             THEN ' . $rationing[$key][$k]['top'] . ' ';
  355.                             }
  356.                         }
  357.                         $case_off .= 'END), ';
  358.                     }
  359.  
  360.                     foreach ($classer as $k => $v) {
  361.                         $case_off .= '@' . $v . '_bottom:=(CASE ';
  362.  
  363.                         foreach ($variable as $key => $value) {
  364.                             if ($key == 5) {
  365.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>' . $variable[$key] . '
  366.                                             THEN ' . $rationing[$key][$k]['bottom'] . ' ';
  367.                             } elseif ($key == 1) {
  368.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>=0 AND questionnaires.car_premi_calc<' . $variable[$key] . '
  369.                                             THEN ' . $rationing[$key][$k]['bottom'] . ' ';
  370.                             } else {
  371.                                 $case_off .= 'WHEN questionnaires.car_premi_calc>=' . $variable[$key - 1] . ' AND questionnaires.car_premi_calc<' . $variable[$key] . '
  372.                                             THEN ' . $rationing[$key][$k]['bottom'] . ' ';
  373.                             }
  374.                         }
  375.                         $case_off .= 'END), ';
  376.                     }
  377.                     $sql .= $case_off;
  378.  
  379.                     $sql .= '@accident:=5000000, ';
  380.  
  381.                     /**
  382.                      * NOW THE QUERY CHANGED AFTER LATENESS DATA. the changed also effecting into degradation of data and
  383.                      * also changed effect into everywhere ...
  384.                      */
  385.  
  386.                     $sql .= '@value_car:=(CASE WHEN questionnaires.degradation_year_condition<' . $gap_age . '
  387.                                 THEN ' . $query['car_value'] . '-(' . $query['car_value'] . '/100)*questionnaires.degradation_rate
  388.                                 ELSE ' . $query['car_value'] . ' END), ';
  389.  
  390.                     if (isset($request['addition'])) {
  391.                         $requests_additional = json_decode($request['addition'], true);
  392.                         $count_request_additional = count($requests_additional);
  393.  
  394.                         if (!empty($requests_additional) and $count_request_additional > 0) {
  395.                             $setcook['addition'] = $requests_additional;
  396.                             $interval_requests_additional = 0;
  397.  
  398.                             $iteration = $requests_additional;
  399.                             unset($iteration['flood_with_tornado']);
  400.                             unset($iteration['earthquake_with_tsunami']);
  401.                             unset($iteration['passenger_seat']);
  402.                             if (count($iteration) - 1 > 0) {
  403.                                 $absolute .= 'AND ';
  404.                                 foreach ($iteration as $k => $v) {
  405.                                     $absolute .= 'additional_coverages.' . $k . ' ';
  406.                                     if ($interval_requests_additional < count($iteration) - 1) {
  407.                                         $absolute .= 'AND ';
  408.                                     }
  409.                                     $interval_requests_additional++;
  410.                                 }
  411.                             }
  412.  
  413.                             if (isset($requests_additional['accident_passenger'])) {
  414.                                 $sql .= '@passenger:=' . $requests_additional['passenger'] . ',';
  415.                             }
  416.                             $sql .= '@passenger:=3,';
  417.  
  418.                             /**
  419.                              * in this part, you'll face the first layer of calculation also called the additional calculation. why
  420.                              * additional calculation is doing in the first time ? the answer is ... ASK YOUR BOSS !!! Anirud
  421.                              * so in this part you will do some of calculation of additional car such as flood, earthquake,etc whatever
  422.                              * also with territorial. so enjoy !
  423.                              * ---------------------------------
  424.                              */
  425.  
  426.                             // flood first ----------------
  427.                             if (isset($requests_additional['flood_with_tornado'])) {
  428.  
  429.                                 $flood .= '@flood:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  430.                                         THEN (CASE ';
  431.                                 foreach ($sort as $key => $value) {
  432.                                     $flood .= 'WHEN zone_territory.zone_id=' . $key . ' AND additional_coverages.flood_with_tornado_zone_' . $value . ' IS NOT NULL
  433.                                             THEN (CASE WHEN additional_coverages.flood_with_tornado_zone_' . $value . ' = "top" THEN ' . $additioning['car']['flood_with_tornado'][$key]['top'] . '
  434.                                                     WHEN additional_coverages.flood_with_tornado_zone_' . $value . ' = "bottom" THEN ' . $additioning['car']['flood_with_tornado'][$key]['bottom'] . '
  435.                                                     ELSE CAST(additional_coverages.flood_with_tornado_zone_' . $value . ' AS DECIMAL(20,2))
  436.                                                     END) ';
  437.                                 }
  438.                                 $flood .= 'ELSE CAST(additional_coverages.flood_with_tornado_zone_custom AS DECIMAL(20,2)) END) ';
  439.                                 $flood .= 'ELSE 0 END), ';
  440.                                 $flood .= '@flood:=(@value_car/100)*@flood, ';
  441.                                 if (!isset($requests_additional['earthquake_with_tsunami'])) {
  442.                                     $flood .= '@disaster:=@flood, ';
  443.                                 }
  444.                             }
  445.  
  446.                             if (isset($requests_additional['earthquake_with_tsunami'])) {
  447.                                 $earthquake .= '@earthquake:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  448.                                         THEN (CASE ';
  449.                                 foreach ($sort as $key => $value) {
  450.                                     $earthquake .= 'WHEN zone_territory.zone_id=' . $key . ' AND additional_coverages.earthquake_with_tsunami_zone_' . $value . ' IS NOT NULL
  451.                                             THEN (CASE WHEN additional_coverages.earthquake_with_tsunami_zone_' . $value . ' = "top" THEN ' . $additioning['car']['earthquake_with_tsunami'][$key]['top'] . '
  452.                                                     WHEN additional_coverages.earthquake_with_tsunami_zone_' . $value . ' = "bottom" THEN ' . $additioning['car']['earthquake_with_tsunami'][$key]['bottom'] . '
  453.                                                     ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_' . $value . ' AS DECIMAL(20,2))
  454.                                                     END) ';
  455.                                 }
  456.                                 $earthquake .= 'ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_custom AS DECIMAL(20,2)) END) ';
  457.                                 $earthquake .= 'ELSE 0 END), ';
  458.                                 $earthquake .= '@earthquake:=(@value_car/100)*@earthquake, ';
  459.                                 $earthquake .= '@disaster:=IF(@flood IS NOT NULL, @flood+@earthquake, @earthquake), ';
  460.                             }
  461.                             $sql .= $flood . $earthquake;
  462.  
  463.                             /*
  464.  
  465.                             // then earthquake ------------
  466.                             foreach($sort as $key=>$value){
  467.                                 $earthquake.= '(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  468.                                     THEN (CASE WHEN zone_territory.zone_id=1 AND additional_coverages.earthquake_with_tsunami_zone_'.$value.' IS NOT NULL
  469.                                     THEN @flood:=(CASE WHEN additional_coverages.earthquake_with_tsunami_zone_'.$value.' = "top" THEN '.$additioning['car']['earthquake_with_tsunami'][1]['top'].'
  470.                                     WHEN additional_coverages.earthquake_with_tsunami_zone_'.$value.' = "bottom" THEN '.$additioning['car']['earthquake_with_tsunami'][1]['bottom'].'
  471.                                     ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_'.$value.' AS UNSIGNED)
  472.                                     END), ';
  473.                             }
  474.  
  475.                             /**
  476.                              * okay, that's territorial zone done, now you'll facing the single zone ...
  477.                              * in this part there's two case condition such as terrorism and chaos part literaly
  478.                              * ----------------------------
  479.                              */
  480.                             // chaos and riot ----------------
  481.                             if (isset($requests_additional['chaos_and_riot'])) {
  482.                                 $srcc = '@chaos_and_riot:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  483.                                     THEN (CASE WHEN additional_coverages.chaos_and_riot IS NOT NULL THEN CAST(' . $additioning['car']['riot_and_chaos'] . ' AS DECIMAL(3,3)) END)
  484.                                     ELSE 0 END), ';
  485.                                 $srcc .= '@chaos_and_riot:=(@value_car/100)*@chaos_and_riot, ';
  486.                                 if (!isset($requests_additional['terrorism_and_sabotage'])) {
  487.                                     $srcc .= '@commotion:=@chaos_and_riot, ';
  488.  
  489.                                 }
  490.                                 $sql .= $srcc;
  491.                             }
  492.  
  493.                             if (isset($requests_additional['terrorism_and_sabotage'])) {
  494.                                 // terrorism and sabotage --------
  495.                                 $terrorism = '@terrorism_and_sabotage:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  496.                                          THEN (CASE WHEN additional_coverages.terrorism_and_sabotage IS NOT NULL THEN CAST(' . $additioning['car']['terrorism_and_sabotage'] . ' AS DECIMAL(3,3)) END)
  497.                                          ELSE 0 END), ';
  498.                                 $terrorism .= '@terrorism_and_sabotage:=(@value_car/100)*@terrorism_and_sabotage, ';
  499.                                 $terrorism .= '@commotion:=IF(@chaos_and_riot IS NOT NULL, @chaos_and_riot+@terrorism_and_sabotage, @terrorism_and_sabotage), ';
  500.                                 $sql .= $terrorism;
  501.                             }
  502.  
  503.                             if (isset($requests_additional['responsibility_third_party_by_law'])) {
  504.                                 $rtpl = (integer)$requests_additional['responsibility_third_party_by_law'];
  505.                                 $pieces_of_prices_law = [];
  506.  
  507.                                 // sequence 1
  508.                                 if ($rtpl > 0) {
  509.                                     if ($rtpl <= 25000000) {
  510.                                         $pieces_of_prices_law[0] = $rtpl;
  511.                                         $rtpl = 0;
  512.                                     } else {
  513.                                         $pieces_of_prices_law[0] = 25000000;
  514.                                         $rtpl = $rtpl - 25000000;
  515.                                     }
  516.                                 }
  517.  
  518.                                 // sequence 2
  519.                                 if ($rtpl > 0) {
  520.                                     if ($rtpl <= 25000000) {
  521.                                         $pieces_of_prices_law[1] = $rtpl;
  522.                                         $rtpl = 0;
  523.                                     } else {
  524.                                         $pieces_of_prices_law[1] = 25000000;
  525.                                         $rtpl = $rtpl - 25000000;
  526.                                     }
  527.                                 }
  528.  
  529.                                 // sequence 3
  530.                                 if ($rtpl > 0) {
  531.                                     if ($rtpl <= 50000000) {
  532.                                         $pieces_of_prices_law[2] = $rtpl;
  533.                                         $rtpl = 0;
  534.                                     } else {
  535.                                         $pieces_of_prices_law[2] = 50000000;
  536.                                         $rtpl = $rtpl - 50000000;
  537.                                     }
  538.                                 }
  539.  
  540.  
  541.                                 // sequence 4 sisanya
  542.                                 if ($rtpl > 0) {
  543.                                     $pieces_of_prices_law[3] = $rtpl;
  544.                                     $rtpl = 0;
  545.                                 }
  546.  
  547.                                 if (isset($pieces_of_prices_law[0])) {
  548.                                     DB::statement('SET @third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED)');
  549.                                     $tpl = '@third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  550.                                 } else {
  551.                                     DB::statement('SET @third_party_liability_one:=0 ');
  552.                                     $tpl = '@third_party_liability_one:=0, ';
  553.                                 }
  554.                                 if (isset($pieces_of_prices_law[1])) {
  555.                                     DB::statement('SET @third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED)');
  556.                                     $tpl .= '@third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED), ';
  557.                                 } else {
  558.                                     DB::statement('SET @third_party_liability_two:=0 ');
  559.                                     $tpl .= '@third_party_liability_two:=0, ';
  560.                                 }
  561.                                 if (isset($pieces_of_prices_law[2])) {
  562.                                     DB::statement('SET @third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED)');
  563.                                     $tpl .= '@third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['car']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED), ';
  564.                                 } else {
  565.                                     DB::statement('SET @third_party_liability_three:=0 ');
  566.                                     $tpl .= '@third_party_liability_three:=0, ';
  567.                                 }
  568.                                 if (isset($pieces_of_prices_law[3])) {
  569.                                     DB::statement('SET @third_party_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_third_party_by_law AS UNSIGNED) ');
  570.                                     $tpl .= '@third_party_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_third_party_by_law AS UNSIGNED), ';
  571.                                 } else {
  572.                                     DB::statement('SET @third_party_liability_four:=0 ');
  573.                                     $tpl .= '@third_party_liability_four:=0, ';
  574.                                 }
  575.  
  576.                                 $tpl .= '@third_party_liability:=@third_party_liability_one+@third_party_liability_two+@third_party_liability_three+@third_party_liability_four, ';
  577.                                 $sql .= $tpl;
  578.                             }
  579.                             if (isset($requests_additional['responsibility_law_for_passenger'])) {
  580.                                 /*
  581.                                 $rtpl = (integer)$requests_additional['responsibility_law_for_passenger'];
  582.                                 DB::statement('SET @passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED)');
  583.                                 //$tpl = '@tpl_one=@tpl_one+1, ';
  584.                                 $tpl = '@passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  585.                                 DB::statement('SET @passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED)');
  586.                                 $tpl .= '@passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED), ';
  587.                                 DB::statement('SET @passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED)');
  588.                                 $tpl .= '@passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED), ';
  589.                                 $tpl .= '@passenger_liability_four:=CAST(IF(@responsibility>100000000,(@responsibility/100)*additional_coverages.responsibility_law_for_passenger,0) AS UNSIGNED), ';
  590.                                 $tpl .= '@passenger_liability:=@passenger_liability_one+@passenger_liability_two+@passenger_liability_three+@passenger_liability_four, ';
  591.                                 $sql .= $tpl;
  592.                                 */
  593.                                 $rtpl = (integer)$requests_additional['responsibility_law_for_passenger'];
  594.                                 $pieces_of_prices_law = [];
  595.  
  596.                                 // sequence 1
  597.                                 if ($rtpl > 0) {
  598.                                     if ($rtpl <= 25000000) {
  599.                                         $pieces_of_prices_law[0] = $rtpl;
  600.                                         $rtpl = 0;
  601.                                     } else {
  602.                                         $pieces_of_prices_law[0] = 25000000;
  603.                                         $rtpl = $rtpl - 25000000;
  604.                                     }
  605.                                 }
  606.  
  607.                                 // sequence 2
  608.                                 if ($rtpl > 0) {
  609.                                     if ($rtpl <= 25000000) {
  610.                                         $pieces_of_prices_law[1] = $rtpl;
  611.                                         $rtpl = 0;
  612.                                     } else {
  613.                                         $pieces_of_prices_law[1] = 25000000;
  614.                                         $rtpl = $rtpl - 25000000;
  615.                                     }
  616.                                 }
  617.  
  618.                                 // sequence 3
  619.                                 if ($rtpl > 0) {
  620.                                     if ($rtpl <= 50000000) {
  621.                                         $pieces_of_prices_law[2] = $rtpl;
  622.                                         $rtpl = 0;
  623.                                     } else {
  624.                                         $pieces_of_prices_law[2] = 50000000;
  625.                                         $rtpl = $rtpl - 50000000;
  626.                                     }
  627.                                 }
  628.  
  629.  
  630.                                 // sequence 4 sisanya
  631.                                 if ($rtpl > 0) {
  632.                                     $pieces_of_prices_law[3] = $rtpl;
  633.                                     $rtpl = 0;
  634.                                 }
  635.  
  636.                                 if (isset($pieces_of_prices_law[0])) {
  637.                                     DB::statement('SET @passenger_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED)');
  638.                                     $tpl = '@passenger_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  639.                                 } else {
  640.                                     DB::statement('SET @passenger_liability_one:=0 ');
  641.                                     $tpl .= '@passenger_liability_one:=0, ';
  642.                                 }
  643.                                 if (isset($pieces_of_prices_law[1])) {
  644.                                     DB::statement('SET @passenger_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED)');
  645.                                     $tpl .= '@passenger_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED), ';
  646.                                 } else {
  647.                                     DB::statement('SET @passenger_liability_two:=0 ');
  648.                                     $tpl .= '@passenger_liability_two:=0, ';
  649.                                 }
  650.                                 if (isset($pieces_of_prices_law[2])) {
  651.                                     DB::statement('SET @passenger_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED)');
  652.                                     $tpl .= '@passenger_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED), ';
  653.                                 } else {
  654.                                     DB::statement('SET @passenger_liability_three:=0 ');
  655.                                     $tpl .= '@passenger_liability_three:=0, ';
  656.                                 }
  657.                                 if (isset($pieces_of_prices_law[3])) {
  658.                                     DB::statement('SET @passenger_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_law_passenger AS UNSIGNED) ');
  659.                                     $tpl .= '@passenger_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_law_passenger AS UNSIGNED), ';
  660.                                 } else {
  661.                                     DB::statement('SET @passenger_liability_four:=0 ');
  662.                                     $tpl .= '@third_party_liability_four:=0, ';
  663.                                 }
  664.  
  665.                                 $tpl .= '@passenger_liability:=@passenger_liability_one+@passenger_liability_two+@passenger_liability_three+@passenger_liability_four, ';
  666.                                 $sql .= $tpl;
  667.                             }
  668.  
  669.                             if (isset($requests_additional['self_accident_for_driver'])) {
  670.                                 $driver = '@driver:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  671.                                     THEN (CASE WHEN additional_coverages.self_accident_for_driver IS NOT NULL THEN CAST(' . $additioning['car']['accident_driver'] . ' AS DECIMAL(3,2)) END)
  672.                                     ELSE 0 END), ';
  673.                                 $driver .= '@driver:=(' . $requests_additional['self_accident_for_driver'] . '/100)*@driver, ';
  674.                                 if (!isset($requests_additional['self_accident_for_passenger'])) {
  675.                                     $driver .= '@car_in:=@driver, ';
  676.                                 }
  677.                                 $sql .= $driver;
  678.                             }
  679.  
  680.                             if (isset($requests_additional['self_accident_for_passenger'])) {
  681.                                 $passenger = '@passengers:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  682.                                     THEN (CASE WHEN additional_coverages.self_accident_for_passenger IS NOT NULL THEN CAST(' . $additioning['car']['accident_passenger'] . ' AS DECIMAL(3,2)) END)
  683.                                     ELSE 0 END), ';
  684.                                 $passenger .= '@passengers:=((' . $requests_additional['self_accident_for_passenger'] . '/100)*@passengers)*' . $requests_additional['passenger_seat'] . ', ';
  685.                                 $passenger .= '@car_in:=IF(@driver IS NOT NULL, @driver+@passengers, @passengers), ';
  686.                                 $sql .= $passenger;
  687.                             }
  688.  
  689.                             $sql .= '@calculate:=(CASE WHEN @disaster IS NOT NULL AND @commotion IS NULL
  690.                                                         THEN @disaster
  691.                                                     WHEN @disaster IS NULL AND @commotion IS NOT NULL
  692.                                                         THEN @commotion
  693.                                                     WHEN @disaster IS NOT NULL AND @commotion IS NOT NULL
  694.                                                         THEN @disaster+@commotion
  695.                                                     ELSE 0 END), ';
  696.  
  697.                             $sql .= '@lawsuit:=(CASE WHEN @third_party_liability IS NOT NULL AND @passenger_liability IS NOT NULL
  698.                                                         THEN @third_party_liability+@passenger_liability
  699.                                                     WHEN @liability IS NULL AND @passenger_liability IS NOT NULL
  700.                                                         THEN @passenger_liability
  701.                                                     WHEN @third_party_liability IS NOT NULL AND @passenger_liability IS NULL
  702.                                                         THEN @third_party_liability
  703.                                                     ELSE 0 END), ';
  704.  
  705.                             // END OF ACCUMULATION ADDITIONAL !!!!!!!! ----------------------------------------------------------------------
  706.  
  707.                         }
  708.                     } else {
  709.                         $sql .= '@accumulation:=0, ';
  710.                     }
  711.  
  712.                     $sql .= $amount_features . $percentages_features;
  713.                     $sql .= '@percentage_feature_prices:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  714.                                 THEN (@value_car/100)*@percentages_price
  715.                                 ELSE 0 END), ';
  716.  
  717.                     // disini query harus ngeliat apa dia punya override atau gak, kalo emang gak, ya berarti di
  718.                     // pake dong territorial ratenya, dan juga territory diliat lagi tipe zonenya
  719.                     $sql .= '(CASE WHEN coverages.territory_custom_rate IS NULL THEN
  720.                                 (CASE
  721.                                     WHEN zone_territory.zone_id=1
  722.                                         THEN (CASE WHEN coverages.territory_one_rate="top" THEN @percentages:=@zone_one_top
  723.                                             WHEN coverages.territory_one_rate="bottom" THEN @percentages:=@zone_one_bottom
  724.                                             ELSE @percentages:=CAST(coverages.territory_one_rate AS DECIMAL(15,2)) END)
  725.                                     WHEN zone_territory.zone_id=2
  726.                                         THEN (CASE WHEN coverages.territory_two_rate="top" THEN @percentages:=@zone_two_top
  727.                                             WHEN coverages.territory_two_rate="bottom" THEN @percentages:=@zone_two_bottom
  728.                                             ELSE @percentages:=CAST(coverages.territory_two_rate AS DECIMAL(15,2)) END)
  729.                                     ELSE (CASE WHEN coverages.territory_three_rate="top" THEN @percentages:=@zone_three_top
  730.                                             WHEN coverages.territory_three_rate="bottom" THEN @percentages:=@zone_three_bottom
  731.                                             ELSE @percentages:=CAST(coverages.territory_three_rate AS DECIMAL(15,2)) END)
  732.                                     END)
  733.                                 ELSE @percentages:=CAST(coverages.territory_custom_rate AS DECIMAL(15,2))
  734.                             END), ';
  735.  
  736.                     $sql .= '(CASE
  737.                                 WHEN questionnaires.additional_year_condition<' . $gap_age . ' THEN @addons_percentages:=(questionnaires.additional_rate/100)
  738.                                 ELSE @addons_percentages:=0
  739.                             END), ';
  740.  
  741.                     /**
  742.                      * calculate everything into one pieces, but first you need an raw prices and then
  743.                      * you can go into accumulation prices based on.
  744.                      */
  745.  
  746.                     $sql .= '@premx:=(@value_car/100)*(@percentages + (@percentages * @addons_percentages)), ';
  747.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premx+@amount_price, @premx), ';
  748.                     $sql .= '@premi:=IF(@percentage_feature_prices IS NOT NULL AND @percentage_feature_prices > 0, @premi+@percentage_feature_prices, @premi), ';
  749.                     $sql .= '@premi:=IF(@calculate IS NOT NULL AND @calculate > 0, @premi+@calculate, @premi), ';
  750.                     $sql .= '@premi:=IF(@lawsuit IS NOT NULL AND @lawsuit > 0, @premi+@lawsuit, @premi), ';
  751.                     $sql .= '@premi:=IF(@car_in IS NOT NULL AND @car_in > 0, @premi+@car_in, @premi), ';
  752.                     $sql .= $additional_fee_admin;
  753.                     $sql .= $additional_fee_materai;
  754.                     $sql .= '@premi:=FLOOR(@premi+@admin_fee+@materai_fee), ';
  755.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  756.                     $sql .= 'product.id as product_id ';
  757.  
  758.                     $sql .= 'FROM insurance_product product ';
  759.                     $sql .= 'LEFT JOIN (SELECT *,';
  760.  
  761.                     // ini gua ngambil harga yang di degradasi, belum di round ya
  762.                     $sql .= '(CASE
  763.                                 WHEN degradation_year_condition<' . $gap_age . ' THEN @value_car:=' . $query['car_value'] . '-(((' . $query['car_value'] . '/100)*degradation_rate))
  764.                                 ELSE @value_car:=' . $query['car_value'] . '
  765.                             END) as car_premi_calc ';
  766.  
  767.                     $sql .= 'FROM insurance_questionnaire_car) questionnaires ON questionnaires.product_id = product.id ';
  768.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_car) features ON features.product_id = product.id ';
  769.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_car_' . $query['level_of_insurance'] . ') coverages ON coverages.product_id = product.id ';
  770.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_additional_car) additional_coverages ON additional_coverages.product_id = product.id ';
  771.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  772.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  773.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  774.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  775.                     $sql .= 'LEFT JOIN (SELECT * FROM zone_territory_car) zone_territory ON TRUE ';
  776.                     $sql .= 'WHERE ( ';
  777.  
  778.                     unset($query['car_year']);
  779.                     unset($query['car_year_brand']);
  780.                     unset($query['car_year_brand_model']);
  781.                     unset($query['car_year_brand_model_type']);
  782.  
  783.                     // PAKE LAGI KALO MAU GUNAKAN FLEXIBLE QUESTIONNAIRE
  784.                     /*
  785.                     foreach ($query as $key => $value) {
  786.                         switch ($key) {
  787.                             case 'car_value':
  788.                                 $sql .= 'questionnaires.car_value_min IS NULL OR questionnaires.car_value_min < ' . $value . ' AND questionnaires.car_value_max IS NULL OR questionnaires.car_value_max > ' . $value . ' ';
  789.                                 $sql .= '';
  790.                                 break;
  791.  
  792.                             case 'car_set':
  793.                                 $sql .= 'cav.car_additional_id = ' . $value . ' OR cav.car_additional_id IS NULL ';
  794.                                 break;
  795.  
  796.                             case 'date_of_birth':
  797.                                 $age            = calculateAge($value);
  798.                                 $setcook['age'] = $age;
  799.                                 $sql            .= 'questionnaires.age_min IS NULL OR questionnaires.age_min < ' . $age . ' AND questionnaires.age_max IS NULL OR questionnaires.age_max > ' . $age . ' ';
  800.                                 break;
  801.  
  802.                             default:
  803.                                 $sql .= 'questionnaires.' . $key . ' IS NULL OR questionnaires.' . $key . ' LIKE "%' . $value . '%" ';
  804.                                 break;
  805.                         }
  806.  
  807.                         if ($counter < count($query) - 1) {
  808.                             $sql .= 'AND ';
  809.                         }
  810.                         $counter++;
  811.     IF(questionnaires.car_value_min IS NOT NULL, questionnaires.car_value_min < 900000000, questionnaires.car_value_min IS NULL) AND
  812.     IF(questionnaires.car_value_max IS NOT NULL, questionnaires.car_value_max > 900000000, questionnaires.car_value_max IS NULL)
  813.                     }*/
  814.                     $sql .= 'IF(questionnaires.car_value_min IS NOT NULL, questionnaires.car_value_min < ' . $query['car_value'] . ', questionnaires.car_value_min IS NULL) AND ';
  815.                     $sql .= 'IF(questionnaires.car_value_max IS NOT NULL, questionnaires.car_value_max > ' . $query['car_value'] . ', questionnaires.car_value_max IS NULL) AND ';
  816.                     $sql .= 'IF(questionnaires.age_vehicle_max IS NOT NULL, questionnaires.age_vehicle_max > ' . $gap_age . ', questionnaires.age_vehicle_max IS NULL) ';
  817.  
  818.                     break;
  819.  
  820.                 case 'motorcycle':
  821.                     $gap_age = date('Y') - (integer)$query['motorcycle_year'];
  822.                     $flood = '';
  823.                     $earthquake = '';
  824.                     $liability = '';
  825.                     $sort = [1 => 'one', 2 => 'two', 3 => 'three'];
  826.  
  827.                     if ($query['level_of_insurance'] == 'comprehensive') {
  828.                         $additioning = $additionalController->comprehensive;
  829.                         $rationing = $rateController->comprehensive['motorcycle'];
  830.                     } else {
  831.                         $additioning = $additionalController->total_loss_only;
  832.                         $rationing = $rateController->total_loss_only['motorcycle'];
  833.                     }
  834.  
  835.                     // SHOW ALL
  836. //                    $variable = [ 1 => 125000000, 2 => 200000000, 3 => 400000000, 4 => 800000000, 5 => 800000000 ];
  837.                     $classer = [1 => 'zone_one', 2 => 'zone_two', 3 => 'zone_three'];
  838.  
  839.                     $case_off = '';
  840.                     foreach ($classer as $k => $v) {
  841.                         DB::statement('SET @' . $v . '_top:=CAST(' . $rationing[1][$k]['top'] . ' AS DECIMAL(15,2)) ');
  842.                         DB::statement('SET @' . $v . '_bottom:=CAST(' . $rationing[1][$k]['bottom'] . ' AS DECIMAL(15,2)) ');
  843.                         $case_off .= '@' . $v . '_top:=CAST(' . $rationing[1][$k]['top'] . ' AS DECIMAL(15,2)) , ';
  844.                         $case_off .= '@' . $v . '_bottom:=CAST(' . $rationing[1][$k]['bottom'] . ' AS DECIMAL(15,2)) , ';
  845.                     }
  846.                     $sql .= $case_off;
  847.  
  848.                     // ini gua ngambil harga yang di degradasi, belum di round ya
  849.                     $sql .= '(CASE
  850.                                 WHEN questionnaires.degradation_year_condition<' . $gap_age . ' THEN @value_motorcycle:=' . $query['motorcycle_value'] . '-(' . $query['motorcycle_value'] . '/100)*questionnaires.degradation_rate
  851.                                 ELSE @value_motorcycle:=' . $query['motorcycle_value'] . '
  852.                             END), ';
  853.  
  854.                     if (isset($request['addition'])) {
  855.                         $requests_additional = json_decode($request['addition'], true);
  856.                         $count_request_additional = count($requests_additional);
  857.  
  858.                         if (!empty($requests_additional) and $count_request_additional > 0) {
  859.                             $setcook['addition'] = $requests_additional;
  860.                             $interval_requests_additional = 0;
  861.  
  862.                             $iteration = $requests_additional;
  863.                             unset($iteration['flood_with_tornado']);
  864.                             unset($iteration['earthquake_with_tsunami']);
  865.                             unset($iteration['passenger_seat']);
  866.                             if (count($iteration) - 1 > 0) {
  867.                                 $absolute .= 'AND ';
  868.                                 foreach ($iteration as $k => $v) {
  869.                                     $absolute .= 'additional_coverages.' . $k . ' ';
  870.                                     if ($interval_requests_additional < count($iteration) - 1) {
  871.                                         $absolute .= 'AND ';
  872.                                     }
  873.                                     $interval_requests_additional++;
  874.                                 }
  875.                             }
  876.  
  877.                             if (isset($requests_additional['accident_passenger'])) {
  878.                                 $sql .= '@passenger:=' . $requests_additional['passenger'] . ',';
  879.                             }
  880.                             $sql .= '@passenger:=3,';
  881.  
  882.                             /**
  883.                              * in this part, you'll face the first layer of calculation also called the additional calculation. why
  884.                              * additional calculation is doing in the first time ? the answer is ... ASK YOUR BOSS !!! Anirud
  885.                              * so in this part you will do some of calculation of additional motorcycle such as flood, earthquake,etc whatever
  886.                              * also with territorial. so enjoy !
  887.                              * ---------------------------------
  888.                              */
  889.  
  890.                             // flood first ----------------
  891.                             if (isset($requests_additional['flood_with_tornado'])) {
  892.  
  893.                                 $flood .= '@flood:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  894.                                         THEN (CASE ';
  895.                                 foreach ($sort as $key => $value) {
  896.                                     $flood .= 'WHEN zone_territory.zone_id=' . $key . ' AND additional_coverages.flood_with_tornado_zone_' . $value . ' IS NOT NULL
  897.                                             THEN (CASE WHEN additional_coverages.flood_with_tornado_zone_' . $value . ' = "top" THEN ' . $additioning['motorcycle']['flood_with_tornado'][$key]['top'] . '
  898.                                                     WHEN additional_coverages.flood_with_tornado_zone_' . $value . ' = "bottom" THEN ' . $additioning['motorcycle']['flood_with_tornado'][$key]['bottom'] . '
  899.                                                     ELSE CAST(additional_coverages.flood_with_tornado_zone_' . $value . ' AS DECIMAL(20,2))
  900.                                                     END) ';
  901.                                 }
  902.                                 $flood .= 'ELSE CAST(additional_coverages.flood_with_tornado_zone_custom AS DECIMAL(20,2)) END) ';
  903.                                 $flood .= 'ELSE 0 END), ';
  904.                                 $flood .= '@flood:=(@value_motorcycle/100)*@flood, ';
  905.                                 if (!isset($requests_additional['earthquake_with_tsunami'])) {
  906.                                     $flood .= '@disaster:=@flood, ';
  907.                                 }
  908.                             }
  909.  
  910.                             if (isset($requests_additional['earthquake_with_tsunami'])) {
  911.                                 $earthquake .= '@earthquake:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  912.                                         THEN (CASE ';
  913.                                 foreach ($sort as $key => $value) {
  914.                                     $earthquake .= 'WHEN zone_territory.zone_id=' . $key . ' AND additional_coverages.earthquake_with_tsunami_zone_' . $value . ' IS NOT NULL
  915.                                             THEN (CASE WHEN additional_coverages.earthquake_with_tsunami_zone_' . $value . ' = "top" THEN ' . $additioning['motorcycle']['earthquake_with_tsunami'][$key]['top'] . '
  916.                                                     WHEN additional_coverages.earthquake_with_tsunami_zone_' . $value . ' = "bottom" THEN ' . $additioning['motorcycle']['earthquake_with_tsunami'][$key]['bottom'] . '
  917.                                                     ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_' . $value . ' AS DECIMAL(20,2))
  918.                                                     END) ';
  919.                                 }
  920.                                 $earthquake .= 'ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_custom AS DECIMAL(20,2)) END) ';
  921.                                 $earthquake .= 'ELSE 0 END), ';
  922.                                 $earthquake .= '@earthquake:=(@value_motorcycle/100)*@earthquake, ';
  923.                                 $earthquake .= '@disaster:=IF(@flood IS NOT NULL, @flood+@earthquake, @earthquake), ';
  924.                             }
  925.                             $sql .= $flood . $earthquake;
  926.  
  927.                             /*
  928.  
  929.                             // then earthquake ------------
  930.                             foreach($sort as $key=>$value){
  931.                                 $earthquake.= '(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  932.                                     THEN (CASE WHEN zone_territory.zone_id=1 AND additional_coverages.earthquake_with_tsunami_zone_'.$value.' IS NOT NULL
  933.                                     THEN @flood:=(CASE WHEN additional_coverages.earthquake_with_tsunami_zone_'.$value.' = "top" THEN '.$additioning['motorcycle']['earthquake_with_tsunami'][1]['top'].'
  934.                                     WHEN additional_coverages.earthquake_with_tsunami_zone_'.$value.' = "bottom" THEN '.$additioning['motorcycle']['earthquake_with_tsunami'][1]['bottom'].'
  935.                                     ELSE CAST(additional_coverages.earthquake_with_tsunami_zone_'.$value.' AS UNSIGNED)
  936.                                     END), ';
  937.                             }
  938.  
  939.                             /**
  940.                              * okay, that's territorial zone done, now you'll facing the single zone ...
  941.                              * in this part there's two case condition such as terrorism and chaos part literaly
  942.                              * ----------------------------
  943.                              */
  944.                             // chaos and riot ----------------
  945.                             if (isset($requests_additional['chaos_and_riot'])) {
  946.                                 $srcc = '@chaos_and_riot:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  947.                                     THEN (CASE WHEN additional_coverages.chaos_and_riot IS NOT NULL THEN CAST(' . $additioning['motorcycle']['riot_and_chaos'] . ' AS DECIMAL(3,3)) END)
  948.                                     ELSE 0 END), ';
  949.                                 $srcc .= '@chaos_and_riot:=(@value_motorcycle/100)*@chaos_and_riot, ';
  950.                                 if (!isset($requests_additional['terrorism_and_sabotage'])) {
  951.                                     $srcc .= '@commotion:=@chaos_and_riot, ';
  952.  
  953.                                 }
  954.                                 $sql .= $srcc;
  955.                             }
  956.  
  957.                             if (isset($requests_additional['terrorism_and_sabotage'])) {
  958.                                 // terrorism and sabotage --------
  959.                                 $terrorism = '@terrorism_and_sabotage:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  960.                                          THEN (CASE WHEN additional_coverages.terrorism_and_sabotage IS NOT NULL THEN CAST(' . $additioning['motorcycle']['terrorism_and_sabotage'] . ' AS DECIMAL(3,3)) END)
  961.                                          ELSE 0 END), ';
  962.                                 $terrorism .= '@terrorism_and_sabotage:=(@value_motorcycle/100)*@terrorism_and_sabotage, ';
  963.                                 $terrorism .= '@commotion:=IF(@chaos_and_riot IS NOT NULL, @chaos_and_riot+@terrorism_and_sabotage, @terrorism_and_sabotage), ';
  964.                                 $sql .= $terrorism;
  965.                             }
  966.  
  967.                             /*if (isset($requests_additional['responsibility_third_party_by_law'])) {
  968.                                 $rtpl = (integer)$requests_additional['responsibility_third_party_by_law'];
  969.                                 $pieces_of_prices_law = [];
  970.  
  971.                                 // sequence 1
  972.                                 if($rtpl >= 25000000){
  973.                                     $pieces_of_prices_law[0] = $rtpl-25000000;
  974.                                     $rtpl = $rtpl-25000000;
  975.                                 } else {
  976.                                     $pieces_of_prices_law[0] = $rtpl;
  977.                                     $rtpl = 0;
  978.                                 }
  979.  
  980.                                 // sequence 2
  981.                                 if($rtpl >= 50000000){
  982.                                     $pieces_of_prices_law[1] = $rtpl-50000000;
  983.                                     $rtpl = $rtpl-50000000;
  984.                                 } elseif($rtpl >= 25000000){
  985.                                     $pieces_of_prices_law[1] = $rtpl-25000000;
  986.                                     $rtpl = $rtpl-25000000;
  987.                                 } else {
  988.                                     $pieces_of_prices_law[1] = $rtpl;
  989.                                     $rtpl = 0;
  990.                                 }
  991.  
  992.                                 // sequence 3
  993.                                 if($rtpl >= 100000000){
  994.                                     $pieces_of_prices_law[2] = $rtpl-100000000;
  995.                                     $rtpl = $rtpl-100000000;
  996.                                 } elseif($rtpl >= 50000000){
  997.                                     $pieces_of_prices_law[2] = $rtpl-50000000;
  998.                                     $rtpl = $rtpl-50000000;
  999.                                 } elseif($rtpl >= 25000000){
  1000.                                     $pieces_of_prices_law[2] = $rtpl-25000000;
  1001.                                     $rtpl = $rtpl-25000000;
  1002.                                 } else {
  1003.                                     $pieces_of_prices_law[2] = $rtpl;
  1004.                                     $rtpl = 0;
  1005.                                 }
  1006.  
  1007.  
  1008.                                 // sequence 4 sisanya
  1009.                                 if($rtpl > 0){
  1010.                                     $pieces_of_prices_law[3] = $rtpl;
  1011.                                     $rtpl = 0;
  1012.                                 }
  1013.  
  1014.                                 if(isset($pieces_of_prices_law[0])){
  1015.                                     DB::statement('SET @third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED)');
  1016.                                     $tpl = '@third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  1017.                                 }
  1018.                                 if(isset($pieces_of_prices_law[1])){
  1019.                                     DB::statement('SET @third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED)');
  1020.                                     $tpl .= '@third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED), ';
  1021.                                 }
  1022.                                 if(isset($pieces_of_prices_law[2])){
  1023.                                     DB::statement('SET @third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED)');
  1024.                                     $tpl .= '@third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED), ';
  1025.                                 }
  1026.                                 if(isset($pieces_of_prices_law[3])){
  1027.                                     $tpl .= '@third_party_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_third_party_by_law AS UNSIGNED), ';
  1028.                                 }
  1029.  
  1030.                                 $tpl .= '@third_party_liability:=@third_party_liability_one+@third_party_liability_two+@third_party_liability_three+@third_party_liability_four, ';
  1031.                                 $sql .= $tpl;
  1032.                             }
  1033.  
  1034.                             if (isset($requests_additional['responsibility_law_for_passenger'])) {
  1035.                                 $rtpl = (integer)$requests_additional['responsibility_law_for_passenger'];
  1036.                                 DB::statement('SET @passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED)');
  1037.                                 //$tpl = '@tpl_one=@tpl_one+1, ';
  1038.                                 $tpl = '@passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  1039.                                 DB::statement('SET @passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED)');
  1040.                                 $tpl .= '@passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED), ';
  1041.                                 DB::statement('SET @passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED)');
  1042.                                 $tpl .= '@passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED), ';
  1043.                                 $tpl .= '@passenger_liability_four:=CAST(IF(@responsibility>100000000,(@responsibility/100)*additional_coverages.responsibility_law_for_passenger,0) AS UNSIGNED), ';
  1044.                                 $tpl .= '@passenger_liability:=@passenger_liability_one+@passenger_liability_two+@passenger_liability_three+@passenger_liability_four, ';
  1045.                                 $sql .= $tpl;
  1046.                             }*/
  1047.                             if (isset($requests_additional['responsibility_third_party_by_law'])) {
  1048.                                 $rtpl = (integer)$requests_additional['responsibility_third_party_by_law'];
  1049.                                 $pieces_of_prices_law = [];
  1050.  
  1051.                                 // sequence 1
  1052.                                 if ($rtpl > 0) {
  1053.                                     if ($rtpl <= 25000000) {
  1054.                                         $pieces_of_prices_law[0] = $rtpl;
  1055.                                         $rtpl = 0;
  1056.                                     } else {
  1057.                                         $pieces_of_prices_law[0] = 25000000;
  1058.                                         $rtpl = $rtpl - 25000000;
  1059.                                     }
  1060.                                 }
  1061.  
  1062.                                 // sequence 2
  1063.                                 if ($rtpl > 0) {
  1064.                                     if ($rtpl <= 25000000) {
  1065.                                         $pieces_of_prices_law[1] = $rtpl;
  1066.                                         $rtpl = 0;
  1067.                                     } else {
  1068.                                         $pieces_of_prices_law[1] = 25000000;
  1069.                                         $rtpl = $rtpl - 25000000;
  1070.                                     }
  1071.                                 }
  1072.  
  1073.                                 // sequence 3
  1074.                                 if ($rtpl > 0) {
  1075.                                     if ($rtpl <= 50000000) {
  1076.                                         $pieces_of_prices_law[2] = $rtpl;
  1077.                                         $rtpl = 0;
  1078.                                     } else {
  1079.                                         $pieces_of_prices_law[2] = 50000000;
  1080.                                         $rtpl = $rtpl - 50000000;
  1081.                                     }
  1082.                                 }
  1083.  
  1084.  
  1085.                                 // sequence 4 sisanya
  1086.                                 if ($rtpl > 0) {
  1087.                                     $pieces_of_prices_law[3] = $rtpl;
  1088.                                     $rtpl = 0;
  1089.                                 }
  1090.  
  1091.                                 if (isset($pieces_of_prices_law[0])) {
  1092.                                     DB::statement('SET @third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED)');
  1093.                                     $tpl = '@third_party_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  1094.                                 } else {
  1095.                                     DB::statement('SET @third_party_liability_one:=0 ');
  1096.                                     $tpl = '@third_party_liability_one:=0, ';
  1097.                                 }
  1098.                                 if (isset($pieces_of_prices_law[1])) {
  1099.                                     DB::statement('SET @third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED)');
  1100.                                     $tpl .= '@third_party_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED), ';
  1101.                                 } else {
  1102.                                     DB::statement('SET @third_party_liability_two:=0 ');
  1103.                                     $tpl .= '@third_party_liability_two:=0, ';
  1104.                                 }
  1105.                                 if (isset($pieces_of_prices_law[2])) {
  1106.                                     DB::statement('SET @third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED)');
  1107.                                     $tpl .= '@third_party_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_third_party_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED), ';
  1108.                                 } else {
  1109.                                     DB::statement('SET @third_party_liability_three:=0 ');
  1110.                                     $tpl .= '@third_party_liability_three:=0, ';
  1111.                                 }
  1112.                                 if (isset($pieces_of_prices_law[3])) {
  1113.                                     DB::statement('SET @third_party_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_third_party_by_law AS UNSIGNED) ');
  1114.                                     $tpl .= '@third_party_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_third_party_by_law AS UNSIGNED), ';
  1115.                                 } else {
  1116.                                     DB::statement('SET @third_party_liability_four:=0 ');
  1117.                                     $tpl .= '@third_party_liability_four:=0, ';
  1118.                                 }
  1119.  
  1120.                                 $tpl .= '@third_party_liability:=@third_party_liability_one+@third_party_liability_two+@third_party_liability_three+@third_party_liability_four, ';
  1121.                                 $sql .= $tpl;
  1122.                             }
  1123.                             if (isset($requests_additional['responsibility_law_for_passenger'])) {
  1124.                                 /*
  1125.                                 $rtpl = (integer)$requests_additional['responsibility_law_for_passenger'];
  1126.                                 DB::statement('SET @passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED)');
  1127.                                 //$tpl = '@tpl_one=@tpl_one+1, ';
  1128.                                 $tpl = '@passenger_liability_one:=CAST((' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  1129.                                 DB::statement('SET @passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED)');
  1130.                                 $tpl .= '@passenger_liability_two:=CAST(IF(' . $rtpl . '>25000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ',0) AS UNSIGNED), ';
  1131.                                 DB::statement('SET @passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED)');
  1132.                                 $tpl .= '@passenger_liability_three:=CAST(IF(' . $rtpl . '>50000000,(' . $rtpl . '/100)*' . $additioning['car']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ',0) AS UNSIGNED), ';
  1133.                                 $tpl .= '@passenger_liability_four:=CAST(IF(@responsibility>100000000,(@responsibility/100)*additional_coverages.responsibility_law_for_passenger,0) AS UNSIGNED), ';
  1134.                                 $tpl .= '@passenger_liability:=@passenger_liability_one+@passenger_liability_two+@passenger_liability_three+@passenger_liability_four, ';
  1135.                                 $sql .= $tpl;
  1136.                                 */
  1137.                                 $rtpl = (integer)$requests_additional['responsibility_law_for_passenger'];
  1138.                                 $pieces_of_prices_law = [];
  1139.  
  1140.                                 // sequence 1
  1141.                                 if ($rtpl > 0) {
  1142.                                     if ($rtpl <= 25000000) {
  1143.                                         $pieces_of_prices_law[0] = $rtpl;
  1144.                                         $rtpl = 0;
  1145.                                     } else {
  1146.                                         $pieces_of_prices_law[0] = 25000000;
  1147.                                         $rtpl = $rtpl - 25000000;
  1148.                                     }
  1149.                                 }
  1150.  
  1151.                                 // sequence 2
  1152.                                 if ($rtpl > 0) {
  1153.                                     if ($rtpl <= 25000000) {
  1154.                                         $pieces_of_prices_law[1] = $rtpl;
  1155.                                         $rtpl = 0;
  1156.                                     } else {
  1157.                                         $pieces_of_prices_law[1] = 25000000;
  1158.                                         $rtpl = $rtpl - 25000000;
  1159.                                     }
  1160.                                 }
  1161.  
  1162.                                 // sequence 3
  1163.                                 if ($rtpl > 0) {
  1164.                                     if ($rtpl <= 50000000) {
  1165.                                         $pieces_of_prices_law[2] = $rtpl;
  1166.                                         $rtpl = 0;
  1167.                                     } else {
  1168.                                         $pieces_of_prices_law[2] = 50000000;
  1169.                                         $rtpl = $rtpl - 50000000;
  1170.                                     }
  1171.                                 }
  1172.  
  1173.  
  1174.                                 // sequence 4 sisanya
  1175.                                 if ($rtpl > 0) {
  1176.                                     $pieces_of_prices_law[3] = $rtpl;
  1177.                                     $rtpl = 0;
  1178.                                 }
  1179.  
  1180.                                 if (isset($pieces_of_prices_law[0])) {
  1181.                                     DB::statement('SET @passenger_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED)');
  1182.                                     $tpl = '@passenger_liability_one:=CAST((' . $pieces_of_prices_law[0] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['less_than_25'] . ' AS UNSIGNED) , ';
  1183.                                 } else {
  1184.                                     DB::statement('SET @passenger_liability_one:=0 ');
  1185.                                     $tpl .= '@passenger_liability_one:=0, ';
  1186.                                 }
  1187.                                 if (isset($pieces_of_prices_law[1])) {
  1188.                                     DB::statement('SET @passenger_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED)');
  1189.                                     $tpl .= '@passenger_liability_two:=CAST((' . $pieces_of_prices_law[1] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_25_and_less_than_50'] . ' AS UNSIGNED), ';
  1190.                                 } else {
  1191.                                     DB::statement('SET @passenger_liability_two:=0 ');
  1192.                                     $tpl .= '@passenger_liability_two:=0, ';
  1193.                                 }
  1194.                                 if (isset($pieces_of_prices_law[2])) {
  1195.                                     DB::statement('SET @passenger_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED)');
  1196.                                     $tpl .= '@passenger_liability_three:=CAST((' . $pieces_of_prices_law[2] . '/100)*' . $additioning['motorcycle']['responsibility_law_passenger']['more_than_50_and_less_than_100'] . ' AS UNSIGNED), ';
  1197.                                 } else {
  1198.                                     DB::statement('SET @passenger_liability_three:=0 ');
  1199.                                     $tpl .= '@passenger_liability_three:=0, ';
  1200.                                 }
  1201.                                 if (isset($pieces_of_prices_law[3])) {
  1202.                                     DB::statement('SET @passenger_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_law_passenger AS UNSIGNED) ');
  1203.                                     $tpl .= '@passenger_liability_four:=CAST((' . $pieces_of_prices_law[3] . '/100)*additional_coverages.responsibility_law_passenger AS UNSIGNED), ';
  1204.                                 } else {
  1205.                                     DB::statement('SET @passenger_liability_four:=0 ');
  1206.                                     $tpl .= '@third_party_liability_four:=0, ';
  1207.                                 }
  1208.  
  1209.                                 $tpl .= '@passenger_liability:=@passenger_liability_one+@passenger_liability_two+@passenger_liability_three+@passenger_liability_four, ';
  1210.                                 $sql .= $tpl;
  1211.                             }
  1212.  
  1213.                             if (isset($requests_additional['self_accident_for_driver'])) {
  1214.                                 $driver = '@driver:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  1215.                                     THEN (CASE WHEN additional_coverages.self_accident_for_driver IS NOT NULL THEN CAST(' . $additioning['motorcycle']['accident_driver'] . ' AS DECIMAL(3,2)) END)
  1216.                                     ELSE 0 END), ';
  1217.                                 $driver .= '@driver:=(' . $requests_additional['self_accident_for_driver'] . '/100)*@driver, ';
  1218.                                 if (!isset($requests_additional['self_accident_for_passenger'])) {
  1219.                                     $driver .= '@motorcycle_in:=@driver, ';
  1220.                                 }
  1221.                                 $sql .= $driver;
  1222.                             }
  1223.  
  1224.                             if (isset($requests_additional['self_accident_for_passenger'])) {
  1225.                                 $passenger = '@passengers:=(CASE WHEN additional_coverages.id IS NOT NULL AND additional_coverages.id > 0
  1226.                                     THEN (CASE WHEN additional_coverages.self_accident_for_passenger IS NOT NULL THEN CAST(' . $additioning['motorcycle']['accident_passenger'] . ' AS DECIMAL(3,2)) END)
  1227.                                     ELSE 0 END), ';
  1228.                                 $passenger .= '@passengers:=((' . $requests_additional['self_accident_for_passenger'] . '/100)*@passengers)*' . $requests_additional['passenger_seat'] . ', ';
  1229.                                 $passenger .= '@motorcycle_in:=IF(@driver IS NOT NULL, @driver+@passengers, @passengers), ';
  1230.                                 $sql .= $passenger;
  1231.                             }
  1232.  
  1233.                             $sql .= '@calculate:=(CASE WHEN @disaster IS NOT NULL AND @commotion IS NULL
  1234.                                                         THEN @disaster
  1235.                                                     WHEN @disaster IS NULL AND @commotion IS NOT NULL
  1236.                                                         THEN @commotion
  1237.                                                     WHEN @disaster IS NOT NULL AND @commotion IS NOT NULL
  1238.                                                         THEN @disaster+@commotion
  1239.                                                     ELSE 0 END), ';
  1240.  
  1241.                             $sql .= '@lawsuit:=(CASE WHEN @third_party_liability IS NOT NULL AND @passenger_liability IS NOT NULL
  1242.                                                         THEN @third_party_liability+@passenger_liability
  1243.                                                     WHEN @liability IS NULL AND @passenger_liability IS NOT NULL
  1244.                                                         THEN @passenger_liability
  1245.                                                     WHEN @third_party_liability IS NOT NULL AND @passenger_liability IS NULL
  1246.                                                         THEN @third_party_liability
  1247.                                                     ELSE 0 END), ';
  1248.  
  1249.                             // END OF ACCUMULATION ADDITIONAL !!!!!!!! ----------------------------------------------------------------------
  1250.  
  1251.                         }
  1252.                     } else {
  1253.                         $sql .= '@accumulation:=0, ';
  1254.                     }
  1255.                     $sql .= $amount_features . $percentages_features;
  1256.                     $sql .= '@percentage_feature_prices:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  1257.                                 THEN (@value_motorcycle/100)*@percentages_price
  1258.                                 ELSE 0 END), ';
  1259.  
  1260.                     // disini query harus ngeliat apa dia punya override atau gak, kalo emang gak, ya berarti di
  1261.                     // pake dong territorial ratenya, dan juga territory diliat lagi tipe zonenya
  1262.                     $sql .= '(CASE WHEN coverages.territory_custom_rate IS NULL THEN
  1263.                                 (CASE
  1264.                                     WHEN zone_territory.zone_id=1
  1265.                                         THEN (CASE WHEN coverages.territory_one_rate="top" THEN @percentages:=@zone_one_top
  1266.                                             WHEN coverages.territory_one_rate="bottom" THEN @percentages:=@zone_one_bottom
  1267.                                             ELSE @percentages:=CAST(coverages.territory_one_rate AS DECIMAL(15,2)) END)
  1268.                                     WHEN zone_territory.zone_id=2
  1269.                                         THEN (CASE WHEN coverages.territory_two_rate="top" THEN @percentages:=@zone_two_top
  1270.                                             WHEN coverages.territory_two_rate="bottom" THEN @percentages:=@zone_two_bottom
  1271.                                             ELSE @percentages:=CAST(coverages.territory_two_rate AS DECIMAL(15,2)) END)
  1272.                                     ELSE (CASE WHEN coverages.territory_three_rate="top" THEN @percentages:=@zone_three_top
  1273.                                             WHEN coverages.territory_three_rate="bottom" THEN @percentages:=@zone_three_bottom
  1274.                                             ELSE @percentages:=CAST(coverages.territory_three_rate AS DECIMAL(15,2)) END)
  1275.                                     END)
  1276.                                 ELSE @percentages:=CAST(coverages.territory_custom_rate AS DECIMAL(15,2))
  1277.                             END), ';
  1278.  
  1279.                     $sql .= '(CASE
  1280.                                 WHEN questionnaires.additional_year_condition<' . $gap_age . ' THEN @addons_percentages:=(questionnaires.additional_rate/100)
  1281.                                 ELSE @addons_percentages:=0
  1282.                             END), ';
  1283.  
  1284.                     $sql .= '@premx:=(@value_motorcycle/100)*(@percentages + (@percentages * @addons_percentages)), ';
  1285.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premx+@amount_price, @premx), ';
  1286.                     $sql .= '@premi:=IF(@percentage_feature_prices IS NOT NULL AND @percentage_feature_prices > 0, @premi+@percentage_feature_prices, @premi), ';
  1287.                     $sql .= '@premi:=IF(@calculate IS NOT NULL AND @calculate > 0, @premi+@calculate, @premi), ';
  1288.                     $sql .= '@premi:=IF(@lawsuit IS NOT NULL AND @lawsuit > 0, @premi+@lawsuit, @premi), ';
  1289.                     $sql .= '@premi:=IF(@motorcycle_in IS NOT NULL AND @motorcycle_in > 0, @premi+@motorcycle_in, @premi), ';
  1290.                     $sql .= $additional_fee_admin;
  1291.                     $sql .= $additional_fee_materai;
  1292.                     $sql .= '@premi:=ROUND(@premi+@admin_fee+@materai_fee), ';
  1293.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  1294.                     $sql .= 'product.id as product_id ';
  1295.  
  1296.                     $sql .= 'FROM insurance_product product ';
  1297.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_questionnaire_motorcycle) questionnaires ON questionnaires.product_id = product.id ';
  1298.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_motorcycle) features ON features.product_id = product.id ';
  1299.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_motorcycle_' . $query['level_of_insurance'] . ') coverages ON coverages.product_id = product.id ';
  1300.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_additional_motorcycle) additional_coverages ON additional_coverages.product_id = product.id ';
  1301.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  1302.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  1303.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  1304.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  1305.                     $sql .= 'LEFT JOIN (SELECT * FROM zone_territory_motorcycle) zone_territory ON true ';
  1306.  
  1307.                     $sql .= 'WHERE (';
  1308.  
  1309.                     unset($query['motorcycle_year']);
  1310.                     unset($query['motorcycle_year_brand']);
  1311.                     unset($query['motorcycle_year_brand_model']);
  1312.                     unset($query['motorcycle_year_brand_model_type']);
  1313.  
  1314.                     /*
  1315.                     foreach ($query as $key => $value) {
  1316.                         switch ($key) {
  1317.                             case 'motorcycle_value':
  1318.                                 $sql .= 'questionnaires.motorcycle_value_min IS NULL OR questionnaires.motorcycle_value_min < ' . $value . ' AND questionnaires.motorcycle_value_max IS NULL OR questionnaires.motorcycle_value_max > ' . $value . ' ';
  1319.                                 $sql .= '';
  1320.                                 break;
  1321.  
  1322.                             case 'motorcycle_set':
  1323.                                 $sql .= 'cav.motorcycle_additional_id = ' . $value . ' OR cav.motorcycle_additional_id IS NULL ';
  1324.                                 break;
  1325.  
  1326.                             case 'date_of_birth':
  1327.                                 $age            = calculateAge($value);
  1328.                                 $setcook['age'] = $age;
  1329.                                 $sql            .= 'questionnaires.age_min IS NULL OR questionnaires.age_min < ' . $age . ' AND questionnaires.age_max IS NULL OR questionnaires.age_max > ' . $age . ' ';
  1330.                                 break;
  1331.  
  1332.                             default:
  1333.                                 $sql .= 'questionnaires.' . $key . ' IS NULL OR questionnaires.' . $key . ' LIKE "%' . $value . '%" ';
  1334.                                 break;
  1335.                         }
  1336.  
  1337.                         if ($counter < count($query) - 1) {
  1338.                             $sql .= 'AND ';
  1339.                         }
  1340.                         $counter++;
  1341.                     }
  1342.                     */
  1343.                     $sql .= 'IF(questionnaires.motorcycle_value_min IS NOT NULL, questionnaires.motorcycle_value_min < ' . $query['motorcycle_value'] . ', questionnaires.motorcycle_value_min IS NULL) AND ';
  1344.                     $sql .= 'IF(questionnaires.motorcycle_value_max IS NOT NULL, questionnaires.motorcycle_value_max > ' . $query['motorcycle_value'] . ', questionnaires.motorcycle_value_max IS NULL) AND ';
  1345.                     $sql .= 'IF(questionnaires.age_vehicle_max IS NOT NULL, questionnaires.age_vehicle_max > ' . $gap_age . ', questionnaires.age_vehicle_max IS NULL) ';
  1346.                     break;
  1347.  
  1348.                 case 'property':
  1349.  
  1350.                     $sql .= '@zone:=0, ';
  1351.                     $sql .= '@others:=0, ';
  1352.                     DB::statement('SET @zone:=0 ');
  1353.                     DB::statement('SET @others:=0 ');
  1354.                     $yo_property = $query['level_of_insurance'];
  1355.                     // jika dia perhitungannya cuma content
  1356.                     if ($query['type_of_insurance'] == 'contents.only') {
  1357.                         $counting = $query['estimated_value_of_the_contents_to_cover'];
  1358.                     } else {
  1359.                         $counting = $query['estimated_value_of_the_property_to_cover'];
  1360.                     }
  1361.  
  1362.                     $sql .= $amount_features . $percentages_features;
  1363.                     $sql .= '@percentage_feature_prices:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  1364.                                 THEN (' . $counting . '/100)*@percentages_price
  1365.                                 ELSE 0 END), ';
  1366.  
  1367.                     if ($query['level_of_insurance'] == 'all_risk' or $query['level_of_insurance'] == 'standard') {
  1368.                         if ($query['level_of_insurance'] == 'all_risk') {
  1369.                             $additioning = $additionalController->all_risk['property'];
  1370.                             $rationing = $rateController->all['property'];
  1371.                             $yo_property = 'all';
  1372.  
  1373.                             //cuman buat all risk doang dia ada additional
  1374.                             if (isset($request['addition'])) {
  1375.                                 $requests_additional = json_decode($request['addition'], true);
  1376.                                 $count_request_additional = count($requests_additional);
  1377.                                 $setcook['addition'] = $requests_additional;
  1378.  
  1379.                                 if ($query['province'] == '3' or $query['province'] == 6 or $query['province'] == 9) {
  1380.                                     if (isset($requests_additional['around_jakarta_zone_one'])) {
  1381.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1382.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1383.                                                                 THEN CAST((' . $counting . '/100)*' . $additioning['around_jakarta_zone_one']['top'] . ' AS UNSIGNED)
  1384.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1385.                                                                 THEN CAST((' . $counting . '/100)*' . $additioning['around_jakarta_zone_one']['bottom'] . ' AS UNSIGNED)
  1386.                                                             ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2)) AS UNSIGNED)
  1387.                                                             END)
  1388.                                                     ELSE@zone:=0 END), ';
  1389.                                     } else if (isset($requests_additional['around_jakarta_zone_two'])) {
  1390.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1391.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1392.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1393.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1394.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1395.                                                             ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1396.                                                             END)
  1397.                                                     ELSE@zone:=0 END), ';
  1398.                                     } else if (isset($requests_additional['around_jakarta_zone_three'])) {
  1399.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1400.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1401.                                                                THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1402.                                                            WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1403.                                                                THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1404.                                                            ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1405.                                                            END)
  1406.                                                    ELSE@zone:=0 END), ';
  1407.                                     } else if (isset($requests_additional['around_jakarta_zone_four'])) {
  1408.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1409.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1410.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1411.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1412.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1413.                                                             ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1414.                                                             END)
  1415.                                                     ELSE@zone:=0 END), ';
  1416.                                     }
  1417.                                 } else {
  1418.                                     if (isset($requests_additional['outside_around_jakarta_zone_one'])) {
  1419.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_one IS NOT NULL)
  1420.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_one="top"
  1421.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_one']['top'] . ' AS UNSIGNED)
  1422.                                                          WHEN additional_coverages.outside_around_jakarta_zone_one="bottom"
  1423.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_one']['bottom'] . ' AS UNSIGNED)
  1424.                                                          ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.outside_around_jakarta_zone_one AS DECIMAL(8,2)) AS UNSIGNED)
  1425.                                                          END)
  1426.                                                     ELSE@zone:=0 END), ';
  1427.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_two'])) {
  1428.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1429.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1430.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_two']['top'] . ' AS UNSIGNED)
  1431.                                                         WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1432.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_two']['bottom'] . ' AS UNSIGNED)
  1433.                                                         ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2)) AS UNSIGNED)
  1434.                                                         END)
  1435.                                                     ELSE@zone:=0 END), ';
  1436.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_three'])) {
  1437.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1438.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1439.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['top'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1440.                                                          WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1441.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['bottom'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1442.                                                          ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1443.                                                          END)
  1444.                                                     ELSE@zone:=0 END), ';
  1445.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_four'])) {
  1446.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1447.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1448.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['top'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1449.                                                         WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1450.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['bottom'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1451.                                                         ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1452.                                                         END)
  1453.                                                     ELSE@zone:=0 END), ';
  1454.                                     }
  1455.                                 }
  1456.  
  1457.                                 if (isset($requests_additional['rsmd'])) {
  1458.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1459.                                                THEN @others:=(CASE WHEN additional_coverages.rsmd IS NOT NULL
  1460.                                                            THEN (' . $counting . '/100)*additional_coverages.rsmd
  1461.                                                        ELSE 0 END)
  1462.                                             ELSE @others:=@others END), ';
  1463.                                 }
  1464.                                 if (isset($requests_additional['cc'])) {
  1465.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1466.                                                THEN @others:=(CASE WHEN additional_coverages.cc IS NOT NULL
  1467.                                                        THEN @others+(' . $counting . '/100)*additional_coverages.cc
  1468.                                                    ELSE 0 END)
  1469.                                             ELSE @others:=@others END), ';
  1470.                                 }
  1471.                                 if (isset($requests_additional['other'])) {
  1472.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1473.                                                THEN @others:=(CASE WHEN additional_coverages.other IS NOT NULL
  1474.                                                        THEN @others+(' . $counting . '/100)*additional_coverages.other
  1475.                                                    ELSE 0 END)
  1476.                                             ELSE @others:=@others END), ';
  1477.                                 }
  1478.                             }
  1479.                         } else {
  1480.                             $additioning = $additionalController->all_risk['property'];
  1481.                             $rationing = $rateController->standard['property'];
  1482.                             $yo_property = 'standard';
  1483.  
  1484.                             //cuman buat all risk doang dia ada additional
  1485.                             if (isset($request['addition'])) {
  1486.                                 $requests_additional = json_decode($request['addition'], true);
  1487.                                 $count_request_additional = count($requests_additional);
  1488.                                 $setcook['addition'] = $requests_additional;
  1489.  
  1490.                                 if ($query['province'] == '3' or $query['province'] == 6 or $query['province'] == 9) {
  1491.                                     if (isset($requests_additional['around_jakarta_zone_one'])) {
  1492.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1493.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1494.                                                                 THEN CAST((' . $counting . '/100)*' . $additioning['around_jakarta_zone_one']['top'] . ' AS UNSIGNED)
  1495.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1496.                                                                 THEN CAST((' . $counting . '/100)*' . $additioning['around_jakarta_zone_one']['bottom'] . ' AS UNSIGNED)
  1497.                                                             ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2)) AS UNSIGNED)
  1498.                                                             END)
  1499.                                                     ELSE@zone:=0 END), ';
  1500.                                     } else if (isset($requests_additional['around_jakarta_zone_two'])) {
  1501.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1502.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1503.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1504.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1505.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1506.                                                             ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_two) AS UNSIGNED)
  1507.                                                             END)
  1508.                                                     ELSE@zone:=0 END), ';
  1509.                                     } else if (isset($requests_additional['around_jakarta_zone_three'])) {
  1510.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1511.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1512.                                                                THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1513.                                                            WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1514.                                                                THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1515.                                                            ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1516.                                                            END)
  1517.                                                    ELSE@zone:=0 END), ';
  1518.                                     } else if (isset($requests_additional['around_jakarta_zone_four'])) {
  1519.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.around_jakarta_zone_one IS NOT NULL)
  1520.                                                    THEN @zone:=(CASE WHEN additional_coverages.around_jakarta_zone_one="top"
  1521.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['top'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1522.                                                             WHEN additional_coverages.around_jakarta_zone_one="bottom"
  1523.                                                                 THEN CAST((' . $counting . '/100)*(' . $additioning['around_jakarta_zone_one']['bottom'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1524.                                                             ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.around_jakarta_zone_one AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1525.                                                             END)
  1526.                                                     ELSE@zone:=0 END), ';
  1527.                                     }
  1528.                                 } else {
  1529.                                     if (isset($requests_additional['outside_around_jakarta_zone_one'])) {
  1530.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_one IS NOT NULL)
  1531.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_one="top"
  1532.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_one']['top'] . ' AS UNSIGNED)
  1533.                                                          WHEN additional_coverages.outside_around_jakarta_zone_one="bottom"
  1534.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_one']['bottom'] . ' AS UNSIGNED)
  1535.                                                          ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.outside_around_jakarta_zone_one AS DECIMAL(8,2)) AS UNSIGNED)
  1536.                                                          END)
  1537.                                                     ELSE@zone:=0 END), ';
  1538.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_two'])) {
  1539.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1540.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1541.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_two']['top'] . ' AS UNSIGNED)
  1542.                                                         WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1543.                                                             THEN CAST((' . $counting . '/100)*' . $additioning['outside_around_jakarta_zone_two']['bottom'] . ' AS UNSIGNED)
  1544.                                                         ELSE CAST((' . $counting . '/100)*CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2)) AS UNSIGNED)
  1545.                                                         END)
  1546.                                                     ELSE@zone:=0 END), ';
  1547.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_three'])) {
  1548.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1549.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1550.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['top'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1551.                                                          WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1552.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['bottom'] . '+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1553.                                                          ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_three) AS UNSIGNED)
  1554.                                                          END)
  1555.                                                     ELSE@zone:=0 END), ';
  1556.                                     } else if (isset($requests_additional['outside_around_jakarta_zone_four'])) {
  1557.                                         $sql .= '(CASE WHEN (coverages.bundle_zone=0 AND additional_coverages.outside_around_jakarta_zone_two IS NOT NULL)
  1558.                                                    THEN @zone:=(CASE WHEN additional_coverages.outside_around_jakarta_zone_two="top"
  1559.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['top'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1560.                                                         WHEN additional_coverages.outside_around_jakarta_zone_two="bottom"
  1561.                                                             THEN CAST((' . $counting . '/100)*(' . $additioning['outside_around_jakarta_zone_two']['bottom'] . '+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1562.                                                         ELSE CAST((' . $counting . '/100)*(CAST(additional_coverages.outside_around_jakarta_zone_two AS DECIMAL(8,2))+additional_coverages.around_jakarta_zone_four) AS UNSIGNED)
  1563.                                                         END)
  1564.                                                     ELSE@zone:=0 END), ';
  1565.                                     }
  1566.                                 }
  1567.  
  1568.                                 if (isset($requests_additional['rsmd'])) {
  1569.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1570.                                                THEN @others:=(CASE WHEN additional_coverages.rsmd IS NOT NULL
  1571.                                                            THEN (' . $counting . '/100)*additional_coverages.rsmd
  1572.                                                        ELSE 0 END)
  1573.                                             ELSE @others:=@others END), ';
  1574.                                 }
  1575.                                 if (isset($requests_additional['cc'])) {
  1576.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1577.                                                THEN @others:=(CASE WHEN additional_coverages.cc IS NOT NULL
  1578.                                                        THEN @others+(' . $counting . '/100)*additional_coverages.cc
  1579.                                                    ELSE 0 END)
  1580.                                             ELSE @others:=@others END), ';
  1581.                                 }
  1582.                                 if (isset($requests_additional['other'])) {
  1583.                                     $sql .= '(CASE WHEN coverages.rsmd_zone=0
  1584.                                                THEN @others:=(CASE WHEN additional_coverages.other IS NOT NULL
  1585.                                                        THEN @others+(' . $counting . '/100)*additional_coverages.other
  1586.                                                    ELSE 0 END)
  1587.                                             ELSE @others:=@others END), ';
  1588.                                 }
  1589.                             }
  1590.                         }
  1591.  
  1592.                         $case_off = '';
  1593.                         $classer = [1 => 'class_one_rate', 2 => 'class_two_rate', 3 => 'class_three_rate'];
  1594.                         $variable = [
  1595.                             1 => 'below.6',
  1596.                             2 => 'in.6-18',
  1597.                             3 => 'up.to.18',
  1598.                             4 => 'park.up.to.24',
  1599.                             5 => 'less.than.3.storeys',
  1600.                             6 => 'boarding.house',
  1601.                             7 => 'floating',
  1602.                         ];
  1603.  
  1604.                         // jika ada construcation property query string
  1605.                         foreach ($variable as $key => $value) {
  1606.                             if ($query['class_property'] == $value) {
  1607.                                 if (isset($query['construction_property'])) {
  1608.                                     $case_off .= '@top:=' . $rationing[$key][$query['construction_property']]['top'] . ', ';
  1609.                                     DB::statement('SET @top:=' . $rationing[$key][$query['construction_property']]['top'] . '');
  1610.                                     $case_off .= '@bottom:=' . $rationing[$key][$query['construction_property']]['bottom'] . ', ';
  1611.                                     DB::statement('SET @bottom:=' . $rationing[$key][$query['construction_property']]['bottom'] . '');
  1612.                                 }
  1613.                             }
  1614.                         }
  1615.                         $sql .= $case_off;
  1616.                         $sql .= '@premi:=(CASE WHEN product.type_of_insurance="' . $query['level_of_insurance'] . '"
  1617.                                             THEN (CASE WHEN coverages.class_custom_rate IS NOT NULL AND coverages.class_custom_rate > 0
  1618.                                                     THEN (' . $counting . '/1000)*coverages.class_custom_rate
  1619.                                                 ELSE (CASE WHEN coverages.' . $classer[$query['construction_property']] . '="top"
  1620.                                                             THEN (' . $counting . '/1000)*@top
  1621.                                                         WHEN coverages.' . $classer[$query['construction_property']] . '="bottom"
  1622.                                                             THEN (' . $counting . '/1000)*@bottom
  1623.                                                         ELSE (' . $counting . '/1000)*coverages.' . $classer[$query['construction_property']] . ' END)
  1624.                                                 END)
  1625.                                 END), ';
  1626.                     } else {
  1627.                         $rationing = $rateController->earthquake['property'];
  1628.                         $yo_property = 'earthquake';
  1629.                         $case_off = '';
  1630.                         $classer = [1 => 'zone_one_rate', 2 => 'zone_two_rate', 3 => 'zone_three_rate', 4 => 'zone_four_rate', 5 => 'zone_five_rate'];
  1631.                         $limiting = [1 => [1 => 1],
  1632.                             2 => [1 => 1]];
  1633.  
  1634.                         $variable = [
  1635.                             1 => 'below.6',
  1636.                             2 => 'in.6-18',
  1637.                             3 => 'up.to.18',
  1638.                             4 => 'park.up.to.24',
  1639.                             5 => 'less.than.3.storeys',
  1640.                             6 => 'boarding.house',
  1641.                             7 => 'floating',
  1642.                         ];
  1643.  
  1644.                         // jika ada construcation property query string
  1645.                         if (isset($query['construction_property'])) {
  1646.                             $case_off .= '(CASE
  1647.                                            WHEN zone_territory.zone_id=1
  1648.                                              THEN (CASE WHEN coverages.' . $classer[1] . '="fixed"
  1649.                                                            THEN @fixed:=' . $rationing[$query['construction_property']][1][1]['fixed'] . '
  1650.                                                        ELSE @fixed:=coverages.' . $classer[1] . '
  1651.                                                    END)
  1652.  
  1653.                                            WHEN zone_territory.zone_id=2
  1654.                                              THEN (CASE WHEN coverages.' . $classer[2] . '="fixed"
  1655.                                                            THEN @fixed:=' . $rationing[$query['construction_property']][1][2]['fixed'] . '
  1656.                                                        ELSE @fixed:=coverages.' . $classer[2] . '
  1657.                                                    END)
  1658.                                            WHEN zone_territory.zone_id=3
  1659.                                              THEN (CASE WHEN coverages.' . $classer[3] . '="fixed"
  1660.                                                            THEN @fixed:=' . $rationing[$query['construction_property']][1][3]['fixed'] . '
  1661.                                                        ELSE @fixed:=coverages.' . $classer[3] . '
  1662.                                                    END)
  1663.                                            WHEN zone_territory.zone_id=4
  1664.                                              THEN (CASE WHEN coverages.' . $classer[4] . '="fixed"
  1665.                                                            THEN @fixed:=' . $rationing[$query['construction_property']][1][4]['fixed'] . '
  1666.                                                        ELSE @fixed:=coverages.' . $classer[4] . '
  1667.                                                    END)
  1668.                                            ELSE (CASE WHEN coverages.' . $classer[5] . '="fixed"
  1669.                                                            THEN @fixed:=' . $rationing[$query['construction_property']][1][5]['fixed'] . '
  1670.                                                    ELSE @fixed:=coverages.' . $classer[5] . '
  1671.                                                 END)
  1672.                                            END), ';
  1673.                         }
  1674.  
  1675.                         $sql .= $case_off;
  1676.                         $sql .= '@premi:=(CASE WHEN product.type_of_insurance="' . $query['level_of_insurance'] . '"
  1677.                                             THEN (CASE WHEN coverages.zone_custom_rate IS NOT NULL AND coverages.zone_custom_rate > 0
  1678.                                                     THEN (' . $counting . '/1000)*coverages.zone_custom_rate
  1679.                                                 ELSE (' . $counting . '/1000)*@fixed END)
  1680.                                         END), ';
  1681.                     }
  1682.  
  1683.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premi+@amount_price, @premi), ';
  1684.                     $sql .= '@premi:=IF(@percentage_feature_prices IS NOT NULL AND @percentage_feature_prices > 0, @premi+@percentage_feature_prices, @premi), ';
  1685.                     $sql .= '@premi:=@premi+@others, ';
  1686.                     $sql .= '@premi:=@premi+@zone, ';
  1687.                     $sql .= $additional_fee_admin;
  1688.                     $sql .= $additional_fee_materai;
  1689.                     $sql .= '@premi:=ROUND(@premi+@admin_fee+@materai_fee), ';
  1690.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  1691.                     $sql .= 'product.id as product_id ';
  1692.  
  1693.                     $sql .= 'FROM insurance_product product ';
  1694.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_questionnaire_property) questionnaires ON questionnaires.product_id = product.id ';
  1695.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_property) features ON features.product_id = product.id ';
  1696.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_property_fire_' . $yo_property . ') coverages ON coverages.product_id = product.id ';
  1697.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_additional_property) as additional_coverages ON additional_coverages.product_id = product.id ';
  1698.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  1699.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  1700.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  1701.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  1702.                     $sql .= 'LEFT JOIN (SELECT * FROM zone_territory_earthquake) zone_territory ON true ';
  1703.  
  1704.                     $sql .= 'WHERE (';
  1705.                     $level_of_insurance = $query['level_of_insurance'];
  1706.                     $construction_property = $query['construction_property'];
  1707.                     if (isset($query['class_property'])) {
  1708.                         $class_property = $query['class_property'];
  1709.                     }
  1710.                     unset($query['level_of_insurance']);
  1711.                     unset($query['class_property']);
  1712.                     unset($query['type_of_insurance']);
  1713.  
  1714.                     $sql .= 'IF(questionnaires.what_type_of_the_property IS NOT NULL, questionnaires.what_type_of_the_property LIKE "%' . $query['what_type_of_the_property'] . '%", questionnaires.what_type_of_the_property IS NULL) AND ';
  1715.                     $sql .= 'IF(questionnaires.why_are_you_looking_for_cover IS NOT NULL, questionnaires.why_are_you_looking_for_cover LIKE "%' . $query['why_are_you_looking_for_cover'] . '%", questionnaires.why_are_you_looking_for_cover IS NULL) AND ';
  1716.  
  1717.                     switch((integer)$query['construction_property']){
  1718.                         case 1:
  1719.                             $cons_class = 'one';
  1720.                             break;
  1721.                         case 2:
  1722.                             $cons_class = 'two';
  1723.                             break;
  1724.                         case 3:
  1725.                             $cons_class = 'three';
  1726.                             break;
  1727.                     }
  1728.  
  1729.                     // tambah lagi class construction
  1730.                     if ($level_of_insurance == 'all_risk' or $level_of_insurance == 'standard') {
  1731.                         $var = 'flexas_class_construction_'.$cons_class;
  1732.                         $sql .= 'IF(questionnaires.flexas_class_construction IS NOT NULL, questionnaires.flexas_class_construction LIKE "%' . $var . '%", questionnaires.flexas_class_construction IS NULL) ';
  1733.                     } else {
  1734.                         $var = 'earthquake_class_construction_'.$cons_class;
  1735.                         $sql .= 'IF(questionnaires.earthquake_class_construction IS NOT NULL, questionnaires.earthquake_class_construction LIKE "%' . $var . '%", questionnaires.earthquake_class_construction IS NULL) ';
  1736.                     }
  1737.                     break;
  1738.  
  1739.                 case 'personal-accident':
  1740.                     $sql = 'SELECT product.*, product_detail.*, product_meta.*, features.*, features.count as count, questionnaires.claim, ';
  1741.                     $sql .= $amount_features . $percentages_features;
  1742.  
  1743.                     switch ($query['type_of_work']) {
  1744.                         case 'one':
  1745.                             $sql .= '@coverages_main:=coverages.class_one_rate, ';
  1746.                             break;
  1747.  
  1748.                         case 'two':
  1749.                             $sql .= '@coverages_main:=coverages.class_two_rate, ';
  1750.                             break;
  1751.  
  1752.                         case 'three':
  1753.                             $sql .= '@coverages_main:=coverages.class_three_rate, ';
  1754.                             break;
  1755.  
  1756.                         case 'four':
  1757.                             $sql .= '@coverages_main:=coverages.class_four_rate, ';
  1758.                             break;
  1759.  
  1760.                         default:
  1761.                             $sql .= '@coverages_main:=coverages.class_five_rate, ';
  1762.                             break;
  1763.                     }
  1764.                     $use_calc = '@premi:=@coverages_main, ';
  1765.  
  1766.                     if ($query['type_of_work_couple'] != '' and $query['type_of_cover'] == 'couple') {
  1767.                         switch ($query['type_of_work_couple']) {
  1768.                             case 'one':
  1769.                                 $sql .= '@coverages_other:=coverages_detail.class_one_rate, ';
  1770.                                 break;
  1771.  
  1772.                             case 'two':
  1773.                                 $sql .= '@coverages_other:=coverages_detail.class_two_rate, ';
  1774.                                 break;
  1775.  
  1776.                             case 'three':
  1777.                                 $sql .= '@coverages_other:=coverages_detail.class_three_rate, ';
  1778.                                 break;
  1779.  
  1780.                             case 'four':
  1781.                                 $sql .= '@coverages_other:=coverages_detail.class_four_rate, ';
  1782.                                 break;
  1783.  
  1784.                             default:
  1785.                                 $sql .= '@coverages_other:=coverages_detail.class_five_rate, ';
  1786.                                 break;
  1787.                         }
  1788.                         $use_calc = '@premi:=@coverages_main+@coverages_other, ';
  1789.                     }
  1790.                     $sql .= $use_calc;
  1791.  
  1792.                     $sql .= '@percentage_feature_prices:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  1793.                                 THEN (@premi/100)*@percentages_price
  1794.                                 ELSE 0 END), ';
  1795.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premi+@amount_price, @premi), ';
  1796.                     $sql .= '@premi:=IF(@percentage_feature_prices IS NOT NULL AND @percentage_feature_prices > 0, @premi+@percentage_feature_prices, @premi), ';
  1797.                     $sql .= $additional_fee_admin;
  1798.                     $sql .= $additional_fee_materai;
  1799.                     $sql .= '@premi:=@premi+@admin_fee+@materai_fee, ';
  1800.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  1801.                     $sql .= 'product.id as product_id ';
  1802.  
  1803.                     $sql .= 'FROM insurance_product product ';
  1804.                     $sql .= 'LEFT JOIN (SELECT *,';
  1805.                     $sql .= 'CASE WHEN label_claim_two IS NOT NULL AND (amount_claim_two > amount_claim_one AND amount_claim_two > amount_claim_three AND amount_claim_two > amount_claim_four AND amount_claim_two > amount_claim_five )THEN @claim:=amount_claim_two
  1806.                                 WHEN label_claim_three IS NOT NULL AND (amount_claim_three > amount_claim_one AND amount_claim_three > amount_claim_two AND amount_claim_three > amount_claim_four AND amount_claim_three > amount_claim_five )THEN @claim:=amount_claim_three
  1807.                                 WHEN label_claim_four IS NOT NULL AND (amount_claim_four > amount_claim_one AND amount_claim_four > amount_claim_two AND amount_claim_four > amount_claim_three AND amount_claim_four > amount_claim_five )THEN @claim:=amount_claim_four
  1808.                                 WHEN label_claim_five IS NOT NULL AND (amount_claim_five > amount_claim_one AND amount_claim_five > amount_claim_two AND amount_claim_five > amount_claim_three AND amount_claim_five > amount_claim_four )THEN @claim:=amount_claim_five
  1809.                                 ELSE @claim:=amount_claim_one END AS claim ';
  1810.                     $sql .= 'FROM insurance_questionnaire_personal_accident) questionnaires ON questionnaires.product_id = product.id ';
  1811.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_personal_accident) features ON features.product_id = product.id ';
  1812.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_self_accident) coverages ON coverages.product_id = product.id ';
  1813.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_self_accident_other) coverages_detail ON coverages_detail.product_id = product.id ';
  1814.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  1815.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  1816.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  1817.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  1818.  
  1819.                     $sql .= 'WHERE (';
  1820. //                  $value_of_cover = $query['value_of_cover'];
  1821.  
  1822.                     unset($query['product_level']);
  1823.                     unset($query['value_of_cover']);
  1824.                     /*foreach ($query as $key => $value) {
  1825.                         switch ($key) {
  1826.                             default:
  1827.                                 $sql .= 'questionnaires.' . $key . ' IS NULL OR questionnaires.' . $key . ' LIKE "%' . $value . '%" ';
  1828.                                 break;
  1829.                         }
  1830.  
  1831.                         if ($counter < count($query) - 1) {
  1832.                             if ($value != '') {
  1833.                                 $sql .= 'AND ';
  1834.                             }
  1835.                         }
  1836.                         $counter++;
  1837.                     }
  1838.                     */
  1839.  
  1840.                     $sql .= 'IF(questionnaires.type_of_cover IS NOT NULL, questionnaires.type_of_cover LIKE "%' . $query['type_of_cover'] . '%", questionnaires.type_of_cover IS NULL) AND ';
  1841.                     $sql .= 'IF(questionnaires.type_of_work IS NOT NULL, questionnaires.type_of_work LIKE "%' . $query['type_of_work'] . '%", questionnaires.type_of_work IS NULL) AND ';
  1842.                     //$sql .= 'IF(questionnaires.warranty_status IS NOT NULL, questionnaires.warranty_status LIKE "%' . $query['warranty_status'] . '%", questionnaires.warranty_status IS NULL) AND ';
  1843.                     $sql .= 'IF(questionnaires.gender IS NOT NULL, questionnaires.gender = "' . $query['gender'] . '" OR questionnaires.gender = "male.or.female", questionnaires.gender IS NULL) ';
  1844.                     break;
  1845.  
  1846.                 case 'travel':
  1847.                     $sql = 'SELECT product.*,
  1848.                                product_detail.*,
  1849.                                product_meta.*,
  1850.                                features.*,
  1851.                                features.count as count,
  1852.                                questionnaires.*, ';
  1853.  
  1854.                     $arrival = date_create(str_replace('/', '-', $query['arrival_date']));
  1855.                     $departure = date_create(str_replace('/', '-', $query['departure_date']));
  1856.                     $date_diff = date_diff($arrival, $departure);
  1857.                     $add_one_date_diff = $date_diff->format('%a') + 1;
  1858.                     $week_diff = ceil($add_one_date_diff / 7);
  1859.                     $sql .= $amount_features . $percentages_features;
  1860.  
  1861.                     if ($query['who_is_the_insurance_for'] != 'family') {
  1862.                         $people = ['just.me' => 'one_person', 'couple' => 'two_person'];
  1863.                         $people = $people[$query['who_is_the_insurance_for']];
  1864.                         $extra = 'extra_' . $people;
  1865.                         $select = $people;
  1866.                     } else {
  1867.                         $counted = [3 => 'three_person', 4 => 'four_person', 5 => 'five_person'];
  1868.                         $people = $counted[(integer)$query['group_count']];
  1869.                         $extra = 'extra_' . $people;
  1870.                         $select = $people;
  1871.                     }
  1872.  
  1873.                     if ($query['trip_type'] != 'annual.trip') {
  1874.                         switch ($query['travel_category']) {
  1875.                             case 'asean':
  1876.                                 $sql .= '@premi:=(CASE
  1877.                                            -- Gua ngambil dulu days_min tertinggi abis itu limit 1.
  1878.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_asean where product_id = product.id AND days_min <' . $add_one_date_diff . ')
  1879.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_asean WHERE product_id = product.id AND days_min <' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1880.  
  1881.                                            -- Disiini days_min yang emang udah pas, gak kurang gak lebih, jadi di kondisi ke satu itu kondisi dimana days_min masih lebih besar
  1882.                                            -- disini kondisi dimana days_min sesuai dan pas gak kurang gak lebih
  1883.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_asean where product_id = product.id AND days_min = ' . $add_one_date_diff . ')
  1884.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_asean WHERE product_id = product.id AND days_min = ' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1885.  
  1886.                                            -- Selain itu ada kondisi tambahan, jika dia punya extra weekly maka premi bakalan ditambahain sesuai weekly
  1887.                                            -- kalo emang days atau daily, ditambahain perharian selain itu NULL
  1888.                                            ELSE
  1889.                                                (CASE WHEN EXISTS (SELECT 1 from insurance_coverage_travel_asean WHERE product_id = product.id AND (extra = "weekly" AND extra IS NOT NULL))
  1890.                                                        THEN (SELECT ' . $people . '+(ceil((' . $add_one_date_diff . '-days_min)/7)*' . $extra . ') from insurance_coverage_travel_asean WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1 )
  1891.                                                    WHEN EXISTS (SELECT 1 from insurance_coverage_travel_asean WHERE product_id = product.id AND (extra = "days" OR extra = "daily" AND extra IS NOT NULL))
  1892.                                                        THEN (SELECT ' . $people . '+((' . $add_one_date_diff . '-days_min)*' . $extra . ') from insurance_coverage_travel_asean WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1)
  1893.                                                    ELSE NULL
  1894.                                                 END)
  1895.                                            END) AS premi, ';
  1896.                                 break;
  1897.                             case 'asia':
  1898.                                 $sql .= '@premi:=(CASE
  1899.                                            -- Gua ngambil dulu days_min tertinggi abis itu limit 1.
  1900.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_asia where product_id = product.id AND days_min <' . $add_one_date_diff . ')
  1901.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_asia WHERE product_id = product.id AND days_min <' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1902.  
  1903.                                            -- Disiini days_min yang emang udah pas, gak kurang gak lebih, jadi di kondisi ke satu itu kondisi dimana days_min masih lebih besar
  1904.                                            -- disini kondisi dimana days_min sesuai dan pas gak kurang gak lebih
  1905.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_asia where product_id = product.id AND days_min = ' . $add_one_date_diff . ')
  1906.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_asia WHERE product_id = product.id AND days_min = ' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1907.  
  1908.                                            -- Selain itu ada kondisi tambahan, jika dia punya extra weekly maka premi bakalan ditambahain sesuai weekly
  1909.                                            -- kalo emang days atau daily, ditambahain perharian selain itu NULL
  1910.                                            ELSE
  1911.                                                (CASE WHEN EXISTS (SELECT 1 from insurance_coverage_travel_asia WHERE product_id = product.id AND (extra = "weekly" AND extra IS NOT NULL))
  1912.                                                        THEN (SELECT ' . $people . '+(ceil((' . $add_one_date_diff . '-days_min)/7)*' . $extra . ') from insurance_coverage_travel_asia WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1 )
  1913.                                                    WHEN EXISTS (SELECT 1 from insurance_coverage_travel_asia WHERE product_id = product.id AND (extra = "days" OR extra = "daily" AND extra IS NOT NULL))
  1914.                                                        THEN (SELECT ' . $people . '+((' . $add_one_date_diff . '-days_min)*' . $extra . ') from insurance_coverage_travel_asia WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1)
  1915.                                                    ELSE NULL
  1916.                                                 END)
  1917.                                            END) AS premi, ';
  1918.                                 break;
  1919.                             case 'worldwide_incl_shenzeng':
  1920.                                 $sql .= '@premi:=(CASE
  1921.                                            -- Gua ngambil dulu days_min tertinggi abis itu limit 1.
  1922.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_wwis where product_id = product.id AND days_min <' . $add_one_date_diff . ')
  1923.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_wwis WHERE product_id = product.id AND days_min <' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1924.  
  1925.                                            -- Disiini days_min yang emang udah pas, gak kurang gak lebih, jadi di kondisi ke satu itu kondisi dimana days_min masih lebih besar
  1926.                                            -- disini kondisi dimana days_min sesuai dan pas gak kurang gak lebih
  1927.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_wwis where product_id = product.id AND days_min = ' . $add_one_date_diff . ')
  1928.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_wwis WHERE product_id = product.id AND days_min = ' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1929.  
  1930.                                            -- Selain itu ada kondisi tambahan, jika dia punya extra weekly maka premi bakalan ditambahain sesuai weekly
  1931.                                            -- kalo emang days atau daily, ditambahain perharian selain itu NULL
  1932.                                            ELSE
  1933.                                                (CASE WHEN EXISTS (SELECT 1 from insurance_coverage_travel_wwis WHERE product_id = product.id AND (extra = "weekly" AND extra IS NOT NULL))
  1934.                                                        THEN (SELECT ' . $people . '+(ceil((' . $add_one_date_diff . '-days_min)/7)*' . $extra . ') from insurance_coverage_travel_wwis WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1 )
  1935.                                                    WHEN EXISTS (SELECT 1 from insurance_coverage_travel_wwis WHERE product_id = product.id AND (extra = "days" OR extra = "daily" AND extra IS NOT NULL))
  1936.                                                        THEN (SELECT ' . $people . '+((' . $add_one_date_diff . '-days_min)*' . $extra . ') from insurance_coverage_travel_wwis WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1)
  1937.                                                    ELSE NULL
  1938.                                                 END)
  1939.                                            END) AS premi, ';
  1940.                                 break;
  1941.                             case 'worldwide_excl_shenzeng':
  1942.                                 $sql .= '@premi:=(CASE
  1943.                                            -- Gua ngambil dulu days_min tertinggi abis itu limit 1.
  1944.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_wwes where product_id = product.id AND days_min <' . $add_one_date_diff . ')
  1945.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_wwes WHERE product_id = product.id AND days_min <' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1946.  
  1947.                                            -- Disiini days_min yang emang udah pas, gak kurang gak lebih, jadi di kondisi ke satu itu kondisi dimana days_min masih lebih besar
  1948.                                            -- disini kondisi dimana days_min sesuai dan pas gak kurang gak lebih
  1949.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_wwes where product_id = product.id AND days_min = ' . $add_one_date_diff . ')
  1950.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_wwes WHERE product_id = product.id AND days_min = ' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1951.  
  1952.                                            -- Selain itu ada kondisi tambahan, jika dia punya extra weekly maka premi bakalan ditambahain sesuai weekly
  1953.                                            -- kalo emang days atau daily, ditambahain perharian selain itu NULL
  1954.                                            ELSE
  1955.                                                (CASE WHEN EXISTS (SELECT 1 from insurance_coverage_travel_wwes WHERE product_id = product.id AND (extra = "weekly" AND extra IS NOT NULL))
  1956.                                                        THEN (SELECT ' . $people . '+(ceil((' . $add_one_date_diff . '-days_min)/7)*' . $extra . ') from insurance_coverage_travel_wwes WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1 )
  1957.                                                    WHEN EXISTS (SELECT 1 from insurance_coverage_travel_wwes WHERE product_id = product.id AND (extra = "days" OR extra = "daily" AND extra IS NOT NULL))
  1958.                                                        THEN (SELECT ' . $people . '+((' . $add_one_date_diff . '-days_min)*' . $extra . ') from insurance_coverage_travel_wwes WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1)
  1959.                                                    ELSE NULL
  1960.                                                 END)
  1961.                                            END) AS premi, ';
  1962.                                 break;
  1963.                             default:
  1964.                                 $sql .= '@premi:=(CASE
  1965.                                            -- Gua ngambil dulu days_min tertinggi abis itu limit 1.
  1966.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_domestic where product_id = product.id AND days_min <' . $add_one_date_diff . ')
  1967.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_domestic WHERE product_id = product.id AND days_min <' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1968.  
  1969.                                            -- Disiini days_min yang emang udah pas, gak kurang gak lebih, jadi di kondisi ke satu itu kondisi dimana days_min masih lebih besar
  1970.                                            -- disini kondisi dimana days_min sesuai dan pas gak kurang gak lebih
  1971.                                            WHEN EXISTS(SELECT 1 from insurance_coverage_travel_domestic where product_id = product.id AND days_min = ' . $add_one_date_diff . ')
  1972.                                                THEN (SELECT ' . $select . ' from insurance_coverage_travel_domestic WHERE product_id = product.id AND days_min = ' . $add_one_date_diff . ' ORDER BY `days_min` DESC LIMIT 1 )
  1973.  
  1974.                                            -- Selain itu ada kondisi tambahan, jika dia punya extra weekly maka premi bakalan ditambahain sesuai weekly
  1975.                                            -- kalo emang days atau daily, ditambahain perharian selain itu NULL
  1976.                                            ELSE
  1977.                                                (CASE WHEN EXISTS (SELECT 1 from insurance_coverage_travel_domestic WHERE product_id = product.id AND (extra = "weekly" AND extra IS NOT NULL))
  1978.                                                        THEN (SELECT ' . $people . '+(ceil((' . $add_one_date_diff . '-days_min)/7)*' . $extra . ') from insurance_coverage_travel_domestic WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1 )
  1979.                                                    WHEN EXISTS (SELECT 1 from insurance_coverage_travel_domestic WHERE product_id = product.id AND (extra = "days" OR extra = "daily" AND extra IS NOT NULL))
  1980.                                                        THEN (SELECT ' . $people . '+((' . $add_one_date_diff . '-days_min)*' . $extra . ') from insurance_coverage_travel_domestic WHERE product_id = product.id ORDER BY days_min DESC LIMIT 1)
  1981.                                                    ELSE NULL
  1982.                                                 END)
  1983.                                            END) AS premi, ';
  1984.                                 break;
  1985.                         }
  1986.                         $dump = '';
  1987.                     } else {
  1988.                         $annual = ['asean' => 'asean', 'asia' => 'asia', 'domestic' => 'domestic', 'worldwide_incl_shenzeng' => 'wwis', 'worldwide_excl_shenzeng' => 'wwes'];
  1989.                         $sql .= '@premi:=(SELECT ' . $people . ' from insurance_coverage_travel_annual WHERE product_id = product.id AND type="' . $annual[$query['travel_category']] . '" LIMIT 1) AS premi, ';
  1990.                         $dump = 'AND (SELECT ' . $people . ' from insurance_coverage_travel_annual WHERE product_id = product.id AND type="' . $annual[$query['travel_category']] . '" LIMIT 1) IS NOT NULL AND (SELECT ' . $people . ' from insurance_coverage_travel_annual WHERE product_id = product.id AND type="' . $annual[$query['travel_category']] . '" LIMIT 1) > 0 ';
  1991.                     }
  1992.                     $sql .= '@percentage_feature_prices:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  1993.                                 THEN (@premi/100)*@percentages_price
  1994.                                 ELSE 0 END), ';
  1995.  
  1996.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premi+@amount_price, @premi), ';
  1997.                     $sql .= '@premi:=IF(@percentage_feature_prices IS NOT NULL AND @percentage_feature_prices > 0, @premi+@percentage_feature_prices, @premi), ';
  1998.                     $sql .= $additional_fee_admin;
  1999.                     $sql .= $additional_fee_materai;
  2000.                     $sql .= '@premi:=@premi+@admin_fee+@materai_fee, ';
  2001.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  2002.                     $sql .= 'product.id as product_id ';
  2003.  
  2004.                     $sql .= 'FROM insurance_product product ';
  2005.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_questionnaire_travel) questionnaires ON questionnaires.product_id = product.id ';
  2006.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_travel) features ON features.product_id = product.id ';
  2007.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  2008.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  2009.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  2010.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  2011.                     $sql .= 'WHERE (';
  2012.                     $ab = 'IF(questionnaires.product_level IS NOT NULL, questionnaires.product_level LIKE "%' . $query['product_level'] . '%", questionnaires.product_level IS NULL) ' . $dump;
  2013.  
  2014.                     unset($query['product_level']);
  2015.                     unset($query['country']);
  2016.                     unset($query['travel_province']);
  2017.                     unset($query['travel_city']);
  2018. //                    unset($query['travel_category']);
  2019.                     unset($query['departure_date']);
  2020.                     unset($query['arrival_date']);
  2021.                     unset($query['group_count']);
  2022.  
  2023.                     $sql .= 'IF(questionnaires.who_is_the_insurance_for IS NOT NULL, questionnaires.who_is_the_insurance_for LIKE "%' . $query['who_is_the_insurance_for'] . '%", questionnaires.who_is_the_insurance_for IS NULL) AND ';
  2024.                     $sql .= 'IF(questionnaires.coverage_level IS NOT NULL, questionnaires.coverage_level LIKE "%' . str_replace('_', '.', $query['travel_category']) . '%", questionnaires.coverage_level IS NULL) AND ';
  2025.                     $sql .= 'IF(questionnaires.travel_category IS NOT NULL, questionnaires.travel_category LIKE "%' . $query['travel_category'] . '%", questionnaires.travel_category IS NULL) ';
  2026.                     break;
  2027.  
  2028.                 case 'health':
  2029.                     $sql = 'SELECT product.*,
  2030.                                product_detail.*,
  2031.                                product_meta.*,
  2032.                                features.*,
  2033.                                features.count as count,
  2034.                                questionnaires.*, ';
  2035.  
  2036.                     $ab = '';
  2037.                     $fams = '';
  2038.                     $now = date_create(date('Y-m-d'));
  2039.                     $index = 0;
  2040.  
  2041.                     if ($query['who_need_the_cover'] == 'couple') {
  2042.                         $birth = [
  2043.                             'guy' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_guy'])))),
  2044.                             'girl' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_girl'])))),
  2045.                         ];
  2046.                         unset($query['couple_guy']);
  2047.                         unset($query['couple_girl']);
  2048.  
  2049.                         $zz = 0;
  2050.                         $counter_birth = count($birth) - 1;
  2051.                         // di loop aja biar singkat
  2052.                         foreach ($birth as $k => $v) {
  2053.                             if ($k == 'guy') {
  2054.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2055.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2056.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2057.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2058.  
  2059.                                 // absolute searches for main
  2060.                                 $ab .= 'coverages.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2061.                                 $ab .= 'coverages.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2062.                             } else {
  2063.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2064.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2065.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2066.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2067.  
  2068.                                 $ab .= 'coverage_others.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2069.                                 $ab .= 'coverage_others.limitation >= ' . date_diff($now, $v)->y . ' ';
  2070.                                 if ($zz < $counter_birth - 1) {
  2071.                                     $ab .= 'AND ';
  2072.                                 }
  2073.                                 $zz++;
  2074.                             }
  2075.                         }
  2076.  
  2077.                         $sql .= '@premi:=@guy_yearly+@girl_yearly, ';
  2078.                         $sql .= '@semester:=@guy_semester+@girl_semester, ';
  2079.                         $sql .= '@quartal:=@guy_quartal+@girl_quartal, ';
  2080.                         $sql .= '@monthly:=@guy_monthly+@girl_monthly, ';
  2081.                     } elseif ($query['who_need_the_cover'] == 'family') {
  2082.                         $birth = [
  2083.                             'husband' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_husband'])))),
  2084.                             'wife' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_wife'])))),
  2085.                         ];
  2086.  
  2087.                         $children = [1, 2, 3, 4];
  2088.                         foreach ($children as $kid) {
  2089.                             if (isset($query['family_children_' . $kid])) {
  2090.                                 $birth['kid_' . $kid] = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_children_' . $kid]))));
  2091.                                 unset($query['family_children_' . $kid]);
  2092.                             }
  2093.                             unset($query['family_husband']);
  2094.                             unset($query['family_wife']);
  2095.                         }
  2096.  
  2097.                         $zz = 0;
  2098.                         $fam_yearly = '';
  2099.                         $fam_semester = '';
  2100.                         $fam_quartal = '';
  2101.                         $fam_monthly = '';
  2102.                         $counter_birth = count($birth) - 2;
  2103.  
  2104.                         foreach ($birth as $k => $v) {
  2105.                             if ($k == 'husband') {
  2106.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2107.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2108.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2109.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2110.                                 $ab .= 'coverages.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2111.                                 $ab .= 'coverages.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2112.  
  2113.                                 $fam_yearly .= '@' . $k . '_yearly+';
  2114.                                 $fam_semester .= '@' . $k . '_semester+';
  2115.                                 $fam_quartal .= '@' . $k . '_quartal+';
  2116.                                 $fam_monthly .= '@' . $k . '_monthly+';
  2117.  
  2118.                             } elseif ($k == 'wife') {
  2119.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2120.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2121.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2122.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2123.                                 $ab .= 'coverage_others.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2124.                                 $ab .= 'coverage_others.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2125.  
  2126.                                 $fam_yearly .= '@' . $k . '_yearly+';
  2127.                                 $fam_semester .= '@' . $k . '_semester+';
  2128.                                 $fam_quartal .= '@' . $k . '_quartal+';
  2129.                                 $fam_monthly .= '@' . $k . '_monthly+';
  2130.  
  2131.                             } else {
  2132.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_health_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2133.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2134.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2135.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2136.                                 $ab .= 'coverage_childrens.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2137.                                 $ab .= 'coverage_childrens.limitation >= ' . date_diff($now, $v)->y . ' ';
  2138.  
  2139.                                 $fam_yearly .= '@' . $k . '_yearly';
  2140.                                 $fam_semester .= '@' . $k . '_semester';
  2141.                                 $fam_quartal .= '@' . $k . '_quartal';
  2142.                                 $fam_monthly .= '@' . $k . '_monthly';
  2143.                                 if ($zz < $counter_birth - 1) {
  2144.                                     $fam_yearly .= '+';
  2145.                                     $fam_semester .= '+';
  2146.                                     $fam_quartal .= '+';
  2147.                                     $fam_monthly .= '+';
  2148.                                     $ab .= 'AND ';
  2149.                                 }
  2150.                                 $zz++;
  2151.                             }
  2152.                         }
  2153.  
  2154.                         $sql .= '@premi:=' . $fam_yearly . ', ';
  2155.                         $sql .= '@semester:=' . $fam_semester . ', ';
  2156.                         $sql .= '@quartal:=' . $fam_quartal . ', ';
  2157.                         $sql .= '@monthly:=' . $fam_monthly . ', ';
  2158.  
  2159.                     } else {
  2160.                         $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['single_date']))));
  2161.                         $sql .= '@single_yearly:=(SELECT yearly_rates FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2162.                         $sql .= '@single_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2163.                         $sql .= '@single_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2164.                         $sql .= '@single_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_health WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2165.  
  2166.                         $sql .= '@premi:=@single_yearly, ';
  2167.                         $sql .= '@semester:=@single_semester, ';
  2168.                         $sql .= '@quartal:=@single_quartal, ';
  2169.                         $sql .= '@monthly:=@single_monthly, ';
  2170.                         $ab .= 'coverages.age_min <= ' . date_diff($now, $birth)->y . ' AND ';
  2171.                         $ab .= 'coverages.limitation >= ' . date_diff($now, $birth)->y . ' ';
  2172.                         unset($query['single_date']);
  2173.                     }
  2174.                     $sql .= $amount_features . $percentages_features;
  2175.  
  2176.                     $sql .= $additional_fee_admin;
  2177.                     $sql .= $additional_fee_materai;
  2178.                     $sql .= '@premi:=@premi+@admin_fee+@materai_fee, ';
  2179.                     $sql .= 'IF(@semester > 0, @semester:=@semester+@admin_fee+@materai_fee, @semester:=0), ';
  2180.                     $sql .= 'IF(@quartal > 0, @quartal:=@quartal+@admin_fee+@materai_fee, @quartal:=0), ';  
  2181.                     $sql .= 'IF(@monthly > 0, @monthly:=@monthly+@admin_fee+@materai_fee, @monthly:=0), ';
  2182.  
  2183.                     /*
  2184.                     // FEATURE ADDITIONAL
  2185.                     $sql .= '@percentage_feature_prices_yearly:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  2186.                                 THEN (@premi/100)*@percentages_price
  2187.                                 ELSE 0 END), ';
  2188.                     $sql .= '@percentage_feature_prices_semester:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  2189.                                 THEN (@semester/100)*@percentages_price
  2190.                                 ELSE 0 END), ';
  2191.                     $sql .= '@percentage_feature_prices_quartal:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  2192.                                 THEN (@quartal/100)*@percentages_price
  2193.                                 ELSE 0 END), ';
  2194.                     $sql .= '@percentage_feature_prices_monthly:=(CASE WHEN @percentages_price IS NOT NULL AND @percentages_price > 0
  2195.                                 THEN (@monthly/100)*@percentages_price
  2196.                                 ELSE 0 END), ';
  2197.  
  2198.                     $sql .= '@premi:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @premi+(@amount_price*12), @premi), ';
  2199.                     $sql .= '@premi:=IF(@percentage_feature_prices_yearly IS NOT NULL AND @percentage_feature_prices_yearly > 0, @premi+@percentage_feature_prices_yearly, @premi), ';
  2200.  
  2201.                     $sql .= '@semester:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @semester+(@amount_price*6), @semester), ';
  2202.                     $sql .= '@semester:=IF(@percentage_feature_prices_semester IS NOT NULL AND @percentage_feature_prices_semester > 0, @semester+@percentage_feature_prices_semester, @semester), ';
  2203.  
  2204.                     $sql .= '@quartal:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @quartal+(@amount_price*4), @quartal), ';
  2205.                     $sql .= '@quartal:=IF(@percentage_feature_prices_quartal IS NOT NULL AND @percentage_feature_prices_quartal > 0, @quartal+@percentage_feature_prices_quartal, @quartal), ';
  2206.  
  2207.                     $sql .= '@monthly:=IF(@amount_price IS NOT NULL AND @amount_price > 0, @monthly+@amount_price, @monthly), ';
  2208.                     $sql .= '@monthly:=IF(@percentage_feature_prices_monthly IS NOT NULL AND @percentage_feature_prices_monthly > 0, @monthly+@percentage_feature_prices_monthly, @monthly), ';
  2209.                     // END OF FEATURE ADDITIONAL
  2210.                     */
  2211.  
  2212.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  2213.                     $sql .= 'CAST(IF(product.premi IS NULL, @semester, product.premi) AS UNSIGNED) as semester, ';
  2214.                     $sql .= 'CAST(IF(product.premi IS NULL, @quartal, product.premi) AS UNSIGNED) as quartal, ';
  2215.                     $sql .= 'CAST(IF(product.premi IS NULL, @monthly, product.premi) AS UNSIGNED) as bulanan, ';
  2216.                     $sql .= 'product.id as product_id ';
  2217.  
  2218.                     $sql .= 'FROM insurance_product product ';
  2219.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_questionnaire_health) questionnaires ON questionnaires.product_id = product.id ';
  2220.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_health) features ON features.product_id = product.id ';
  2221.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_health) coverages ON coverages.product_id = product.id ';
  2222.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_health_others) coverage_others ON coverage_others.product_id = product.id ';
  2223.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_health_childrens) coverage_childrens ON coverage_childrens.product_id = product.id ';
  2224.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  2225.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  2226.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  2227.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  2228.  
  2229.                     $sql .= 'WHERE (';
  2230.                     $ab .= ' AND IF(questionnaires.product_level IS NOT NULL, questionnaires.product_level LIKE "%' . $query['product_level'] . '%", questionnaires.product_level IS NULL) ';
  2231.  
  2232.                     unset($query['product_level']);
  2233.  
  2234.                     $sql .= 'IF(questionnaires.what_type_of_cover_would_you_like IS NOT NULL, questionnaires.what_type_of_cover_would_you_like LIKE "%' . $query['what_type_of_cover_would_you_like'] . '%", questionnaires.what_type_of_cover_would_you_like IS NULL) AND ';
  2235.                     $sql .= 'IF(questionnaires.who_need_cover IS NOT NULL, questionnaires.who_need_cover LIKE "%' . $query['who_need_the_cover'] . '%", questionnaires.who_need_cover IS NULL) AND ';
  2236.                     $sql .= 'IF(questionnaires.do_you_currently_have_a_health_insurance IS NOT NULL, questionnaires.do_you_currently_have_a_health_insurance LIKE "%' . $query['do_you_currently_have_a_health_insurance'] . '%", questionnaires.do_you_currently_have_a_health_insurance IS NULL) AND ';
  2237.                     $sql .= 'IF(questionnaires.gender IS NOT NULL, questionnaires.gender = "' . $query['gender'] . '" OR questionnaires.gender = "male.or.female", questionnaires.gender IS NULL) ';
  2238.  
  2239.                     break;
  2240.  
  2241.                 case 'life':
  2242.                     $sql = 'SELECT product.*,
  2243.                                product_detail.*,
  2244.                                product_meta.*,
  2245.                                features.*,
  2246.                                features.count as count,
  2247.                                questionnaires.*, ';
  2248.  
  2249.                     $ab = '';
  2250.                     switch ($query['type_of_product']) {
  2251.                         case 'basic':
  2252.                             $fams = '';
  2253.                             $now = date_create(date('Y-m-d'));
  2254.                             $index = 0;
  2255.  
  2256.                             if ($query['how_many_people_insured'] == 'couple') {
  2257.                                 $birth = [
  2258.                                     'guy' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_guy'])))),
  2259.                                     'girl' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_girl'])))),
  2260.                                 ];
  2261.                                 unset($query['couple_guy']);
  2262.                                 unset($query['couple_girl']);
  2263.  
  2264.                                 $zz = 0;
  2265.                                 $counter_birth = count($birth) - 1;
  2266.                                 // di loop aja biar singkat
  2267.                                 foreach ($birth as $k => $v) {
  2268.                                     if ($k == 'guy') {
  2269.                                         $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2270.                                         $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2271.                                         $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2272.                                         $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2273.  
  2274.                                         // absolute searches for main
  2275.                                         $ab .= 'coverages.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2276.                                         $ab .= 'coverages.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2277.                                     } else {
  2278.                                         $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2279.                                         $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2280.                                         $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2281.                                         $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2282.  
  2283.                                         $ab .= 'coverage_others.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2284.                                         $ab .= 'coverage_others.limitation >= ' . date_diff($now, $v)->y . ' ';
  2285.                                         if ($zz < $counter_birth - 1) {
  2286.                                             $ab .= 'AND ';
  2287.                                         }
  2288.                                         $zz++;
  2289.                                     }
  2290.                                 }
  2291.  
  2292.                                 $sql .= '@premi:=@guy_yearly+@girl_yearly, ';
  2293.                                 $sql .= '@semester:=@guy_semester+@girl_semester, ';
  2294.                                 $sql .= '@quartal:=@guy_quartal+@girl_quartal, ';
  2295.                                 $sql .= '@monthly:=@guy_monthly+@girl_monthly, ';
  2296.  
  2297.                             } elseif ($query['how_many_people_insured'] == 'family') {
  2298.                                 $birth = [
  2299.                                     'husband' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_husband'])))),
  2300.                                     'wife' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_wife'])))),
  2301.                                 ];
  2302.  
  2303.                                 $children = [1, 2, 3, 4];
  2304.                                 foreach ($children as $kid) {
  2305.                                     if (isset($query['family_children_' . $kid])) {
  2306.                                         $birth['kid_' . $kid] = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['family_children_' . $kid]))));
  2307.                                         unset($query['family_children_' . $kid]);
  2308.                                     }
  2309.                                     unset($query['family_husband']);
  2310.                                     unset($query['family_wife']);
  2311.                                 }
  2312.  
  2313.                                 $zz = 0;
  2314.                                 $fam_yearly = '';
  2315.                                 $fam_semester = '';
  2316.                                 $fam_quartal = '';
  2317.                                 $fam_monthly = '';
  2318.                                 $counter_birth = count($birth) - 2;
  2319.  
  2320.                                 foreach ($birth as $k => $v) {
  2321.                                     if ($k == 'husband') {
  2322.                                         $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2323.                                         $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2324.                                         $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2325.                                         $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2326.                                         $ab .= 'coverages.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2327.                                         $ab .= 'coverages.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2328.  
  2329.                                         $fam_yearly .= '@' . $k . '_yearly+';
  2330.                                         $fam_semester .= '@' . $k . '_semester+';
  2331.                                         $fam_quartal .= '@' . $k . '_quartal+';
  2332.                                         $fam_monthly .= '@' . $k . '_monthly+';
  2333.  
  2334.                                     } elseif ($k == 'wife') {
  2335.                                         $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2336.                                         $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2337.                                         $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2338.                                         $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_others WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2339.                                         $ab .= 'coverage_others.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2340.                                         $ab .= 'coverage_others.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2341.  
  2342.                                         $fam_yearly .= '@' . $k . '_yearly+';
  2343.                                         $fam_semester .= '@' . $k . '_semester+';
  2344.                                         $fam_quartal .= '@' . $k . '_quartal+';
  2345.                                         $fam_monthly .= '@' . $k . '_monthly+';
  2346.  
  2347.                                     } else {
  2348.                                         $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2349.                                         $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2350.                                         $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2351.                                         $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_childrens WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2352.                                         $ab .= 'coverage_childrens.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2353.                                         $ab .= 'coverage_childrens.limitation >= ' . date_diff($now, $v)->y . ' ';
  2354.  
  2355.                                         $fam_yearly .= '@' . $k . '_yearly';
  2356.                                         $fam_semester .= '@' . $k . '_semester';
  2357.                                         $fam_quartal .= '@' . $k . '_quartal';
  2358.                                         $fam_monthly .= '@' . $k . '_monthly';
  2359.                                         if ($zz < $counter_birth - 1) {
  2360.                                             $fam_yearly .= '+';
  2361.                                             $fam_semester .= '+';
  2362.                                             $fam_quartal .= '+';
  2363.                                             $fam_monthly .= '+';
  2364.                                             $ab .= 'AND ';
  2365.                                         }
  2366.                                         $zz++;
  2367.                                     }
  2368.                                 }
  2369.  
  2370.                                 $sql .= '@premi:=' . $fam_yearly . ', ';
  2371.                                 $sql .= '@semester:=' . $fam_semester . ', ';
  2372.                                 $sql .= '@quartal:=' . $fam_quartal . ', ';
  2373.                                 $sql .= '@monthly:=' . $fam_monthly . ', ';
  2374.  
  2375.                             } else {
  2376.                                 $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['single_date']))));
  2377.                                 $sql .= '@single_yearly:=(SELECT yearly_rates FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2378.                                 $sql .= '@single_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2379.                                 $sql .= '@single_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2380.                                 $sql .= '@single_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_life_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2381.  
  2382.                                 $sql .= '@premi:=@single_yearly, ';
  2383.                                 $sql .= '@semester:=@single_semester, ';
  2384.                                 $sql .= '@quartal:=@single_quartal, ';
  2385.                                 $sql .= '@monthly:=@single_monthly, ';
  2386.                                 $ab .= 'coverages.age_min <= ' . date_diff($now, $birth)->y . ' AND ';
  2387.                                 $ab .= 'coverages.limitation >= ' . date_diff($now, $birth)->y . ' ';
  2388.  
  2389.                                 unset($query['single_date']);
  2390.                             }
  2391.  
  2392.                             break;
  2393.                         default:
  2394.                             break;
  2395.                     }
  2396.                     $sql .= $amount_features . $percentages_features;
  2397.  
  2398.                     $sql .= $additional_fee_admin;
  2399.                     $sql .= $additional_fee_materai;
  2400.                     $sql .= '@premi:=@premi+@admin_fee+@materai_fee, ';
  2401.                     $sql .= 'IF(@semester > 0, @semester:=@semester+@admin_fee+@materai_fee, @semester:=0), ';
  2402.                     $sql .= 'IF(@quartal > 0, @quartal:=@quartal+@admin_fee+@materai_fee, @quartal:=0), ';
  2403.                     $sql .= 'IF(@monthly > 0, @monthly:=@monthly+@admin_fee+@materai_fee, @monthly:=0), ';
  2404.  
  2405.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  2406.                     $sql .= 'CAST(IF(product.premi IS NULL, @semester, product.premi) AS UNSIGNED) as semester, ';
  2407.                     $sql .= 'CAST(IF(product.premi IS NULL, @quartal, product.premi) AS UNSIGNED) as quartal, ';
  2408.                     $sql .= 'CAST(IF(product.premi IS NULL, @monthly, product.premi) AS UNSIGNED) as bulanan, ';
  2409.                     $sql .= 'product.id as product_id ';
  2410.  
  2411.                     $sql .= 'FROM insurance_product product ';
  2412.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_questionnaire_life) questionnaires ON questionnaires.product_id = product.id ';
  2413.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_life) features ON features.product_id = product.id ';
  2414.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_life_basic) coverages ON coverages.product_id = product.id ';
  2415.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_life_others) coverage_others ON coverage_others.product_id = product.id ';
  2416.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_life_childrens) coverage_childrens ON coverage_childrens.product_id = product.id ';
  2417.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  2418.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  2419.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  2420.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  2421.  
  2422.                     $sql .= 'WHERE (';
  2423.                     $sql .= 'IF(questionnaires.how_many_people_insured IS NOT NULL, questionnaires.how_many_people_insured LIKE "%' . $query['how_many_people_insured'] . '%", questionnaires.how_many_people_insured IS NULL) AND ';
  2424.                     $sql .= 'IF(questionnaires.gender IS NOT NULL, questionnaires.gender = "' . $query['gender'] . '" OR questionnaires.gender = "male.or.female", questionnaires.gender IS NULL) ';
  2425.  
  2426.                     break;
  2427.                 case 'personal-accident-age':
  2428.                     $sql = 'SELECT product.*, product_detail.*, product_meta.*, features.*, features.count as count, questionnaires.claim, ';
  2429.                     $sql .= $amount_features . $percentages_features;
  2430.  
  2431.                     $ab = '';
  2432.                     $now = date_create(date('Y-m-d'));
  2433.  
  2434.                     if ($query['type_of_cover'] == 'couple') {
  2435.                         $birth = [
  2436.                             'guy' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_guy'])))),
  2437.                             'girl' => date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['couple_girl'])))),
  2438.                         ];
  2439.                         unset($query['couple_guy']);
  2440.                         unset($query['couple_girl']);
  2441.  
  2442.                         $zz = 0;
  2443.                         $counter_birth = count($birth) - 1;
  2444.                         // di loop aja biar singkat
  2445.                         foreach ($birth as $k => $v) {
  2446.                             if ($k == 'guy') {
  2447.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2448.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2449.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2450.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2451.  
  2452.                                 // absolute searches for main
  2453.                                 $ab .= 'coverages.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2454.                                 $ab .= 'coverages.limitation >= ' . date_diff($now, $v)->y . ' AND ';
  2455.                             } else {
  2456.                                 $sql .= '@' . $k . '_yearly:=(SELECT yearly_rates FROM insurance_coverage_self_accident_age_couple WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2457.                                 $sql .= '@' . $k . '_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_self_accident_age_couple WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2458.                                 $sql .= '@' . $k . '_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_self_accident_age_couple WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2459.                                 $sql .= '@' . $k . '_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_self_accident_age_couple WHERE age_min <= ' . date_diff($now, $v)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2460.  
  2461.                                 $ab .= 'coverage_others.age_min <= ' . date_diff($now, $v)->y . ' AND ';
  2462.                                 $ab .= 'coverage_others.limitation >= ' . date_diff($now, $v)->y . ' ';
  2463.                                 if ($zz < $counter_birth - 1) {
  2464.                                     $ab .= 'AND ';
  2465.                                 }
  2466.                                 $zz++;
  2467.                             }
  2468.                         }
  2469.  
  2470.                         $sql .= '@premi:=@guy_yearly+@girl_yearly, ';
  2471.                         $sql .= '@semester:=@guy_semester+@girl_semester, ';
  2472.                         $sql .= '@quartal:=@guy_quartal+@girl_quartal, ';
  2473.                         $sql .= '@monthly:=@guy_monthly+@girl_monthly, ';
  2474.                     } else {
  2475.                         $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $query['single_date']))));
  2476.                         $sql .= '@single_yearly:=(SELECT yearly_rates FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2477.                         $sql .= '@single_semester:=(SELECT IF(semester_rates IS NOT NULL,semester_rates, 0) as semester FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2478.                         $sql .= '@single_quartal:=(SELECT IF(quartal_rates IS NOT NULL,quartal_rates, 0) as quartal FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2479.                         $sql .= '@single_monthly:=(SELECT IF(monthly_rates IS NOT NULL,monthly_rates, 0) as monthly FROM insurance_coverage_self_accident_age_basic WHERE age_min <= ' . date_diff($now, $birth)->y . ' AND product_id = product.id ORDER BY age_min DESC LIMIT 1), ';
  2480.  
  2481.                         $sql .= '@premi:=@single_yearly, ';
  2482.                         $sql .= '@semester:=@single_semester, ';
  2483.                         $sql .= '@quartal:=@single_quartal, ';
  2484.                         $sql .= '@monthly:=@single_monthly, ';
  2485.                         $ab .= 'coverages.age_min <= ' . date_diff($now, $birth)->y . ' AND ';
  2486.                         $ab .= 'coverages.limitation >= ' . date_diff($now, $birth)->y . ' ';
  2487.                         unset($query['single_date']);
  2488.                     }
  2489.                     $sql .= $amount_features . $percentages_features;
  2490.  
  2491.                     $sql .= $additional_fee_admin;
  2492.                     $sql .= $additional_fee_materai;
  2493.                     $sql .= '@premi:=@premi+@admin_fee+@materai_fee, ';
  2494.                     $sql .= 'IF(@semester > 0, @semester:=@semester+@admin_fee+@materai_fee, @semester:=0), ';
  2495.                     $sql .= 'IF(@quartal > 0, @quartal:=@quartal+@admin_fee+@materai_fee, @quartal:=0), ';
  2496.                     $sql .= 'IF(@monthly > 0, @monthly:=@monthly+@admin_fee+@materai_fee, @monthly:=0), ';
  2497.                     $sql .= 'CAST(IF(product.premi IS NULL, @premi, product.premi) AS UNSIGNED) as premi, ';
  2498.                     $sql .= 'CAST(IF(product.premi IS NULL, @semester, product.premi) AS UNSIGNED) as semester, ';
  2499.                     $sql .= 'CAST(IF(product.premi IS NULL, @quartal, product.premi) AS UNSIGNED) as quartal, ';
  2500.                     $sql .= 'CAST(IF(product.premi IS NULL, @monthly, product.premi) AS UNSIGNED) as bulanan, ';
  2501.                     $sql .= 'product.id as product_id ';
  2502.  
  2503.                     $sql .= 'FROM insurance_product product ';
  2504.                     $sql .= 'LEFT JOIN (SELECT *,';
  2505.                     $sql .= 'CASE WHEN label_claim_two IS NOT NULL AND (amount_claim_two > amount_claim_one AND amount_claim_two > amount_claim_three AND amount_claim_two > amount_claim_four AND amount_claim_two > amount_claim_five )THEN @claim:=amount_claim_two
  2506.                                 WHEN label_claim_three IS NOT NULL AND (amount_claim_three > amount_claim_one AND amount_claim_three > amount_claim_two AND amount_claim_three > amount_claim_four AND amount_claim_three > amount_claim_five )THEN @claim:=amount_claim_three
  2507.                                 WHEN label_claim_four IS NOT NULL AND (amount_claim_four > amount_claim_one AND amount_claim_four > amount_claim_two AND amount_claim_four > amount_claim_three AND amount_claim_four > amount_claim_five )THEN @claim:=amount_claim_four
  2508.                                 WHEN label_claim_five IS NOT NULL AND (amount_claim_five > amount_claim_one AND amount_claim_five > amount_claim_two AND amount_claim_five > amount_claim_three AND amount_claim_five > amount_claim_four )THEN @claim:=amount_claim_five
  2509.                                 ELSE @claim:=amount_claim_one END AS claim ';
  2510.                     $sql .= 'FROM insurance_questionnaire_personal_accident) questionnaires ON questionnaires.product_id = product.id ';
  2511.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_feature_personal_accident) features ON features.product_id = product.id ';
  2512.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_self_accident_age_basic) coverages ON coverages.product_id = product.id ';
  2513.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_coverage_self_accident_age_couple) coverages_others ON coverages_others.product_id = product.id ';
  2514.                     $sql .= 'LEFT JOIN (SELECT * FROM insurance_product_detail) product_detail ON product_detail.product_id = product.id ';
  2515.                     $sql .= 'LEFT JOIN (SELECT id, image, product_id FROM insurance_product_meta) product_meta ON product_meta.product_id = product.id ';
  2516.                     $sql .= 'LEFT JOIN (SELECT id,is_active FROM insurance_provider) provider ON product.provider_id = provider.id ';
  2517.                     $sql .= 'LEFT JOIN (SELECT id, provider_id, last_login FROM users) users ON users.provider_id = provider.id ';
  2518.  
  2519.                     $sql .= 'WHERE (';
  2520.  
  2521.                     unset($query['product_level']);
  2522.                     unset($query['value_of_cover']);
  2523.  
  2524.                     $sql .= 'IF(questionnaires.type_of_cover IS NOT NULL, questionnaires.type_of_cover LIKE "%' . $query['type_of_cover'] . '%", questionnaires.type_of_cover IS NULL) AND ';
  2525.                     $sql .= 'IF(questionnaires.type_of_work IS NOT NULL, questionnaires.type_of_work LIKE "%' . $query['type_of_work'] . '%", questionnaires.type_of_work IS NULL) AND ';
  2526.                     //$sql .= 'IF(questionnaires.warranty_status IS NOT NULL, questionnaires.warranty_status LIKE "%' . $query['warranty_status'] . '%", questionnaires.warranty_status IS NULL) AND ';
  2527.                     $sql .= 'IF(questionnaires.gender IS NOT NULL, questionnaires.gender = "' . $query['gender'] . '" OR questionnaires.gender = "male.or.female", questionnaires.gender IS NULL) ';
  2528.                     break;
  2529.             }
  2530.  
  2531.             $type = str_replace('-', '.', $type);
  2532.             /*
  2533.              * Menambahkan logic ketika ada PRODUCT LEVEL untuk travel, personal accident dan health
  2534.              * maka ditambahkan logic untuk WHERE yang ada diluar lingkaran maut itu untuk mendapatkan
  2535.              * produk yang sesuai dengan level produknya
  2536.              */
  2537. //            if (isset($setcook['product_level'])) {
  2538. //                $sql .= ') AND product.type = "' . $type . '" AND product.is_active = 1 AND questionnaires.product_level="' . $setcook['product_level'] . '"';
  2539. //            } else {
  2540.                 $sql .= ') AND product.type = "' . $type . '" AND product.is_active = 1 ';
  2541. //            }
  2542.  
  2543.             switch ($type) {
  2544.                 case 'motorcycle':
  2545.                     $sql .= 'AND zone_territory.province_id=' . $query['province'] . ' AND product.type_of_insurance="' . $query['level_of_insurance'] . '"';
  2546.                     break;
  2547.  
  2548.                 case 'car':
  2549.                     $sql .= 'AND zone_territory.province_id=' . $query['province'] . ' AND product.type_of_insurance="' . $query['level_of_insurance'] . '" AND (CASE WHEN questionnaires.car_premi_calc > 800000000
  2550.                                                                                                                                                                         THEN coverages.up_to=0
  2551.                                                                                                                                                                      WHEN questionnaires.car_premi_calc > 400000000 AND questionnaires.car_premi_calc <=800000000
  2552.                                                                                                                                                                         THEN coverages.up_to=800000000
  2553.                                                                                                                                                                      WHEN questionnaires.car_premi_calc > 200000000 AND questionnaires.car_premi_calc <=400000000
  2554.                                                                                                                                                                         THEN coverages.up_to=400000000
  2555.                                                                                                                                                                      WHEN questionnaires.car_premi_calc > 125000000 AND questionnaires.car_premi_calc <=200000000
  2556.                                                                                                                                                                         THEN coverages.up_to=200000000
  2557.                                                                                                                                                                      ELSE coverages.up_to=125000000 END) ';
  2558.                     break;
  2559.  
  2560.                 case 'property':
  2561.                     $sql .= 'AND zone_territory.city_id=' . $query['city'] . ' ';
  2562.                     if ($level_of_insurance != 'earthquake') {
  2563.                         $sql .= 'AND coverages.property="' . $class_property . '" AND product.type_of_insurance="' . $level_of_insurance . '" ';
  2564.                     } else {
  2565.                         $sql .= 'AND coverages.category='.$construction_property.' AND coverages.class=1 AND product.type_of_insurance="' . $level_of_insurance . '" ';
  2566.                     }
  2567.                     break;
  2568.  
  2569.                 case 'health':
  2570.                     $sql .= 'AND ' . $ab;
  2571.                     break;
  2572.                 case 'life':
  2573.                     $sql .= 'AND ' . $ab;
  2574.                     break;
  2575.                 case 'travel':
  2576.                     //Ini apa ya? Bikin error di search result
  2577.                     $sql .= 'AND ' . $ab;
  2578.                     break;
  2579.                 case 'personal-accident':
  2580.                 case 'personal-accident-age':
  2581.                     $sql .= 'AND ' . $ab;
  2582.  
  2583.                     break;
  2584.             }
  2585.  
  2586.             $sql .= $absolute;
  2587.  
  2588.             if ($factor == 'rates') {
  2589.                 $sql .= ' AND product.rates > 0 ';
  2590.             }
  2591.             $sql .= ' AND provider.is_active=1 GROUP BY product.id ';
  2592.  
  2593.             // nanti kalo yang mau dipake buat average total_amount_of_features desc, awas jangan typo
  2594.  
  2595.             switch ($factor) {
  2596.                 case 'price':
  2597.                     $sql .= 'ORDER BY premi ASC, features.count DESC,features.total_amount_of_features DESC, product.rates DESC, (product.promo > "") DESC,product.viewers DESC, product.id DESC ';
  2598.                     break;
  2599.  
  2600.                 case 'feature':
  2601.                     $sql .= 'ORDER BY features.count DESC, features.total_amount_of_features DESC, premi ASC , product.rates DESC, (product.promo > "") DESC, product.viewers DESC,product.id DESC ';
  2602.                     break;
  2603.  
  2604.                 case 'expensive':
  2605.                     $sql .= 'ORDER BY premi DESC, features.count ASC,features.total_amount_of_features ASC, product.rates ASC, (product.promo > "") DESC, product.viewers ASC, product.id DESC ';
  2606.                     break;
  2607.  
  2608.                 case 'rates':
  2609.                     $sql .= 'ORDER BY product.rates DESC ';
  2610.                     break;
  2611.  
  2612.                 case 'cheapest':
  2613.                     $sql .= 'ORDER BY premi ASC, features.count DESC,features.total_amount_of_features DESC, product.rates DESC,  (product.promo > "") DESC, product.viewers DESC, product.id DESC ';
  2614.                     break;
  2615.  
  2616.                 case 'average':
  2617.                     $sql .= 'ORDER BY product.promo DESC, product.rates DESC, product.viewers DESC, users.last_login DESC';
  2618.                     break;
  2619.             }
  2620.             if (isset($request['sort'])) {
  2621.                 switch ($request['sort']) {
  2622.                     default:
  2623.                         $sql .= 'ORDER BY premi ASC, features.count DESC,features.total_amount_of_features DESC, product.rates DESC, (product.promo > "") DESC,product.viewers DESC, product.id DESC ';
  2624.                         break;
  2625.  
  2626.                     case 'expensive':
  2627.                         $sql .= 'ORDER BY premi DESC, features.count ASC,features.total_amount_of_features ASC, product.rates ASC, (product.promo > "") DESC, product.viewers ASC, product.id DESC ';
  2628.                         break;
  2629.                 }
  2630.             }
  2631.             if ($factor != 'average' and $factor != 'cheapest' and $factor != 'expensive') {
  2632.                 $sql .= 'LIMIT 0,1';
  2633.             } elseif ($factor == 'average') {
  2634.                 //$sql .= 'LIMIT 0,3';
  2635.             } elseif (isset($request['offset']) and $request['offset']) {
  2636.                 $sql .= 'LIMIT ' . $request['offset'] . ',10';
  2637.             } else {
  2638.                 $sql .= 'LIMIT 10';
  2639.             }
  2640.             //print($sql);die();
  2641.             $res      = DB::select(DB::raw($sql));
  2642.             $features = collect([])->toArray();
  2643.             switch ($type) {
  2644.                 case 'car':
  2645.                     $ftr = $featureController->car;
  2646.                     break;
  2647.                 case 'motorcycle':
  2648.                     $ftr = $featureController->motorcycle;
  2649.                     break;
  2650.                 case 'property':
  2651.                     $ftr = $featureController->property;
  2652.                     break;
  2653.                 case 'health':
  2654.                     $ftr = $featureController->health;
  2655.                     break;
  2656.                 case 'travel':
  2657.                     $ftr = $featureController->travel;
  2658.                     break;
  2659.                 case 'personal.accident':
  2660.                 case 'personal.accident.age':
  2661.                     $ftr = $featureController->personal_accident;
  2662.                     break;
  2663.                 case 'life':
  2664.                     $ftr = $featureController->life;
  2665.                     break;
  2666.             }
  2667.  
  2668.             // features insertion
  2669.             foreach ($res as $key => $val) {
  2670.                 $zo = 1;
  2671.                 if ($val->sort_features != null and $val->sort_features != 'null') {
  2672.                     $featurez = json_decode($val->sort_features);
  2673.                     if (json_last_error() == JSON_ERROR_NONE) {
  2674.                         $tmp_f = [];
  2675.                         foreach ($val as $ka => $va) {
  2676.                             foreach ($ftr as $k => $v) {
  2677.                                 if ($v['name'] == $ka and !is_null($va)) {
  2678.                                     if ($zo <= 4) {
  2679. //                                      $features = collect($features);
  2680.                                         foreach ($featurez as $keys => $vals) {
  2681.                                             $replace = trans('feature.' . str_replace('_', '.', $keys));
  2682.                                             /*if ( strlen( $replace ) > 20 ) {
  2683.                                                 $replace = substr( $replace, 0, 20 ) . '...';
  2684.                                             }*/
  2685.                                             $tmp_f[$vals] = $replace;
  2686.                                         }
  2687.                                         ksort($tmp_f);
  2688.  
  2689.                                         foreach ($tmp_f as $vv) {
  2690.                                             $res[$key]->features[$vv] = $va;
  2691.                                         }
  2692.                                         $zo++;
  2693.                                     }
  2694.                                 }
  2695.                             }
  2696.                         }
  2697.                     }
  2698.                 } else {
  2699.                     foreach ($val as $ka => $va) {
  2700.                         foreach ($ftr as $k => $v) {
  2701.                             if ($v['name'] == $ka and !is_null($va)) {
  2702.                                 if ($zo <= 4) {
  2703.                                     $features[$ka] = $va;
  2704.                                     $replace       = trans('feature.' . str_replace('_', '.', $ka));
  2705.                                     /*
  2706.                                     if ( strlen( $replace ) > 20 ) {
  2707.                                         $replace = substr( $replace, 0, 20 ) . '...';
  2708.                                     }*/
  2709.                                     $res[$key]->features[$replace] = $va;
  2710.                                     $zo++;
  2711.                                 }
  2712.                             }
  2713.                         }
  2714.                     }
  2715.                 }
  2716.             }
  2717.            
  2718.             if ($factor == 'cheapest' or $factor == 'expensive') {
  2719.                 if (count($res) < 2) {
  2720.                     $res['limit'] = 'yes';
  2721.                 }
  2722.             }
  2723.             if ($factor == 'average' and $type != "personal.accident") {
  2724.                 $sum   = 0;
  2725.                 $count = count($res);
  2726.                 foreach ($res as $k => $v) {
  2727.                     $sum += $v->premi;
  2728.                 }
  2729.  
  2730.                 $avg = ($count < 1 ? 0 : $sum / $count); // fix division by zero
  2731.                 // add 10% to $avg
  2732.                 $avg *= (1 + 50 / 100);
  2733.             }
  2734.             // foreach
  2735.  
  2736.             foreach ($res as $k => $r) {
  2737.                 if (!is_string($r)) {
  2738.  
  2739.                     // create score object
  2740.                     if ($factor == 'average' and $type != 'personal.accident') {
  2741.                         if ($r->premi > $avg) {
  2742.                             unset($res[$k]); // unset the product with premi above average
  2743.                             continue;
  2744.                         }
  2745.                         $counter       = ($r->count < 1 ? 1 : $r->count);
  2746.                         $r->score      = (int)($r->premi / $counter);
  2747.                         $r->avg        = $avg;
  2748.                         $r->score      = (int)($r->premi / $counter);
  2749.                         $r->promo_bool = (!empty($r->promo)?100:50);
  2750.                         $r->last_login = Insurance_Provider::where('id', $r->provider_id)->with([
  2751.                             'users.user' => function ($q) {
  2752.                                 return $q->orderBy('last_login', 'DESC');
  2753.                             },
  2754.                         ])->first()->last_login;
  2755.  
  2756.  
  2757.                     }
  2758.                     //end
  2759.  
  2760.                     $r->int_premi = $r->premi;
  2761.                     $r->premi     = rupiah($r->premi);
  2762.                     if(isset($r->semester)){
  2763.                         if(is_int($r->semester)){
  2764.                             $r->semester = rupiah($r->semester);
  2765.                         }
  2766.                     }
  2767.                     if(isset($r->quartal)){
  2768.                         if(is_int($r->quartal)){
  2769.                             $r->quartal = rupiah($r->quartal);
  2770.                         }
  2771.                     }
  2772.                     if(isset($r->bulanan)){
  2773.                         if(is_int($r->bulanan)){
  2774.                             $r->bulanan = rupiah($r->bulanan);
  2775.                         }
  2776.                     }
  2777.                     switch ($type) {
  2778.                         case 'personal.accident':
  2779.                             $r->claim = rupiah($r->claim);
  2780.                             break;
  2781.                         case 'property':
  2782.                             $r->values = (integer)$query['estimated_value_of_the_property_to_cover'];
  2783.                             break;
  2784.                         case 'car':
  2785.                             $r->values = (integer)$query['car_value'];
  2786.                             break;
  2787.                         case 'motorcycle':
  2788.                             $r->values = (integer)$query['motorcycle_value'];
  2789.                             break;
  2790.                     }
  2791.                     $provider_slug = Insurance_Provider::find($r->provider_id)->slug;
  2792.                     $url           = url('/insurance') . '/' . $provider_slug . '/product/' . $r->slug . '';
  2793.                     $r->partner    = InsuranceProductPartner::where('product_id', $r->product_id)->count();
  2794.                     $r->url        = $url;
  2795.                     $r->questionnaire  = $setcook;
  2796.                     $r->bypass     = encrypt($setcook);
  2797.                 }
  2798.             }
  2799.             // comment
  2800.  
  2801.             if ($factor == 'average' and $type != "personal.accident") {
  2802.                 // sorting rules
  2803.                
  2804.                 // udah muncul
  2805.                 $udah = (array) json_decode($request['ids']);
  2806.                 // konversi
  2807.                 $uKeys = array_keys($udah);
  2808.                 $uValues = array_values($udah);
  2809.                 $uIntKeys = array_map('intval', $uKeys);
  2810.                 $udah = array_combine($uIntKeys, $uValues);
  2811.                 // done
  2812.                 $excl = [];
  2813.                 foreach($udah as $k=>$v){
  2814.                     if($v>1){
  2815.                         $excl[] = $k;
  2816.                     }
  2817.                 }
  2818.                 $collection = collect($res);
  2819.  
  2820.                 // sortby collection caranya terbalik dari eloquent, kalau disini dia dari kanan ke kiri
  2821.                 $lastavg = clone $collection; // clone the object for last avg
  2822.                 // if excl are more than 1, AND THERE IS OTHER RESULT then it must have whereNot In
  2823.                 if(count($excl)>0){
  2824.                     /** $try = array_slice($collection->whereNotIn('product_id', $excl)->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  2825.                         return !empty($arr->promo);
  2826.                     })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  2827.                     $try = array_slice($collection->whereNotIn('product_id', $excl)->sortByMulti([
  2828.                                 'score' => 'ASC',
  2829.                                 'rates' => 'DESC',
  2830.                                 'promo_bool' => 'DESC',
  2831.                                 'viewers' => 'DESC',
  2832.                                 'product_id' => 'DESC'
  2833.                             ])->values()->all(),0,2);
  2834.                     if(count($try)>0){
  2835.                         $x = $try;
  2836.                     }else{
  2837.                         /** $x  = array_slice($collection->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  2838.                                         return !empty($arr->promo);
  2839.                                     })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  2840.                         $x = array_slice($collection->sortByMulti([
  2841.                                 'score' => 'ASC',
  2842.                                 'rates' => 'DESC',
  2843.                                 'promo_bool' => 'DESC',
  2844.                                 'viewers' => 'DESC',
  2845.                                 'product_id' => 'DESC'
  2846.                             ])->values()->all(),0,2);            
  2847.                     }
  2848.                 }else{
  2849.                     /** $x  = array_slice($collection->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  2850.                                     return !empty($arr->promo);
  2851.                                 })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  2852.                     $x = array_slice($collection->sortByMulti([
  2853.                                 'score' => 'ASC',
  2854.                                 'rates' => 'DESC',
  2855.                                 'promo_bool' => 'DESC',
  2856.                                 'viewers' => 'DESC',
  2857.                                 'product_id' => 'DESC'
  2858.                             ])->values()->all(),0,2);                
  2859.                 }
  2860.                 // not include
  2861.                 // first increment to "udah" array
  2862.                 $newUdah = [];
  2863.                 foreach ($x as $item) {
  2864.                     foreach($udah as $kUdah=>$vUdah){
  2865.                         if($kUdah==$item->product_id){
  2866.                             $udah[$item->product_id]++;
  2867.                         }else{
  2868.                             // if the product are never shown on cheapest and MF, assign it into newUdah
  2869.                             if(!isset($udah[$item->product_id])){
  2870.                                 $newUdah[$item->product_id] = 1;
  2871.                             }
  2872.                         }
  2873.                     }
  2874.                 }
  2875.                 // now we create the second exclude
  2876.                 $notIn = [];
  2877.                 // from newUdah
  2878.                 foreach($newUdah as $k=>$v){
  2879.                     $notIn[] = $k;
  2880.                 }
  2881.                 // and from udah, but if the product already showing twice
  2882.                 foreach($udah as $k=>$v){
  2883.                     if($v>1){
  2884.                         $notIn[] = $k;
  2885.                     }
  2886.                 }
  2887.                 // then prepare
  2888.                 /**
  2889.                  * Zul, semua script yang kaya dibawah ini diubah jadi sortByMulti ya, ini gw kasi contoh satu, sisanya lu tinggal ikutin..
  2890.                  * Ini ga ad di dokumentasi laravel, karena ini custom..
  2891.                  * Nah.. berhubung ini masih test.. script yang lama jangan dihapus.. melainkan di comment aja.. kaya contoh yang gw lakuin ini
  2892.                  *
  2893.                  * JANGAN LUPA!! Order nya dari kanan > kiri , jadi atas > bawah pas di sortByMulti, lihat contoh bawah
  2894.                
  2895.                 $y = array_slice($lastavg->whereNotIn('product_id', $notIn)->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  2896.                     return !empty($arr->promo);
  2897.                 })->sortByDesc('rates')->sortBy('int_premi')->sortBy('score')->values()->all(), 0, 1);
  2898.                
  2899.                 * Pake yang dibawah ini ya
  2900.                 * Thankyou zul
  2901.                 **/
  2902.                
  2903.                 $y = array_slice($lastavg->whereNotIn('product_id', $notIn)->sortByMulti([
  2904.                     'score' => 'ASC',
  2905.                     'int_premi' => 'ASC',
  2906.                     'rates' => 'DESC',
  2907.                     'promo_bool' => 'DESC',
  2908.                     'viewers' => 'DESC',
  2909.                     'product_id' => 'DESC'
  2910.                 ])->values()->all(),0,1);
  2911.                
  2912.                 // if $y ( most value ) are below 1 then use the cheapes > mf > follow by others
  2913.                 if(count($y)<1){
  2914.                     /** $y = array_slice($lastavg->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  2915.                         return !empty($arr->promo);
  2916.                     })->sortByDesc('rates')->sortByDesc('total_amount_of_features')->sortByDesc('count')->sortBy('int_premi')->values()->all(), 0, 1); **/
  2917.                     $y = array_slice($lastavg->sortByMulti([
  2918.                         'int_premi' => 'ASC',
  2919.                         'count' => 'DESC',
  2920.                         'total_amount_of_features' => 'DESC',
  2921.                         'rates' => 'DESC',
  2922.                         'promo_bool' => 'DESC',
  2923.                         'viewers' => 'DESC',
  2924.                         'product_id' => 'DESC',
  2925.                     ])->values()->all(),0,1);
  2926.                 }
  2927.                 // fill $x with the same product if there is only one
  2928.                 // kage bushin no jutsu
  2929.                 if (count($x) == 1) {
  2930.                     $tmp_x = $x[0];
  2931.                     array_push($x, $tmp_x);
  2932.                     //$x[]   = $tmp_x;
  2933.                 }
  2934.  
  2935.                 return array_merge($x, $y);
  2936.  
  2937.                 //return $twoavg;
  2938.             } else {
  2939.                 return $res;
  2940.             }
  2941.         }
  2942.     }
  2943.  
  2944.     public function addingViewers(Request $request, Insurance_Product_View $insurance_Product_View)
  2945.     {
  2946.         $result = false;
  2947.         $slugProduct = $request->slugProduct;
  2948.         $product_id = $request->product_id;
  2949.         $ip = $request->ip();
  2950.  
  2951.         // set session token
  2952.         // jika emang dia punya auth user maka dipake auth usernya buat otentikasi data, kalo enggak ya dibikinin random.
  2953.         if (!Auth::check()) {
  2954.             if (!Session::has('who')) {
  2955.                 Session::put('who', hash('whirlpool', str_random(30)) . $ip);
  2956.             }
  2957.             $data_who = Session::get('who');
  2958.         } else {
  2959.             $data_who = Auth::user()->id;
  2960.         }
  2961.  
  2962.         // config token waktu produk yang saat ini lagi dilihat.
  2963.         if (Session::has($data_who)) {
  2964.             if (isset(Session::get($data_who)[$slugProduct])) {
  2965.                 // ngambil waktu dulu berdasarkan produk sama token usernya juga, jika kurang dari maka next step kalo gak dibuatin baru
  2966.                 if (Session::get($data_who)[$slugProduct]['token_time'] > time()) {
  2967.                     if (Session::get($data_who)[$slugProduct]['token_break'] < 1) {
  2968.                         if (Session::get($data_who)[$slugProduct]['break_time'] > time()) {
  2969.                             // jika token time masih valid, tapi token break juga masih kurang dari 2
  2970.                             // maka data view di input dan break_tokennya juga ditambah
  2971.                             Session::put($data_who, array(
  2972.                                 $slugProduct => [
  2973.                                     'token_time' => Session::get($data_who)[$slugProduct]['token_time'],
  2974.                                     'token_break' => Session::get($data_who)[$slugProduct]['token_break'] + 1,
  2975.                                     'break_time' => Session::get($data_who)[$slugProduct]['break_time']
  2976.                                 ]
  2977.                             ));
  2978.                             $result = $this->addingNewViewers($product_id, hash('whirlpool', $slugProduct), $insurance_Product_View, $ip);
  2979.                         }
  2980.                     }
  2981.                 } else {
  2982.                     Session::put($data_who, array(
  2983.                         $slugProduct => [
  2984.                             'token_time' => time() + 3600,
  2985.                             'token_break' => 0,
  2986.                             'break_time' => time() + 30
  2987.                         ]
  2988.                     ));
  2989.                     $result = $this->addingNewViewers($product_id, hash('whirlpool', $slugProduct), $insurance_Product_View, $ip);
  2990.                 }
  2991.             } else {
  2992.                 Session::put($data_who, array(
  2993.                     $slugProduct => [
  2994.                         'token_time' => time() + 3600,
  2995.                         'token_break' => 0,
  2996.                         'break_time' => time() + 30
  2997.                     ]
  2998.                 ));
  2999.                 $result = $this->addingNewViewers($product_id, hash('whirlpool', $slugProduct), $insurance_Product_View, $ip);
  3000.             }
  3001.         } else {
  3002.             Session::put($data_who, array(
  3003.                 $slugProduct => [
  3004.                     'token_time' => time() + 3600,
  3005.                     'token_break' => 0,
  3006.                     'break_time' => time() + 30
  3007.                 ]
  3008.             ));
  3009.             $result = $this->addingNewViewers($product_id, hash('whirlpool', $slugProduct), $insurance_Product_View, $ip);
  3010.         }
  3011.  
  3012.         if ($result) {
  3013.             return 'ok';
  3014.         } else {
  3015.             $remaining = Session::get($data_who)[$slugProduct]['token_time'];
  3016.             $now = time();
  3017.             $rems = date('H:i:s', $remaining - $now);
  3018.  
  3019.             return $rems . ' Remaining!';
  3020.         }
  3021.     }
  3022.  
  3023.     public function addingNewViewers($product_id, $token, $insurance_Product_View, $ip)
  3024.     {
  3025.         $insurance_Product_View->ip = $ip;
  3026.         $insurance_Product_View->product_id = $product_id;
  3027.         $insurance_Product_View->token = $token;
  3028.         DB::table('insurance_product')->whereId($product_id)->increment('viewers');
  3029.  
  3030.         return $insurance_Product_View->save();
  3031.     }
  3032.  
  3033.     /**
  3034.      * View search five result
  3035.      *
  3036.      * @param \Illuminate\Http\Request                                          $request
  3037.      * @param \Thanatos\Modules\Insurance\Http\Controllers\FeatureController    $featureController
  3038.      * @param \Thanatos\Modules\Insurance\Http\Controllers\AdditionalController $additionalController
  3039.      *
  3040.      * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
  3041.      */
  3042.     public function viewSearchFiveResult(Request $request, FeatureController $featureController, AdditionalController $additionalController)
  3043.     {
  3044.         //echo $request->fullUrl();exit;
  3045.         if ($request->has('type')) {
  3046.             if ($request->type == 'car') {
  3047.                 if ($request->level_of_insurance == 'comprehensive') {
  3048.                     $additional = $additionalController->comprehensive['car'];
  3049.                 } else {
  3050.                     $additional = $additionalController->total_loss_only['car'];
  3051.                 }
  3052.             } elseif ($request->type == 'property') {
  3053.                 if ($request->level_of_insurance == 'standard' or $request->level_of_insurance == 'all_risk') {
  3054.                     $additional = $additionalController->all_risk['property'];
  3055.                     if ($request->province == '3' or $request->province == '6' || $request->province == '9') {
  3056.                         unset($additional['outside_around_jakarta_zone_one']);
  3057.                         unset($additional['outside_around_jakarta_zone_two']);
  3058.                         unset($additional['outside_around_jakarta_zone_three']);
  3059.                         unset($additional['outside_around_jakarta_zone_four']);
  3060.  
  3061.                     } else {
  3062.                         unset($additional['around_jakarta_zone_one']);
  3063.                         unset($additional['around_jakarta_zone_two']);
  3064.                         unset($additional['around_jakarta_zone_three']);
  3065.                         unset($additional['around_jakarta_zone_four']);
  3066.                     }
  3067.                 }
  3068.             } elseif ($request->type == 'motorcycle') {
  3069.                 if ($request->level_of_insurance == 'comprehensive') {
  3070.                     $additional = $additionalController->comprehensive['motorcycle'];
  3071.                 } else {
  3072.                     $additional = $additionalController->total_loss_only['motorcycle'];
  3073.                 }
  3074.             }
  3075.  
  3076.             $title = trans('global.searchResult') . ' - ' . trans('global.title');
  3077.             $data  = [
  3078.                 'types'    => $request->type,
  3079.                 'qs'       => parse_url($request->fullUrl())['query'],
  3080.                 'type'     => $request->type,
  3081.                 'title'    => $title,
  3082.                 'features' => $featureController->getAllByType($request, true),
  3083.                 'en'       => str_replace('/search', '/en/search', $request->fullUrl()),
  3084.                 'id'       => str_replace('/en', '', $request->fullUrl()),
  3085.             ];
  3086.             if (isset($additional)) {
  3087.                 $data['additional'] = $additional;
  3088.             }
  3089.  
  3090.             return view('front.search.result', $data);
  3091.         }
  3092.     }
  3093.  
  3094.     public function viewSearchAllResult(Request $request, FeatureController $featureController, AdditionalController $additionalController)
  3095.     {
  3096.         if ($request->has('type')) {
  3097.             if ($request->type == 'car') {
  3098.                 if ($request->level_of_insurance == 'comprehensive') {
  3099.                     $additional = $additionalController->comprehensive['car'];
  3100.                 } else {
  3101.                     $additional = $additionalController->total_loss_only['car'];
  3102.                 }
  3103.             } elseif ($request->type == 'property') {
  3104.                 if ($request->level_of_insurance == 'all_risk' or $request->level_of_insurance == 'standard') {
  3105.                     $additional = $additionalController->all_risk['property'];
  3106.                     if ($request->province == '3' or $request->province == '6' || $request->province == '9') {
  3107.                         unset($additional['outside_around_jakarta_zone_one']);
  3108.                         unset($additional['outside_around_jakarta_zone_two']);
  3109.                         unset($additional['outside_around_jakarta_zone_three']);
  3110.                         unset($additional['outside_around_jakarta_zone_four']);
  3111.  
  3112.                     } else {
  3113.                         unset($additional['around_jakarta_zone_one']);
  3114.                         unset($additional['around_jakarta_zone_two']);
  3115.                         unset($additional['around_jakarta_zone_three']);
  3116.                         unset($additional['around_jakarta_zone_four']);
  3117.                     }
  3118.                 }
  3119.             } elseif ($request->type == 'motorcycle') {
  3120.                 if ($request->level_of_insurance == 'comprehensive') {
  3121.                     $additional = $additionalController->comprehensive['motorcycle'];
  3122.                 } else {
  3123.                     $additional = $additionalController->total_loss_only['motorcycle'];
  3124.                 }
  3125.             }
  3126.  
  3127.             $title = trans('global.showAllTitle') . ' - ' . trans('global.title');
  3128.             $view = array(
  3129.                 'qs' => parse_url($request->fullUrl())['query'],
  3130.                 'features' => $featureController->getAllByType($request, true),
  3131.                 'title' => $title,
  3132.                 'type' => $request->type,
  3133.                 'bypass' => $request->config,
  3134.                 'en' => str_replace('/search', '/en/search', $request->fullUrl()),
  3135.                 'id' => str_replace('/en', '', $request->fullUrl())
  3136.             );
  3137.  
  3138.             if (isset($additional)) {
  3139.                 $view['additional'] = $additional;
  3140.             }
  3141.  
  3142.             return view('front.search.product-list', $view);
  3143.         }
  3144.     }
  3145.  
  3146.     public function viewComparerResult(Request $request, FeatureController $featureController)
  3147.     {
  3148.         if ($request->has('type') and $request->has('first') and $request->has('second')) {
  3149.             $view = array(
  3150.                 'features' => $featureController->getAllByType($request, true),
  3151.             );
  3152.  
  3153.             return view('front.search.product-list', $view);
  3154.         }
  3155.     }
  3156.  
  3157.     public function viewAllDetailFront(Request $request, $slug, $slugProduct, Insurance_Product_View $insurance_Product_View, AdditionalController $additionalController, RateController $rateController, FeatureController $featureController){
  3158.         $config = array();
  3159.         $detail = $this->getDetailProduct($slug, $slugProduct, $request->configuration, $request->ip(), $insurance_Product_View, $additionalController, $rateController, $featureController);
  3160.         $detail['config'] = $request->configuration;
  3161.         $detail['raw'] = $detail['configuration'];
  3162.         $detail['info_addons'] = [];
  3163.         $detail['info_features'] = [];
  3164.         $conf = decrypt($request->configuration);
  3165.         foreach ($conf as $k => $v) {
  3166.             if (!is_array($v)) {
  3167.                 if ($k != 'age') {
  3168.                     $types = str_replace('.', '-', $detail["product"]["type"]);
  3169.                     $exclude = ['Provinsi', 'Kota', 'Kecamatan', 'Province', 'City', 'Subdistrict'];
  3170.                     $k = trans('questionnaire.' . $types . '.' . str_replace('_', '.', $k));
  3171.                     $v = trans('questionnaire.' . $types . '.' . str_replace('_', '.', $v));
  3172.  
  3173.                     if (!in_array($k, $exclude)) {
  3174.                         $v = str_replace('questionnaire.car.', '', $v);
  3175.                         $v = str_replace('questionnaire.motorcycle.', '', $v);
  3176.                         $v = str_replace('questionnaire.property.', '', $v);
  3177.                         $v = str_replace('questionnaire.personal-accident.', '', $v);
  3178.                         $v = str_replace('questionnaire.personal-accident-age.', '', $v);
  3179.                         $v = str_replace('questionnaire.travel.', '', $v);
  3180.                         $v = str_replace('questionnaire.health.', '', $v);
  3181.                         $v = str_replace('questionnaire.life.', '', $v);
  3182.                         $config[$k] = $v;
  3183.                     }
  3184.                 }
  3185.             }
  3186.         }
  3187.  
  3188.        
  3189.         if (isset($conf['addition'])) {
  3190.             foreach ($conf['addition'] as $k => $v) {
  3191.                 if ($v > 100) {
  3192.                     $detail['info_addons'][trans('additional.' . $detail['product']['type'] . "." . str_replace('_', '.', $k))] = rupiah($v);
  3193.                 } else {
  3194.                     $detail['info_addons'][trans('additional.' . $detail['product']['type'] . "." . str_replace('_', '.', $k))] = $v;
  3195.                 }
  3196.  
  3197.             }
  3198.         }
  3199.  
  3200.         if (isset($conf['feature'])) {
  3201.             $rp = '';
  3202.             $ext = '';
  3203.             switch ($k) {
  3204.                 case 'grace_period_for_decease_benefit':
  3205.                 case 'grace_period_for_critical_illness_benefit':
  3206.                 case 'survival_period_for_critical_illness_benefit':
  3207.                     $ext = ' Days';
  3208.                     break;
  3209.                 case 'preexisting_condition_for_decease_benefit':
  3210.                 case 'preexisting_condition_for_critical_illness_benefit':
  3211.                 case 'policy_reinstatement':
  3212.                 case 'policy_termination':
  3213.                     $ext = ' Mo.';
  3214.                     break;
  3215.                 case 'investment_benefit':
  3216.                 case 'automatic_premium_leave':
  3217.                     $ext = ' Yr';
  3218.                     break;
  3219.                 default:
  3220.                     if ($v < 100) {
  3221.                         $ext = '%';
  3222.                     } else {
  3223.                         $rp = 'Rp. ';
  3224.                     }
  3225.                     break;
  3226.             }
  3227.             foreach ($conf['feature'] as $k => $v) {
  3228.                 $detail['info_features'][trans('feature.' . str_replace('_', '.', $v))] = "true";
  3229.             }
  3230.         }
  3231.  
  3232.         $detail['configuration'] = $config;
  3233.         if(isset($detail['product']['semester'])){
  3234.             if($detail['product']['semester'] > 0){
  3235.                 $detail['product']['semester'] = rupiah($detail['product']['semester']);
  3236.             }
  3237.         }
  3238.         if(isset($detail['product']['quartal'])){
  3239.             if($detail['product']['quartal'] > 0){
  3240.                 $detail['product']['quartal'] = rupiah($detail['product']['quartal']);
  3241.             }
  3242.         }
  3243.         if(isset($detail['product']['monthly'])){
  3244.             if($detail['product']['monthly'] > 0){
  3245.                 $detail['product']['monthly'] = rupiah($detail['product']['monthly']);
  3246.             }
  3247.         }
  3248.         if (LaravelLocalization::getCurrentLocale() == 'en') {
  3249.             $interest = "If you're interest with this product, please click the button below";
  3250.             $detail['en'] = $request->fullUrl();
  3251.             $detail['id'] = str_replace('/en/insurance/', '/insurance/', $request->fullUrl());
  3252.             /*
  3253.             $detail['product']['premi'] = str_replace('Rp.','Rp.',$detail['product']['premi']);
  3254.             if(isset($detail['product']['semester'])){
  3255.                 if($detail['product']['semester'] != ''){
  3256.                     $detail['product']['semester'] = str_replace('Rp.','Rp.',$detail['product']['semester']);
  3257.                 }
  3258.             }
  3259.             if(isset($detail['product']['quartal'])){
  3260.                 if($detail['product']['quartal'] != ''){
  3261.                     $detail['product']['quartal'] = str_replace('Rp.','Rp.',$detail['product']['quartal']);
  3262.                 }
  3263.             }
  3264.             if(isset($detail['product']['monthly'])){
  3265.                 if($detail['product']['monthly'] != ''){
  3266.                     $detail['product']['monthly'] = str_replace('Rp.','Rp.',$detail['product']['monthly']);
  3267.                 }
  3268.             }*/
  3269.         } else {
  3270.             $interest = "Jika Anda tertarik dengan produk ini, silahkan klik tombol di bawah ini";
  3271.             $detail['en'] = str_replace('/insurance/', '/en/insurance/', $request->fullUrl());
  3272.             $detail['id'] = $request->fullUrl();
  3273.         }
  3274.        
  3275.         $detail['share_url'] = $request->fullUrl();
  3276.         $detail['slugProduct'] = $slugProduct;
  3277.         $detail['slugProvider'] = $slug;
  3278.        
  3279.         if($detail['product']['type']=='car' || $detail['product']['type']=='motorcycle'){
  3280.             $tmp_vehicle_price = $detail['product']['transparency']['value_price'];
  3281.             $tmp_trans = $detail['product']['transparency'];
  3282.             unset($detail['product']['transparency']);
  3283.            
  3284.             $detail['product']['transparency'] = ['vehicle_price' => $tmp_vehicle_price];
  3285.             $detail['product']['transparency'] = array_merge($detail['product']['transparency'], $tmp_trans);
  3286.             unset($detail['product']['transparency']['value_price']);
  3287.         } elseif($detail['product']['type']=='property'){
  3288.             $tmp_prop_price = null;
  3289.             if(isset($detail['product']['transparency']['value_price'])){
  3290.                 $tmp_prop_price = $detail['product']['transparency']['value_price'];
  3291.             }
  3292.             $tmp_trans = $detail['product']['transparency'];
  3293.             unset($detail['product']['transparency']);
  3294.            
  3295.             if(!is_null($tmp_prop_price)){
  3296.                 $detail['product']['transparency'] = ['property_price' => $tmp_prop_price];
  3297.                 $detail['product']['transparency'] = array_merge($detail['product']['transparency'], $tmp_trans);
  3298.             } else {
  3299.                 $detail['product']['transparency'] = $tmp_trans;
  3300.             }
  3301.             unset($detail['product']['transparency']['value_price']);
  3302.         }
  3303.         $detail['interested'] = $interest;
  3304.  
  3305.         return view('front.search.detail', $detail);
  3306.     }
  3307.  
  3308.     public function bacaKweri(Request $request, $exclude = null, FeatureController $featureController, AdditionalController $additionalController, RateController $rateController){
  3309.         $type = $request['type'];
  3310.         if($type != 'personal-accident'){
  3311.             return $this->getSearchQuery($request, $exclude = null, $featureController, $additionalController, $rateController);
  3312.         }
  3313.         else {
  3314.             $bagian_1 = $this->getSearchQuery($request, $exclude = null, $featureController, $additionalController, $rateController);
  3315.             // problemnya adalah ketika getSearch query dilempar maka semua data dengan jumlah minimal 3 akan dihitung.
  3316.             // yang perlu dilakukan adalah dengan meng-group-by product_id yang sama.
  3317.             $dd_tmp_1 = [];
  3318.             $temp_bag_1 = collect($bagian_1)->groupBy('product_id')->toArray();
  3319.             foreach($temp_bag_1 as $key => $val){
  3320.                 $dd_tmp_1[] = $val[0];
  3321.             }
  3322.             $bagian_1 = $dd_tmp_1;
  3323.  
  3324.             $request['type'] = 'personal-accident-age';
  3325.             $bagian_2 = $this->getSearchQuery($request, $exclude = null, $featureController, $additionalController, $rateController);
  3326.             // problemnya adalah ketika getSearch query dilempar maka semua data dengan jumlah minimal 3 akan dihitung.
  3327.             // yang perlu dilakukan adalah dengan meng-group-by product_id yang sama.
  3328.             $dd_tmp_2 = [];
  3329.             $temp_bag_2 = collect($bagian_2)->groupBy('product_id')->toArray();
  3330.             foreach($temp_bag_2 as $key => $val){
  3331.                 $dd_tmp_2[] = $val[0];
  3332.             }
  3333.             $bagian_2 = $dd_tmp_2;
  3334.            
  3335.             $gabungke = $bagian_1;
  3336.             foreach($bagian_2 as $bag_k => $bag_v){
  3337.                 $gabungke[] = $bag_v;
  3338.             }
  3339.             $gabungke = collect($gabungke);
  3340. /*
  3341.             switch ($factor) {
  3342.                 case 'price':
  3343.                     $sql .= 'ORDER BY premi ASC, features.count DESC,features.total_amount_of_features DESC, product.rates DESC, (product.promo > "") DESC,product.viewers DESC, product.id DESC ';
  3344.                     break;
  3345.  
  3346.                 case 'feature':
  3347.                     $sql .= 'ORDER BY features.count DESC, features.total_amount_of_features DESC, premi ASC , product.rates DESC, (product.promo > "") DESC, product.viewers DESC,product.id DESC ';
  3348.                     break;
  3349.  
  3350.                 case 'expensive':
  3351.                     $sql .= 'ORDER BY premi DESC, features.count ASC,features.total_amount_of_features ASC, product.rates ASC, (product.promo > "") DESC, product.viewers ASC, product.id DESC ';
  3352.                     break;
  3353.  
  3354.                 case 'rates':
  3355.                     $sql .= 'ORDER BY product.rates DESC ';
  3356.                     break;
  3357.  
  3358.                 case 'cheapest':
  3359.                     $sql .= 'ORDER BY premi ASC, features.count DESC,features.total_amount_of_features DESC, product.rates DESC,  (product.promo > "") DESC, product.viewers DESC, product.id DESC ';
  3360.                     break;
  3361.  
  3362.                 case 'average':
  3363.                     $sql .= 'ORDER BY product.promo DESC, product.rates DESC, product.viewers DESC, users.last_login DESC';
  3364.                     break;
  3365.             }
  3366.             } elseif (isset($request['offset']) and $request['offset']) {
  3367.                 $sql .= 'LIMIT ' . $request['offset'] . ',10';
  3368.  * */
  3369. //            if(isset($))
  3370.             if($request['factor']=='cheapest' || $request['factor']=='price'){
  3371.                 $hasile = $gabungke->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc('rates')->sortByDesc('total_amont_of_features')->sortByDesc('count')->sortBy('int_premi');
  3372.                 $hasile = $hasile->values()->toArray();
  3373.             } elseif($request['factor']=='feature') {
  3374.                 $hasile = $gabungke->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc('rates')->sortBy('premi')->sortByDesc('total_amont_of_features')->sortByDesc('count');
  3375.                 $hasile = $hasile->values()->toArray();
  3376.             } elseif($request['factor']=='expensive') {
  3377.                 $hasile = $gabungke->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc('rates')->sortByDesc('total_amont_of_features')->sortByDesc('count')->sortByDesc('int_premi');
  3378.                 $hasile = $hasile->values()->toArray();
  3379.             } else {
  3380.                 $hasile = $gabungke->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc('rates');
  3381.                 $hasile = $hasile->values()->toArray();
  3382.  
  3383.                 $sum   = 0;
  3384.                 $count = count($hasile);
  3385.                 foreach ($hasile as $k => $v) {
  3386.                     $sum += $v->int_premi;
  3387.                 }
  3388.  
  3389.                 $avg = ($count < 1 ? 0 : $sum / $count); // fix division by zero
  3390. // add 10% to $avg
  3391.                 $avg *= (1 + 50 / 100);
  3392. // foreach
  3393.  
  3394.                 foreach ($hasile as $k => $r) {
  3395.                     if (!is_string($r)) {
  3396.  
  3397. // create score object
  3398.                         if ($r->int_premi > $avg) {
  3399.                             unset($hasile[$k]); // unset the product with premi above average
  3400.                             continue;
  3401.                         }
  3402.                         $counter       = ($r->count < 1 ? 1 : $r->count);
  3403.                         $r->score      = (int)($r->int_premi / $counter);
  3404.                         $r->avg        = $avg;
  3405.                         $r->score      = (int)($r->int_premi / $counter);
  3406.  
  3407.                         $r->last_login = Insurance_Provider::where('id', $r->provider_id)->with([
  3408.                             'users.user' => function ($q) {
  3409.                                 return $q->orderBy('last_login', 'DESC');
  3410.                             },
  3411.                         ])->first()->last_login;
  3412.  
  3413.                         // YANG GAK DIPAKE GAK PERLU DI DECLARE ULANG
  3414.                         /*
  3415.                         $r->int_premi = $r->premi;
  3416.                         $r->premi     = rupiah($r->premi);
  3417.                         $r->claim = rupiah($r->claim);
  3418.                         $provider_slug = Insurance_Provider::find($r->provider_id)->slug;
  3419.                         $url           = url('/insurance') . '/' . $provider_slug . '/product/' . $r->slug . '';
  3420.                         $r->partner    = InsuranceProductPartner::where('product_id', $r->product_id)->count();
  3421.                         $r->url        = $url;
  3422.                         $r->questionnaire  = $setcook;
  3423.                         $r->bypass     = encrypt($setcook);
  3424.                         */
  3425.                     }
  3426.                 }
  3427.                
  3428. // udah muncul
  3429.                 $udah = (array) json_decode($request['ids']);
  3430. // konversi
  3431.                 $uKeys = array_keys($udah);
  3432.                 $uValues = array_values($udah);
  3433.                 $uIntKeys = array_map('intval', $uKeys);
  3434.                 $udah = array_combine($uIntKeys, $uValues);
  3435. // done
  3436.                 $excl = [];
  3437.                 foreach($udah as $k=>$v){
  3438.                     if($v>1){
  3439.                         $excl[] = $k;
  3440.                     }
  3441.                 }
  3442.                 $collection = collect($hasile);
  3443.  
  3444. // sortby collection caranya terbalik dari eloquent, kalau disini dia dari kanan ke kiri
  3445.                 $lastavg = clone $collection; // clone the object for last avg
  3446. // if excl are more than 1, AND THERE IS OTHER RESULT then it must have whereNot In
  3447.                 if(count($excl)>0){
  3448.                     /** $try = array_slice($collection->whereNotIn('product_id', $excl)->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  3449.                         return !empty($arr->promo);
  3450.                     })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  3451.                     $try = array_slice($collection->whereNotIn('product_id', $excl)->sortByMulti([
  3452.                                 'score' => 'ASC',
  3453.                                 'rates' => 'DESC',
  3454.                                 'promo_bool' => 'DESC',
  3455.                                 'viewers' => 'DESC',
  3456.                                 'product_id' => 'DESC'
  3457.                             ])->values()->all(),0,2);
  3458.                     if(count($try)>0){
  3459.                         $x = $try;
  3460.                     }else{
  3461.                         /** $x  = array_slice($collection->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  3462.                                         return !empty($arr->promo);
  3463.                                     })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  3464.                         $x = array_slice($collection->sortByMulti([
  3465.                                 'score' => 'ASC',
  3466.                                 'rates' => 'DESC',
  3467.                                 'promo_bool' => 'DESC',
  3468.                                 'viewers' => 'DESC',
  3469.                                 'product_id' => 'DESC'
  3470.                             ])->values()->all(),0,2);            
  3471.                     }
  3472.                 }else{
  3473.                     /** $x  = array_slice($collection->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  3474.                                     return !empty($arr->promo);
  3475.                                 })->sortByDesc('rates')->sortBy('score')->values()->all(), 0, 2); **/
  3476.                     $x = array_slice($collection->sortByMulti([
  3477.                                 'score' => 'ASC',
  3478.                                 'rates' => 'DESC',
  3479.                                 'promo_bool' => 'DESC',
  3480.                                 'viewers' => 'DESC',
  3481.                                 'product_id' => 'DESC'
  3482.                             ])->values()->all(),0,2);                
  3483.                 }
  3484. // not include
  3485. // first increment to "udah" array
  3486.                 $newUdah = [];
  3487.                 foreach ($x as $item) {
  3488.                     foreach($udah as $kUdah=>$vUdah){
  3489.                         if($kUdah==$item->product_id){
  3490.                             $udah[$item->product_id]++;
  3491.                         }else{
  3492. // if the product are never shown on cheapest and MF, assign it into newUdah
  3493.                             if(!isset($udah[$item->product_id])){
  3494.                                 $newUdah[$item->product_id] = 1;
  3495.                             }
  3496.                         }
  3497.                     }
  3498.                 }
  3499. // now we create the second exclude
  3500.                 $notIn = [];
  3501. // from newUdah
  3502.                 foreach($newUdah as $k=>$v){
  3503.                     $notIn[] = $k;
  3504.                 }
  3505. // and from udah, but if the product already showing twice
  3506.                 foreach($udah as $k=>$v){
  3507.                     if($v>1){
  3508.                         $notIn[] = $k;
  3509.                     }
  3510.                 }
  3511. // then prepare
  3512.                 $y = array_slice($lastavg->whereNotIn('product_id', $notIn)->sortByMulti([
  3513.                     'score' => 'ASC',
  3514.                     'int_premi' => 'ASC',
  3515.                     'rates' => 'DESC',
  3516.                     'promo_bool' => 'DESC',
  3517.                     'viewers' => 'DESC',
  3518.                     'product_id' => 'DESC'
  3519.                 ])->values()->all(),0,1);
  3520.                
  3521.                 // if $y ( most value ) are below 1 then use the cheapes > mf > follow by others
  3522.                 if(count($y)<1){
  3523.                     /** $y = array_slice($lastavg->sortByDesc('product_id')->sortByDesc('viewers')->sortByDesc(function($arr,$k){
  3524.                         return !empty($arr->promo);
  3525.                     })->sortByDesc('rates')->sortByDesc('total_amount_of_features')->sortByDesc('count')->sortBy('int_premi')->values()->all(), 0, 1); **/
  3526.                     $y = array_slice($lastavg->sortByMulti([
  3527.                         'int_premi' => 'ASC',
  3528.                         'count' => 'DESC',
  3529.                         'total_amount_of_features' => 'DESC',
  3530.                         'rates' => 'DESC',
  3531.                         'promo_bool' => 'DESC',
  3532.                         'viewers' => 'DESC',
  3533.                         'product_id' => 'DESC',
  3534.                     ])->values()->all(),0,1);
  3535.                 }
  3536. // fill $x with the same product if there is only one
  3537. // kage bushin no jutsu
  3538.                 if (count($x) == 1) {
  3539.                     $tmp_x = $x[0];
  3540.                     array_push($x, $tmp_x);
  3541. //$x[]   = $tmp_x;
  3542.                 }
  3543.  
  3544.                 return array_merge($x, $y);
  3545.  
  3546. //return $twoavg;
  3547.  
  3548.             }
  3549.  
  3550.             if($request['factor'] != 'average' and ($request['factor'] == 'price' or $request['factor'] == 'feature')){
  3551.                 if(isset($hasile[0])){
  3552.                     return array($hasile[0]);
  3553.                 } else {
  3554.                     return [];
  3555.                 }
  3556.             } elseif(isset($request['offset']) and $request['offset']){
  3557.                 $tmp = [];
  3558.                 $akhiran = count($hasile);
  3559.                 if($akhiran >= 10){
  3560.                     $awal = (integer)$request['offset'];
  3561.                     $akhiran = ($awal + 10);
  3562.                     for($ix = $awal; $ix < $akhiran; $ix++){
  3563.                         $tmp[] = $hasile[$ix];
  3564.                     }
  3565.                 } else {
  3566.                     $tmp['limit'] = 'yes';
  3567.                 }
  3568.                 return $tmp;
  3569.             } elseif($request['factor'] == 'cheapest' or $request['factor'] == 'expensive') {
  3570.                 $awal = (integer)$request['offset'];
  3571.                 $akhiran = count($hasile);
  3572.                 if($akhiran > 10){
  3573.                     $akhiran = 10;
  3574.                 }
  3575.                 $tmp = [];
  3576.                 for($ix = $awal; $ix < $akhiran; $ix++){
  3577.                     if($hasile[$ix]!='yes'){
  3578.                         $tmp[] = $hasile[$ix];
  3579.                     }
  3580.                 }
  3581.                 return $tmp;
  3582.             }
  3583.         }
  3584.     }
  3585.  
  3586.     public function getDetailProduct($slug, $slugProduct, $bypass, $ip, $insurance_Product_View, $additional_controller, $rate_controller, $feature_controller, $life_count = 'yearly')
  3587.     {
  3588.         // get provider information
  3589.         $provider = Insurance_Provider::where('slug', $slug)->first()->toArray();
  3590.         // feature and benefit relation call conditional
  3591.         $products = Insurance_Product::where('slug', $slugProduct)->where('provider_id', $provider['id'])->first();
  3592.  
  3593.         $type = $products->type;
  3594.         $prefix = str_replace('-', '_', $type);
  3595.         $prefix = str_replace('.', '_', $prefix);
  3596.         if($prefix == 'personal_accident_age'){
  3597.             $prefix = 'personal_accident';
  3598.         }
  3599.         $questionnaire = 'quest_' . $prefix;
  3600.         $feature = 'feature_' . $prefix;
  3601.         $additional = 'additional_' . $prefix;
  3602.         $setcook = '';
  3603.         // end
  3604.         $wherein = array();
  3605.         if (isset($bypass) && !empty($bypass)) {
  3606.             $setcook = decrypt($bypass);
  3607.         }
  3608.  
  3609.         if ($type == 'car' || $type == 'motorcycle') {
  3610.             $benefit = 'benefit_' . $prefix;
  3611.             $coverage = 'coverage_' . $prefix . '_' . $setcook['level_of_insurance'];
  3612.             $product = Insurance_Product::with($questionnaire, $benefit, $feature, $coverage, $additional, 'insurance_product_partners','features_additional_prices')
  3613.                 ->where('slug', $slugProduct)
  3614.                 ->where('provider_id', $provider['id'])
  3615.                 ->first()->toArray();
  3616.  
  3617.             $product['additional'] = $product['additional_' . $prefix];
  3618.             $product['additional'] = array();
  3619.         } else if ($type == 'property') {
  3620.             $benefit = 'benefit_' . $prefix;
  3621.             $coverage = 'coverage_' . $prefix . '_' . $setcook['level_of_insurance'];
  3622.             if ($setcook['level_of_insurance'] == 'all_risk') {
  3623.                 $coverage = 'coverage_' . $prefix . '_all';
  3624.             }
  3625.  
  3626.             if($setcook['level_of_insurance'] != 'earthquake'){
  3627.                 $product = Insurance_Product::with($questionnaire, $benefit, $feature, $additional, 'insurance_product_partners','features_additional_prices')
  3628.                     ->with([$coverage => function ($query) use ($setcook) {
  3629.                         $query->where('property', $setcook['class_property']);
  3630.                         $query->limit(1);
  3631.                     }])
  3632.                     ->where('slug', $slugProduct)
  3633.                     ->where('provider_id', $provider['id'])
  3634.                     ->first()->toArray();
  3635.  
  3636.                 $product['additional'] = array();
  3637.             } else {
  3638.                 $class_property = array('below.6' =>1,
  3639.                     'in.6-18' =>2,
  3640.                     'up.to.18'=>3,
  3641.                     'park.up.to.24'=>4,
  3642.                     'less.than.3.storeys'=>5,
  3643.                     'boarding.house'=>6,
  3644.                     'floating'=>7);
  3645.  
  3646.                 $limiting    = array(1=>[1=>1,2=>2,3=>3],
  3647.                                      2=>[1=>1,2=>2,3=>3],
  3648.                                      3=>[1=>1,2=>2,3=>3],
  3649.                                      4=>[1=>1,2=>2,3=>3],
  3650.                                      5=>[1=>1,2=>2,3=>2],
  3651.                                      6=>[1=>1,2=>2,3=>2],
  3652.                                      7=>[1=>1,2=>2,3=>2]);
  3653.                 //$setcook['construction_property'] = $limiting[$class_property[$setcook['class_property']]][$setcook['construction_property']];
  3654.  
  3655.                 $product = Insurance_Product::with($questionnaire, $benefit, $feature, $additional, 'insurance_product_partners','features_additional_prices')
  3656.                     ->with([$coverage => function ($query) use ($setcook,$class_property) {
  3657.                         $query->where('class', 1);
  3658.                         $query->where('category', $setcook['construction_property']);
  3659.                         $query->limit(1);
  3660.                     }])
  3661.                     ->where('slug', $slugProduct)
  3662.                     ->where('provider_id', $provider['id'])
  3663.                     ->first()->toArray();
  3664.  
  3665.                 $product['additional'] = array();
  3666.             }
  3667.         } elseif ($type == 'personal.accident' or $type == 'personal.accident.age') {
  3668.             if($type == 'personal.accident'){
  3669.                 $coverage = 'coverage_self_accident';
  3670.                 $product = Insurance_Product::with($questionnaire, $feature, $coverage, 'coverage_self_accident_other', 'insurance_product_partners')
  3671.                     ->where('slug', $slugProduct)
  3672.                     ->where('provider_id', $provider['id'])
  3673.                     ->first()->toArray();
  3674.             }elseif($type == 'personal.accident.age'){
  3675.                 $now = date_create(date('Y-m-d'));
  3676.                 $coverage = 'coverage_self_accident_age_basic';
  3677.                 $product = Insurance_Product::with($questionnaire, $feature, 'insurance_product_partners')
  3678.                     ->with(['coverage_self_accident_age_basic' => function ($query) use ($setcook, $now) {
  3679.                         if ($setcook['type_of_cover'] == 'couple') {
  3680.                             $guy = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_guy']))));
  3681.                             $guy = date_diff($now, $guy)->y;
  3682.                             $query->where('age_min', '<=', $guy);
  3683.                             $query->where('limitation', '>=', $guy);
  3684.                         } elseif ($setcook['type_of_cover'] == 'family') {
  3685.                             $husband = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_husband']))));
  3686.                             $husband = date_diff($now, $husband)->y;
  3687.                             $query->where('age_min', '<=', $husband);
  3688.                             $query->where('limitation', '>=', $husband);
  3689.                         } else {
  3690.                             $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['single_date']))));
  3691.                             $birth = date_diff($now, $birth)->y;
  3692.                             $query->where('age_min', '<=', $birth);
  3693.                             $query->where('limitation', '>=', $birth);
  3694.                         }
  3695.                         $query->orderBy('age_min', 'desc');
  3696.                         $query->limit(1);}
  3697.                     ])
  3698.                     ->with(['coverage_self_accident_age_couple' => function ($query) use ($setcook, $now) {
  3699.                         if ($setcook['type_of_cover'] == 'couple') {
  3700.                             $girl = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_girl']))));
  3701.                             $girl = date_diff($now, $girl)->y;
  3702.                             $query->where('age_min', '<=', $girl);
  3703.                             $query->where('limitation', '>=', $girl);
  3704.  
  3705.                         } elseif ($setcook['type_of_cover'] == 'family') {
  3706.                             $wife = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_wife']))));
  3707.                             $wife = date_diff($now, $wife)->y;
  3708.                             $query->where('age_min', '<=', $wife);
  3709.                             $query->where('limitation', '>=', $wife);
  3710.                         }
  3711.                         $query->orderBy('age_min', 'desc');
  3712.                         $query->limit(1);
  3713.                     }])
  3714.                     ->where('slug', $slugProduct)
  3715.                     ->where('provider_id', $provider['id'])
  3716.                     ->first()
  3717.                     ->toArray();
  3718.             }
  3719.         } elseif ($type == 'travel') {
  3720.             $arrival = date_create(str_replace('/', '-', $setcook['arrival_date']));
  3721.             $departure = date_create(str_replace('/', '-', $setcook['departure_date']));
  3722.             $date_diff = (integer)date_diff($arrival, $departure)->format('%a') + 1;
  3723.  
  3724.             $product = Insurance_Product::with($questionnaire, $feature, 'insurance_product_partners')
  3725.                 ->with(['coverage_travel_domestic' => function ($query) use ($setcook, $date_diff) {
  3726.                     $query->where('days_min', '<=', $date_diff);
  3727.                     $query->orderBy('days_min', 'DESC');
  3728.                     $query->limit(1);
  3729.                 }])
  3730.                 ->with(['coverage_travel_asia' => function ($query) use ($setcook, $date_diff) {
  3731.                     $query->where('days_min', '<=', $date_diff);
  3732.                     $query->orderBy('days_min', 'DESC');
  3733.                     $query->limit(1);
  3734.                 }])
  3735.                 ->with(['coverage_travel_asean' => function ($query) use ($setcook, $date_diff) {
  3736.                     $query->where('days_min', '<=', $date_diff);
  3737.                     $query->orderBy('days_min', 'DESC');
  3738.                     $query->limit(1);
  3739.                 }])
  3740.                 ->with(['coverage_travel_worldwide_exclude_shenzeng' => function ($query) use ($setcook, $date_diff) {
  3741.                     $query->where('days_min', '<=', $date_diff);
  3742.                     $query->orderBy('days_min', 'DESC');
  3743.                     $query->limit(1);
  3744.                 }])
  3745.                 ->with(['coverage_travel_worldwide_include_shenzeng' => function ($query) use ($setcook, $date_diff) {
  3746.                     $query->where('days_min', '<=', $date_diff);
  3747.                     $query->orderBy('days_min', 'DESC');
  3748.                     $query->limit(1);
  3749.                 }])
  3750.                 ->with(['coverage_travel_annual' => function ($query) use ($setcook) {
  3751.                     $query->where('type', '<=', $setcook['travel_category']);
  3752.                     $query->limit(1);
  3753.                 }])
  3754.                 ->where('slug', $slugProduct)
  3755.                 ->where('provider_id', $provider['id'])
  3756.                 ->first()->toArray();
  3757.         } elseif ($type == 'health') {
  3758.             $now = date_create(date('Y-m-d'));
  3759.             $coverage = 'coverage_health';
  3760.             $product = Insurance_Product::with($questionnaire, $feature, 'insurance_product_partners')
  3761.                 ->with([
  3762.                     $coverage => function ($query) use ($setcook, $now) {
  3763.                         if ($setcook['who_need_the_cover'] == 'couple') {
  3764.                             $guy = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_guy']))));
  3765.                             $guy = date_diff($now, $guy)->y;
  3766.                             $query->where('age_min', '<=', $guy);
  3767.                             $query->where('limitation', '>=', $guy);
  3768.                         } elseif ($setcook['who_need_the_cover'] == 'family') {
  3769.                             $husband = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_husband']))));
  3770.                             $husband = date_diff($now, $husband)->y;
  3771.                             $query->where('age_min', '<=', $husband);
  3772.                             $query->where('limitation', '>=', $husband);
  3773.                         } else {
  3774.                             $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['single_date']))));
  3775.                             $birth = date_diff($now, $birth)->y;
  3776.                             $query->where('age_min', '<=', $birth);
  3777.                             $query->where('limitation', '>=', $birth);
  3778.                         }
  3779.                         $query->orderBy('age_min', 'desc');
  3780.                         $query->limit(1);
  3781.                     }
  3782.                 ])
  3783.                 ->with(['coverage_health_others' => function ($query) use ($setcook, $now) {
  3784.                     if ($setcook['who_need_the_cover'] == 'couple') {
  3785.                         $girl = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_girl']))));
  3786.                         $girl = date_diff($now, $girl)->y;
  3787.                         $query->where('age_min', '<=', $girl);
  3788.                         $query->where('limitation', '>=', $girl);
  3789.  
  3790.                     } elseif ($setcook['who_need_the_cover'] == 'family') {
  3791.                         $wife = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_wife']))));
  3792.                         $wife = date_diff($now, $wife)->y;
  3793.                         $query->where('age_min', '<=', $wife);
  3794.                         $query->where('limitation', '>=', $wife);
  3795.                     }
  3796.                     $query->orderBy('age_min', 'desc');
  3797.                     $query->limit(1);
  3798.                 }])
  3799.                 ->with(['coverage_health_childrens' => function ($query) use ($setcook, $now) {
  3800.                     if ($setcook['who_need_the_cover'] == 'family') {
  3801.                         $children = array(1, 2, 3, 4);
  3802.  
  3803.                         foreach ($children as $kid) {
  3804.                             if (isset($setcook['family_children_' . $kid])) {
  3805.                                 $lato = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_children_' . $kid]))));
  3806.                                 $births['kid_' . $kid] = date_diff($now, $lato)->y;
  3807.                             }
  3808.                         }
  3809.  
  3810.                         foreach ($births as $role => $fam) {
  3811.                             $query->orWhere('age_min', '<=', $fam);
  3812.                         }
  3813.  
  3814.                         foreach ($births as $role => $fam) {
  3815.                             $query->where('limitation', '>=', $fam);
  3816.                         }
  3817.                     }
  3818.                     $query->orderBy('age_min', 'desc');
  3819.                 }])
  3820.                 ->where('slug', $slugProduct)
  3821.                 ->where('provider_id', $provider['id'])
  3822.                 ->first()->toArray();
  3823.         } elseif ($type == 'life') {
  3824.             $now = date_create(date('Y-m-d'));
  3825.             $coverage = 'coverage_life_' . $setcook['type_of_product'];
  3826.             $product = Insurance_Product::with($questionnaire, $feature, 'insurance_product_partners')
  3827.                 ->with([
  3828.                     $coverage => function ($query) use ($setcook, $now) {
  3829.                         if ($setcook['how_many_people_insured'] == 'couple') {
  3830.                             $guy = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_guy']))));
  3831.                             $guy = date_diff($now, $guy)->y;
  3832.                             $query->where('age_min', '<=', $guy);
  3833.                             $query->where('limitation', '>=', $guy);
  3834.                         } elseif ($setcook['how_many_people_insured'] == 'family') {
  3835.                             $husband = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_husband']))));
  3836.                             $husband = date_diff($now, $husband)->y;
  3837.                             $query->where('age_min', '<=', $husband);
  3838.                             $query->where('limitation', '>=', $husband);
  3839.                         } else {
  3840.                             $birth = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['single_date']))));
  3841.                             $birth = date_diff($now, $birth)->y;
  3842.                             $query->where('age_min', '<=', $birth);
  3843.                             $query->where('limitation', '>=', $birth);
  3844.                         }
  3845.                         $query->orderBy('age_min', 'desc');
  3846.                         $query->limit(1);
  3847.                     }
  3848.                 ])
  3849.                 ->with(['coverage_life_others' => function ($query) use ($setcook, $now) {
  3850.                     if ($setcook['how_many_people_insured'] == 'couple') {
  3851.                         $girl = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['couple_girl']))));
  3852.                         $girl = date_diff($now, $girl)->y;
  3853.                         $query->where('age_min', '<=', $girl);
  3854.                         $query->where('limitation', '>=', $girl);
  3855.  
  3856.                     } elseif ($setcook['how_many_people_insured'] == 'family') {
  3857.                         $wife = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_wife']))));
  3858.                         $wife = date_diff($now, $wife)->y;
  3859.                         $query->where('age_min', '<=', $wife);
  3860.                         $query->where('limitation', '>=', $wife);
  3861.                     }
  3862.                     $query->orderBy('age_min', 'desc');
  3863.                     $query->limit(1);
  3864.                 }])
  3865.                 ->with(['coverage_life_childrens' => function ($query) use ($setcook, $now) {
  3866.                     if ($setcook['how_many_people_insured'] == 'family') {
  3867.                         $children = array(1, 2, 3, 4);
  3868.  
  3869.                         foreach ($children as $kid) {
  3870.                             if (isset($setcook['family_children_' . $kid])) {
  3871.                                 $lato = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_children_' . $kid]))));
  3872.                                 $births['kid_' . $kid] = date_diff($now, $lato)->y;
  3873.                             }
  3874.                         }
  3875.  
  3876.                         foreach ($births as $role => $fam) {
  3877.                             $query->orWhere('age_min', '<=', $fam);
  3878.                         }
  3879.  
  3880.                         foreach ($births as $role => $fam) {
  3881.                             $query->where('limitation', '>=', $fam);
  3882.                         }
  3883.                     }
  3884.                     $query->orderBy('age_min', 'desc');
  3885.                 }])
  3886.                 ->where('slug', $slugProduct)
  3887.                 ->where('provider_id', $provider['id'])
  3888.                 ->first()
  3889.                 ->toArray();
  3890.         }
  3891. //        dd($product);
  3892.  
  3893.         if ((int)$product['premi'] < 1) {
  3894.             $condition = [];
  3895.             $formulation = [];
  3896.  
  3897.             if ($type == 'car') {
  3898.                 $zone_tan = [1 => 'one', 2 => 'two', 3 => 'three'];
  3899.                 $zone = Zone_Territory_Car::where('province_id', $setcook['province'])->first()->toArray();
  3900.                 if ($setcook['level_of_insurance'] == 'comprehensive') {
  3901.                     $rates = $rate_controller->comprehensive['car'];
  3902.                 } else {
  3903.                     $rates = $rate_controller->total_loss_only['car'];
  3904.                 }
  3905.  
  3906.                 $formulation = array(
  3907.                     'degradation_rate' => $product['quest_car']['degradation_rate'],
  3908.                     'additional_rate' => $product['quest_car']['additional_rate'],
  3909.                     'car_year' => $setcook['car_year'],
  3910.                     'additional' => $additional_controller,
  3911.                 );
  3912.  
  3913.                 if ($product['quest_car']['degradation_year_condition'] < (date('Y') - $formulation['car_year'])) {
  3914.                     $now_value = $setcook['car_value'] - ($setcook['car_value'] / 100) * $formulation['degradation_rate'];
  3915.                 } else {
  3916.                     $now_value = $setcook['car_value'];
  3917.                 }
  3918.  
  3919.                 foreach ($product['coverage_car_' . $setcook['level_of_insurance']] as $key => $value) {
  3920.                     if ($value['up_to'] > 0) {
  3921.                         if ($value['up_to'] >= $now_value) {
  3922.                             $formulation['territory_one_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][$key]['territory_one_rate'];
  3923.                             $formulation['territory_two_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][$key]['territory_two_rate'];
  3924.                             $formulation['territory_three_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][$key]['territory_three_rate'];
  3925.                             break;
  3926.                         }
  3927.                     } else {
  3928.                         $formulation['territory_one_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][4]['territory_one_rate'];
  3929.                         $formulation['territory_two_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][4]['territory_two_rate'];
  3930.                         $formulation['territory_three_rate'] = $product['coverage_car_' . $setcook['level_of_insurance']][4]['territory_three_rate'];
  3931.                     }
  3932.                 }
  3933.  
  3934.                 $condition = array(
  3935.                     'rates_condition' => $rates,
  3936.                     'degradation_year_condition' => $product['quest_car']['degradation_year_condition'],
  3937.                     'additional_year_condition' => $product['quest_car']['additional_year_condition'],
  3938.                     'zone_id' => $zone['zone_id'],
  3939.                     'product_id' => $product['id'],
  3940.                     'level' => $setcook['level_of_insurance'],
  3941.                 );
  3942.  
  3943.                 if (isset($setcook['feature'])) {
  3944.                     $condition['features'] = $setcook['feature'];
  3945.                 }
  3946.                 if (isset($setcook['addition'])) {
  3947.                     $condition['additional'] = $setcook['addition'];
  3948.                 }
  3949.  
  3950.                 $formulation['admin_fee'] = $product['quest_car']['admin_fee'];
  3951.                 $formulation['materai_fee'] = $product['quest_car']['materai_fee'];
  3952.  
  3953.                 $prems = $this->doCalculation($type, $setcook['car_value'], $formulation, $condition);
  3954.                 $product['premi'] = rupiah($prems['premi']);
  3955.                 $product['premi_num'] = $prems['premi'];
  3956.                 $product['transparency'] = $prems['sorted'];
  3957.             } elseif ($type == 'motorcycle') {
  3958.                 $zone_tan = [1 => 'one', 2 => 'two', 3 => 'three'];
  3959.                 $zone = Zone_Territory_Motorcycle::where('province_id', $setcook['province'])->first()->toArray();
  3960.                 if ($setcook['level_of_insurance'] == 'comprehensive') {
  3961.                     $rates = $rate_controller->comprehensive['motorcycle'];
  3962.                 } else {
  3963.                     $rates = $rate_controller->total_loss_only['motorcycle'];
  3964.                 }
  3965.  
  3966.                 $formulation = array(
  3967.                     'degradation_rate' => $product['quest_motorcycle']['degradation_rate'],
  3968.                     'additional_rate' => $product['quest_motorcycle']['additional_rate'],
  3969.                     'motorcycle_year' => $setcook['motorcycle_year'],
  3970.                     'territory_one_rate' => $product['coverage_motorcycle_' . $setcook['level_of_insurance']][0]['territory_one_rate'],
  3971.                     'territory_two_rate' => $product['coverage_motorcycle_' . $setcook['level_of_insurance']][0]['territory_two_rate'],
  3972.                     'territory_three_rate' => $product['coverage_motorcycle_' . $setcook['level_of_insurance']][0]['territory_three_rate'],
  3973.                     'additional' => $additional_controller,
  3974.                     //'territory_custom_rate' => $product[ 'coverage_motorcycle_' . $setcook['level_of_insurance'] ][0]['territory_custom_rate'],
  3975.                 );
  3976.  
  3977.                 $condition = array(
  3978.                     'rates_condition' => $rates,
  3979.                     'degradation_year_condition' => $product['quest_motorcycle']['degradation_year_condition'],
  3980.                     'additional_year_condition' => $product['quest_motorcycle']['additional_year_condition'],
  3981.                     'zone_id' => $zone['zone_id'],
  3982.                     'product_id' => $product['id'],
  3983.                     'level' => $setcook['level_of_insurance'],
  3984.                 );
  3985.  
  3986.                 if (isset($setcook['feature'])) {
  3987.                     $condition['features'] = $setcook['feature'];
  3988.                 }
  3989.                 if (isset($setcook['addition'])) {
  3990.                     $condition['additional'] = $setcook['addition'];
  3991.                 }
  3992.  
  3993.                 /*
  3994.                 if(count($product[ 'additional_' . $prefix ])>0){
  3995.                 foreach ( $product[ 'additional_' . $prefix ] as $label => $value ) {
  3996.                     if ( strpos( $label, 'earthquake_with_tsunami' ) !== false ) {
  3997.                         if ( $label == 'earthquake_with_tsunami_zone_' . $zone_tan[ $condition['zone_id'] ] and ! is_null( $value ) ) {
  3998.                             $product['additional']['earthquake_with_tsunami'] = array(
  3999.                                 'value' => (float) $value,
  4000.                                 'type'  => $additional_controller['vehicle']['earthquake_with_tsunami']
  4001.                             );
  4002.                         } elseif ( $label == 'earthquake_with_tsunami_zone_custom' and ! is_null( $value ) ) {
  4003.                             $product['additional']['earthquake_with_tsunami'] = array(
  4004.                                 'value' => (float) $value,
  4005.                                 'type'  => $additional_controller['vehicle']['earthquake_with_tsunami']
  4006.                             );
  4007.                         }
  4008.                     }
  4009.                     if ( strpos( $label, 'earthquake_with_tsunami' ) !== false ) {
  4010.                         if ( $label == 'earthquake_with_tsunami_zone_' . $zone_tan[ $condition['zone_id'] ] and ! is_null( $value ) ) {
  4011.                             $product['additional']['earthquake_with_tsunami'] = array(
  4012.                                 'value' => (float) $value,
  4013.                                 'type'  => $additional_controller['vehicle']['earthquake_with_tsunami']
  4014.                             );
  4015.                         } elseif ( $label == 'earthquake_with_tsunami_custom' and ! is_null( $value ) ) {
  4016.                             $product['additional']['earthquake_with_tsunami'] = array(
  4017.                                 'value' => (float) $value,
  4018.                                 'type'  => $additional_controller['vehicle']['earthquake_with_tsunami']
  4019.                             );
  4020.                         }
  4021.                     }
  4022.  
  4023.                     /*
  4024.                     if ( ( strpos( $label, 'earthquake_with_tsunami' ) === false and strpos( $label, 'earthquake_with_tsunami' ) === false ) and $value != 0 ) {
  4025.                         if ( isset( $additional_controller['vehicle'][ $label ] ) ) {
  4026.                             $product['additional'][ $label ] = array(
  4027.                                 'value' => $value,
  4028.                                 'type'  => $additional_controller['vehicle'][ $label ]
  4029.                             );
  4030.                         }
  4031.                     }*/
  4032.                 $formulation['admin_fee'] = $product['quest_motorcycle']['admin_fee'];
  4033.                 $formulation['materai_fee'] = $product['quest_motorcycle']['materai_fee'];
  4034.  
  4035.                 $prems = $this->doCalculation($type, $setcook['motorcycle_value'], $formulation, $condition);
  4036.                 $product['premi'] = rupiah($prems['premi']);
  4037.                 $product['premi_num'] = $prems['premi'];
  4038.                 $product['transparency'] = $prems['sorted'];
  4039.             } elseif ($type == 'property') {
  4040.                 if ($setcook['level_of_insurance'] == 'standard') {
  4041.                     $rates = $rate_controller->standard['property'];
  4042.                     $rates = $rates[$product['coverage_property_standard'][0]['category']];
  4043.                 } elseif ($setcook['level_of_insurance'] == 'earthquake') {
  4044.                     $rates = $rate_controller->earthquake['property'];
  4045.                     $zone = Zone_Territory_Earthquake::where('city_id', $setcook['city'])->first()->toArray();
  4046.  
  4047.                 } elseif ($setcook['level_of_insurance'] == 'all_risk') {
  4048.                     $rates = $rate_controller->all['property'];
  4049.                     $rates = $rates[$product['coverage_property_all'][0]['category']];
  4050.                 }
  4051.  
  4052.                 $formulation = array(
  4053.                     'additional' => $additional_controller,
  4054.                 );
  4055.  
  4056.                 // jika dia perhitungannya cuma content
  4057.                 if ($setcook['type_of_insurance'] == 'contents.only') {
  4058.                     $counting = $setcook['estimated_value_of_the_contents_to_cover'];
  4059.                 } else {
  4060.                     $counting = $setcook['estimated_value_of_the_property_to_cover'];
  4061.                 }
  4062.  
  4063.                 if ($product['type_of_insurance'] == 'all_risk') {
  4064.                     $cons = array('1' => 'class_one_rate', '2' => 'class_two_rate', '3' => 'class_three_rate');
  4065.                     $cns = $cons[$setcook['construction_property']];
  4066.  
  4067.                     foreach ($product['coverage_property_all'] as $key => $value) {
  4068.                         if ($value['property'] == $setcook['class_property']) {
  4069.                             if (!is_null($product['coverage_property_all'][$key]['class_custom_rate']) and $product['coverage_property_all'][$key]['class_custom_rate'] != '') {
  4070.                                 $formulation['custom_rate'] = $product['coverage_property_all'][$key]['class_custom_rate'];
  4071.                             } else {
  4072.                                 if ($product['coverage_property_all'][0][$cns] == 'top' or $product['coverage_property_all'][0][$cns] == 'bottom') {
  4073.                                     $formulation['custom_rate'] = $rates[$setcook['construction_property']][$product['coverage_property_all'][0][$cns]];
  4074.                                 } else {
  4075.                                     $formulation['custom_rate'] = (float)$product['coverage_property_all'][0][$cns];
  4076.                                 }
  4077.                             }
  4078.                         }
  4079.                     }
  4080.                 } elseif ($product['type_of_insurance'] == 'standard') {
  4081.                     $cons = array('1' => 'class_one_rate', '2' => 'class_two_rate', '3' => 'class_three_rate');
  4082.                     $cns = $cons[$setcook['construction_property']];
  4083.  
  4084.                     foreach ($product['coverage_property_standard'] as $key => $value) {
  4085.                         if ($value['property'] == $setcook['class_property']) {
  4086.                             if (!is_null($product['coverage_property_standard'][$key]['class_custom_rate']) and $product['coverage_property_standard'][$key]['class_custom_rate'] != '') {
  4087.                                 $formulation['custom_rate'] = $product['coverage_property_standard'][$key]['class_custom_rate'];
  4088.                             } else {
  4089.                                 if ($product['coverage_property_standard'][0][$cns] == 'top' or $product['coverage_property_standard'][0][$cns] == 'bottom') {
  4090.                                     $formulation['custom_rate'] = $rates[$setcook['construction_property']][$product['coverage_property_standard'][0][$cns]];
  4091.                                 } else {
  4092.                                     $formulation['custom_rate'] = (float)$product['coverage_property_standard'][0][$cns];
  4093.                                 }
  4094.                             }
  4095.                         }
  4096.                     }
  4097.                 } else {
  4098.                     $cons = array('1' => 'zone_one_rate', '2' => 'zone_two_rate', '3' => 'zone_three_rate', 4 => 'zone_four_rate', 5=>'zone_five_rate');
  4099.                     $cns = $cons[$zone['zone_id']];
  4100.  
  4101.                     $class_property = array('below.6' =>1,
  4102.                                             'in.6-18' =>2,
  4103.                                             'up.to.18'=>3,
  4104.                                             'park.up.to.24'=>4,
  4105.                                             'less.than.3.storeys'=>5,
  4106.                                             'boarding.house'=>6,
  4107.                                             'floating'=>7);
  4108.                     $csp = $setcook['construction_property'];
  4109.                     //dd(['class' => $csp, 'cate' => $setcook['construction_property'], 'product' => $product['coverage_property_earthquake']]);
  4110.  
  4111.                     foreach ($product['coverage_property_earthquake'] as $key => $value) {
  4112.                         if ($value['category'] == $csp and $value['class']==1) {
  4113.                             if (!is_null($product['coverage_property_earthquake'][$key]['zone_custom_rate']) and (integer)$product['coverage_property_earthquake'][$key]['zone_custom_rate'] > 0) {
  4114.                                 $formulation['custom_rate'] = $product['coverage_property_standard'][$key]['zone_custom_rate'];
  4115.                             } else {
  4116.                                 if ($product['coverage_property_earthquake'][0][$cns] == 'fixed') {
  4117.                                     $formulation['custom_rate'] = $rates[$csp][1][$zone['zone_id']][$product['coverage_property_earthquake'][0][$cns]];
  4118.                                 } else {
  4119.                                     $formulation['custom_rate'] = (float)$product['coverage_property_earthquake'][0][$cns];
  4120.                                 }
  4121.                             }
  4122.                         }
  4123.                     }
  4124. //                    dd($formulation);
  4125.                 }
  4126.  
  4127.                 if (isset($product['additional_' . $prefix]) and is_array(isset($product['additional_' . $prefix]))) {
  4128.                     foreach ($product['additional_' . $prefix] as $label => $value) {
  4129.                         if ($setcook['province'] == '3' or $setcook['province'] == '6' or $setcook['province'] == '9') {
  4130.                             $product['additional']['around_jakarta_zone_one'] = array(
  4131.                                 'value' => $product['additional_' . $prefix]['around_jakarta_zone_one'],
  4132.                                 'type' => $additional_controller['property']['around_jakarta_zone_one']
  4133.                             );
  4134.                         } else {
  4135.                             $product['additional']['outside_around_jakarta_zone_one'] = array(
  4136.                                 'value' => $product['additional_' . $prefix]['outside_around_jakarta_zone_one'],
  4137.                                 'type' => $additional_controller['property']['outside_around_jakarta_zone_one']
  4138.                             );
  4139.                             $product['additional']['outside_around_jakarta_zone_two'] = array(
  4140.                                 'value' => $product['additional_' . $prefix]['outside_around_jakarta_zone_two'],
  4141.                                 'type' => $additional_controller['property']['outside_around_jakarta_zone_two']
  4142.                             );
  4143.                         }
  4144.  
  4145.                         if (strpos($label, 'outside_around_jakarta_zone') === false and strpos($label, 'around_jakarta_zone') === false) {
  4146.                             if ($value > 0 and !is_null($value)) {
  4147.                                 if (isset($additional_controller['property'][$label])) {
  4148.                                     $product['additional'][$label] = array(
  4149.                                         'value' => $value,
  4150.                                         'type' => $additional_controller['property'][$label]
  4151.                                     );
  4152.                                 }
  4153.                             }
  4154.                         }
  4155.                     }
  4156.                 }
  4157.  
  4158.                 $formulation['admin_fee'] = $product['quest_property']['admin_fee'];
  4159.                 $formulation['materai_fee'] = $product['quest_property']['materai_fee'];
  4160.                 $condition = array(
  4161.                     'product_id' => $product['id'],
  4162.                     'level' => $setcook['level_of_insurance'],
  4163.                     'province' => $setcook['province'],
  4164.                     'bundle_zone' => 1,
  4165.                     'rsmd_zone' => 1,
  4166.                 );
  4167.  
  4168.                 if(isset($product['coverage_property_standard'][0]['bundle_zone'])){
  4169.                     $condition['bundle_zone'] = $product['coverage_property_standard'][0]['bundle_zone'];
  4170.                 }
  4171.  
  4172.                 if(isset($product['coverage_property_standard'][0]['rsmd_zone'])){
  4173.                     $condition['rsmd_zone'] = $product['coverage_property_standard'][0]['rsmd_zone'];
  4174.                 }
  4175.  
  4176.                 if (isset($setcook['feature'])) {
  4177.                     $condition['features'] = $setcook['feature'];
  4178.                 }
  4179.                 if (isset($setcook['addition'])) {
  4180.                     $condition['additional'] = $setcook['addition'];
  4181.                 }
  4182.  
  4183.                 $prems = $this->doCalculation($type, $counting, $formulation, $condition);
  4184.                 $product['base_premi'] = (integer)$prems['premi'];
  4185.                 $product['premi'] = rupiah($prems['premi']);
  4186.                 $product['premi_num'] = $prems['premi'];
  4187.                 $product['transparency'] = $prems['sorted'];
  4188.             } elseif ($type == 'personal.accident') {
  4189.                 switch ($setcook['type_of_work']) {
  4190.                     case 'one':
  4191.                         $premis = $product['coverage_self_accident'][0]['class_one_rate'];
  4192.                         break;
  4193.                     case 'two':
  4194.                         $premis = $product['coverage_self_accident'][0]['class_two_rate'];
  4195.                         break;
  4196.                     case 'three':
  4197.                         $premis = $product['coverage_self_accident'][0]['class_three_rate'];
  4198.                         break;
  4199.                     case 'four':
  4200.                         $premis = $product['coverage_self_accident'][0]['class_four_rate'];
  4201.                         break;
  4202.                     default:
  4203.                         $premis = $product['coverage_self_accident'][0]['class_five_rate'];
  4204.                         break;
  4205.                 }
  4206.  
  4207.                 if (isset($setcook['type_of_work_couple']) and $setcook['type_of_cover'] == 'couple') {
  4208.                     switch ($setcook['type_of_work_couple']) {
  4209.                         case 'one':
  4210.                             $premis += $product['coverage_self_accident_other'][0]['class_one_rate'];
  4211.                             break;
  4212.                         case 'two':
  4213.                             $premis += $product['coverage_self_accident_other'][0]['class_two_rate'];
  4214.                             break;
  4215.                         case 'three':
  4216.                             $premis += $product['coverage_self_accident_other'][0]['class_three_rate'];
  4217.                             break;
  4218.                         case 'four':
  4219.                             $premis += $product['coverage_self_accident_other'][0]['class_four_rate'];
  4220.                             break;
  4221.                         default:
  4222.                             $premis += $product['coverage_self_accident_other'][0]['class_five_rate'];
  4223.                             break;
  4224.                     }
  4225.                 }
  4226.  
  4227.                 $formulation['admin_fee'] = $product['quest_personal_accident']['admin_fee'];
  4228.                 $formulation['materai_fee'] = $product['quest_personal_accident']['materai_fee'];
  4229.  
  4230.                 $prems = $this->doCalculation($type, $premis, $formulation, $condition);
  4231.                 $product['premi'] = rupiah($prems['premi']);
  4232.                 $product['premi_num'] = $prems['premi'];
  4233.                 $product['transparency'] = $prems['sorted'];
  4234.             } elseif ($type == 'personal.accident.age') {
  4235.                 $condition = array('product_id' => $product['id']);
  4236.  
  4237.                 $now = date_create(date('Y-m-d'));
  4238. //              $condition = array('yearly');
  4239. //              $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4240.                 $formulation['use'] = $life_count;
  4241.                 $condition['premi']['main'] = array();
  4242.                 $condition['premi']['couple'] = array();
  4243.                 $condition['premi']['main']['yearly'] = 0;
  4244.                 $condition['premi']['main']['semester'] = 0;
  4245.                 $condition['premi']['main']['quartal'] = 0;
  4246.                 $condition['premi']['main']['monthly'] = 0;
  4247.                 $condition['premi']['couple']['yearly'] = [];
  4248.                 $condition['premi']['couple']['semester'] = [];
  4249.                 $condition['premi']['couple']['quartal'] = [];
  4250.                 $condition['premi']['couple']['monthly'] = [];
  4251.  
  4252.                 $condition['premi']['main']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4253.                 $condition['premi']['main']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4254.                 $condition['premi']['main']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4255.                 $condition['premi']['main']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4256.  
  4257.                 if (isset($setcook['feature'])) {
  4258.                     $condition['features'] = $setcook['feature'];
  4259.                 }
  4260.  
  4261.                 if ($setcook['type_of_cover'] == 'couple') {
  4262.  
  4263.                     foreach ($product['coverage_self_accident_age_couple'] as $k => $value) {
  4264.                         $condition['premi']['couple']['yearly'][$k] = $value['yearly_rates'];
  4265.                         $condition['premi']['couple']['semester'][$k] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4266.                         $condition['premi']['couple']['quartal'][$k] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4267.                         $condition['premi']['couple']['monthly'][$k] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4268.                     }
  4269.  
  4270.                 } else {
  4271.                     $condition['premi']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4272.                     $condition['premi']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4273.                     $condition['premi']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4274.                     $condition['premi']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4275.                 }
  4276.  
  4277.                 $formulation['admin_fee'] = $product['quest_personal_accident']['admin_fee'];
  4278.                 $formulation['materai_fee'] = $product['quest_personal_accident']['materai_fee'];
  4279.                 $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4280.                 foreach ($condition['premi'] as $key => $val) {
  4281.                     $product[$key] = rupiah($val);
  4282.                 }
  4283.                 $product['premi'] = rupiah($prems['premi']);
  4284.                 $product['transparency'] = $prems['sorted'];
  4285.                 foreach ($prems['any'] as $key => $val) {
  4286.                     $product[$key] = $val;
  4287.                 }
  4288.             } elseif ($type == 'travel') {
  4289.                 switch ($setcook['travel_category']) {
  4290.                     case 'asean':
  4291.                         $premis = $product['coverage_travel_asean'][0];
  4292.                         break;
  4293.                     case 'asia':
  4294.                         $premis = $product['coverage_travel_asia'][0];
  4295.                         break;
  4296.                     case 'worldwide_incl_shenzeng':
  4297.                         $premis = $product['coverage_travel_worldwide_include_shenzeng'][0];
  4298.                         break;
  4299.                     case 'worldwide_excl_shenzeng':
  4300.                         $premis = $product['coverage_travel_worldwide_exclude_shenzeng'][0];
  4301.                         break;
  4302.                     default:
  4303.                         $premis = $product['coverage_travel_domestic'][0];
  4304.                         break;
  4305.                 }
  4306.                 $setcook['travel_category'] = trans('questionnaire.travel.' . $setcook['travel_category']);
  4307.  
  4308.                 $arrival = date_create(str_replace('/', '-', $setcook['arrival_date']));
  4309.                 $departure = date_create(str_replace('/', '-', $setcook['departure_date']));
  4310.                 $date_diff = (integer)date_diff($arrival, $departure)->format('%a') + 1;
  4311.  
  4312.                 if ($setcook['who_is_the_insurance_for'] != 'family') {
  4313.                     $people = [
  4314.                         'just.me' => 'one_person',
  4315.                         'couple' => 'two_person',
  4316.                     ];
  4317.                     $select = $people[$setcook['who_is_the_insurance_for']];
  4318.                     $setrow = $premis[$select];
  4319.                     $count = 1;
  4320.                 } else {
  4321.                     $counted = [3 => 'three_person', 4 => 'four_person', 5 => 'five_person'];
  4322.                     $select = $counted[$setcook['group_count']];
  4323.                     $setrow = $premis[$select];
  4324.                     $count = 1;
  4325.                 }
  4326.  
  4327.                 $condition = [
  4328.                     'max_days' => $premis['days_min'],
  4329.                     'difference' => $date_diff - $premis['days_min'],
  4330.                     'people' => $select, 'days' => $date_diff,
  4331.                     'extra' => $premis['extra'],
  4332.                     'trip_type' => $setcook['trip_type']
  4333.                 ];
  4334.                 $formulation = [
  4335.                     'harga' => $count * $setrow,
  4336.                     'extra' => $premis['extra_' . $select],
  4337.                     'annual' => $product['coverage_travel_annual'][0][$select]
  4338.                 ];
  4339.                 if (isset($setcook['group_count'])) {
  4340.                     $formulation['group_count'] = $setcook['group_count'];
  4341.                 }
  4342.  
  4343.                 $formulation['admin_fee'] = $product['quest_travel']['admin_fee'];
  4344.                 $formulation['materai_fee'] = $product['quest_travel']['materai_fee'];
  4345.  
  4346.                 $prems = $this->doCalculation($type, $premis, $formulation, $condition);
  4347.                 $product['premi'] = rupiah($prems['premi']);
  4348.                 $product['premi_num'] = $prems['premi'];
  4349.                 $product['transparency'] = $prems['sorted'];
  4350.  
  4351.             } elseif ($type == 'health') {
  4352.                 $condition = array('product_id' => $product['id']);
  4353.  
  4354.                 $now = date_create(date('Y-m-d'));
  4355. //              $condition = array('yearly');
  4356. //              $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4357.                 $formulation['use'] = $life_count;
  4358.                 $condition['premi']['main'] = array();
  4359.                 $condition['premi']['other'] = array();
  4360.                 $condition['premi']['main']['yearly'] = 0;
  4361.                 $condition['premi']['main']['semester'] = 0;
  4362.                 $condition['premi']['main']['quartal'] = 0;
  4363.                 $condition['premi']['main']['monthly'] = 0;
  4364.                 $condition['premi']['other']['yearly'] = [];
  4365.                 $condition['premi']['other']['semester'] = [];
  4366.                 $condition['premi']['other']['quartal'] = [];
  4367.                 $condition['premi']['other']['monthly'] = [];
  4368.                 $condition['premi']['children']['yearly'] = [];
  4369.                 $condition['premi']['children']['semester'] = [];
  4370.                 $condition['premi']['children']['quartal'] = [];
  4371.                 $condition['premi']['children']['monthly'] = [];
  4372.  
  4373.                 $condition['premi']['main']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4374.                 $condition['premi']['main']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4375.                 $condition['premi']['main']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4376.                 $condition['premi']['main']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4377.  
  4378.                 if (isset($setcook['feature'])) {
  4379.                     $condition['features'] = $setcook['feature'];
  4380.                 }
  4381.  
  4382.                 if ($setcook['who_need_the_cover'] == 'couple') {
  4383.  
  4384.                     foreach ($product['coverage_health_others'] as $k => $value) {
  4385.                         $condition['premi']['other']['yearly'][$k] = $value['yearly_rates'];
  4386.                         $condition['premi']['other']['semester'][$k] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4387.                         $condition['premi']['other']['quartal'][$k] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4388.                         $condition['premi']['other']['monthly'][$k] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4389.                     }
  4390.  
  4391.                 } elseif ($setcook['who_need_the_cover'] == 'family') {
  4392.                     foreach ($product['coverage_health_others'] as $k => $value) {
  4393.                         $condition['premi']['other']['yearly'][$k] = $value['yearly_rates'];
  4394.                         $condition['premi']['other']['semester'][$k] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4395.                         $condition['premi']['other']['quartal'][$k] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4396.                         $condition['premi']['other']['monthly'][$k] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4397.                     }
  4398.  
  4399.                     $births = array();
  4400.                     $children = array(1, 2, 3, 4);
  4401.  
  4402.                     foreach ($children as $kid) {
  4403.                         if (isset($setcook['family_children_' . $kid])) {
  4404.                             $lato = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_children_' . $kid]))));
  4405.                             $births['kid_' . $kid] = date_diff($now, $lato)->y;
  4406.                             $get_what['kid_' . $kid] = null;
  4407.                         }
  4408.                     }
  4409.  
  4410.                     $i = 0;
  4411.                     foreach ($births as $role => $fam) {
  4412.                         if (is_null($get_what[$role])) {
  4413.                             foreach ($product['coverage_health_childrens'] as $value) {
  4414.                                 if ($value['age_min'] <= $fam) {
  4415.                                     $condition['premi']['children']['yearly'][$i] = $value['yearly_rates'];
  4416.                                     $condition['premi']['children']['semester'][$i] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4417.                                     $condition['premi']['children']['quartal'][$i] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4418.                                     $condition['premi']['children']['monthly'][$i] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4419.                                     goto adding_get_what_to_health;
  4420.                                 }
  4421.                             }
  4422.                             adding_get_what_to_health:
  4423.                             $get_what[$role] = 'filled';
  4424.                             $i++;
  4425.                         }
  4426.                     }
  4427.                 } else {
  4428.                     $condition['premi']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4429.                     $condition['premi']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4430.                     $condition['premi']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4431.                     $condition['premi']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4432.                 }
  4433.  
  4434.                 $formulation['admin_fee'] = $product['quest_health']['admin_fee'];
  4435.                 $formulation['materai_fee'] = $product['quest_health']['materai_fee'];
  4436.                 $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4437.                 foreach ($condition['premi'] as $key => $val) {
  4438.                     $product[$key] = rupiah($val);
  4439.                 }
  4440.                 $product['premi'] = rupiah($prems['premi']);
  4441.  
  4442.                 $product['transparency'] = $prems['sorted'];
  4443.                 foreach ($prems['any'] as $key => $val) {
  4444.                     $product[$key] = $val;
  4445.                 }
  4446.             } elseif ($type == 'life') {
  4447.                 $condition = array('product_id' => $product['id']);
  4448.  
  4449.                 $now = date_create(date('Y-m-d'));
  4450. //              $condition = array('yearly');
  4451. //              $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4452.                 $formulation['use'] = $life_count;
  4453.                 $condition['premi']['main'] = array();
  4454.                 $condition['premi']['other'] = array();
  4455.                 $condition['premi']['main']['yearly'] = 0;
  4456.                 $condition['premi']['main']['semester'] = 0;
  4457.                 $condition['premi']['main']['quartal'] = 0;
  4458.                 $condition['premi']['main']['monthly'] = 0;
  4459.                 $condition['premi']['other']['yearly'] = [];
  4460.                 $condition['premi']['other']['semester'] = [];
  4461.                 $condition['premi']['other']['quartal'] = [];
  4462.                 $condition['premi']['other']['monthly'] = [];
  4463.                 $condition['premi']['children']['yearly'] = [];
  4464.                 $condition['premi']['children']['semester'] = [];
  4465.                 $condition['premi']['children']['quartal'] = [];
  4466.                 $condition['premi']['children']['monthly'] = [];
  4467.  
  4468.                 $condition['premi']['main']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4469.                 $condition['premi']['main']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4470.                 $condition['premi']['main']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4471.                 $condition['premi']['main']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4472.  
  4473.                 if (isset($setcook['feature'])) {
  4474.                     $condition['features'] = $setcook['feature'];
  4475.                 }
  4476.  
  4477.                 if ($setcook['how_many_people_insured'] == 'couple') {
  4478.  
  4479.                     foreach ($product['coverage_life_others'] as $k => $value) {
  4480.                         $condition['premi']['other']['yearly'][$k] = $value['yearly_rates'];
  4481.                         $condition['premi']['other']['semester'][$k] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4482.                         $condition['premi']['other']['quartal'][$k] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4483.                         $condition['premi']['other']['monthly'][$k] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4484.                     }
  4485.  
  4486.                 } elseif ($setcook['how_many_people_insured'] == 'family') {
  4487.                     foreach ($product['coverage_life_others'] as $k => $value) {
  4488.                         $condition['premi']['other']['yearly'][$k] = $value['yearly_rates'];
  4489.                         $condition['premi']['other']['semester'][$k] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4490.                         $condition['premi']['other']['quartal'][$k] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4491.                         $condition['premi']['other']['monthly'][$k] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4492.                     }
  4493.  
  4494.                     $births = array();
  4495.                     $children = array(1, 2, 3, 4);
  4496.  
  4497.                     foreach ($children as $kid) {
  4498.                         if (isset($setcook['family_children_' . $kid])) {
  4499.                             $lato = date_create(date('Y-m-d', strtotime(str_replace('/', '-', $setcook['family_children_' . $kid]))));
  4500.                             $births['kid_' . $kid] = date_diff($now, $lato)->y;
  4501.                             $get_what['kid_' . $kid] = null;
  4502.                         }
  4503.                     }
  4504.  
  4505.                     $i = 0;
  4506.                     foreach ($births as $role => $fam) {
  4507.                         if (is_null($get_what[$role])) {
  4508.                             foreach ($product['coverage_life_childrens'] as $value) {
  4509.                                 if ($value['age_min'] <= $fam) {
  4510.                                     $condition['premi']['children']['yearly'][$i] = $value['yearly_rates'];
  4511.                                     $condition['premi']['children']['semester'][$i] = is_null($value['semester_rates']) ? 0 : $value['semester_rates'];
  4512.                                     $condition['premi']['children']['quartal'][$i] = is_null($value['quartal_rates']) ? 0 : $value['quartal_rates'];
  4513.                                     $condition['premi']['children']['monthly'][$i] = is_null($value['monthly_rates']) ? 0 : $value['monthly_rates'];
  4514.                                     goto adding_get_what_to;
  4515.                                 }
  4516.                             }
  4517.                             adding_get_what_to:
  4518.                             $get_what[$role] = 'filled';
  4519.                             $i++;
  4520.                         }
  4521.                     }
  4522.                 } else {
  4523.                     $condition['premi']['yearly'] = $product[$coverage][0]['yearly_rates'];
  4524.                     $condition['premi']['semester'] = is_null($product[$coverage][0]['semester_rates']) ? 0 : $product[$coverage][0]['semester_rates'];
  4525.                     $condition['premi']['quartal'] = is_null($product[$coverage][0]['quartal_rates']) ? 0 : $product[$coverage][0]['quartal_rates'];
  4526.                     $condition['premi']['monthly'] = is_null($product[$coverage][0]['monthly_rates']) ? 0 : $product[$coverage][0]['monthly_rates'];
  4527.                 }
  4528.  
  4529.                 $formulation['admin_fee'] = $product['quest_life']['admin_fee'];
  4530.                 $formulation['materai_fee'] = $product['quest_life']['materai_fee'];
  4531.                 $prems = $this->doCalculation($type, 0, $formulation, $condition);
  4532.                 foreach ($condition['premi'] as $key => $val) {
  4533.                     $product[$key] = rupiah($val);
  4534.                 }
  4535.                 $product['premi'] = rupiah($prems['premi']);
  4536.                 $product['transparency'] = $prems['sorted'];
  4537.                 foreach ($prems['any'] as $key => $val) {
  4538.                     $product[$key] = $val;
  4539.                 }
  4540.             }
  4541.         }
  4542.  
  4543.         $product_meta = Insurance_Product_Meta::where('product_id', $product['id'])->first();
  4544.         if (isset($product_meta->image) && $product_meta != '') {
  4545.             $product['img'] = $product_meta->image;
  4546.         } else {
  4547.             $product['img'] = url('/image/global/dummy-logo.jpg');
  4548.         }
  4549.         $product['share_url'] = URL::full();
  4550.         $product['testimonies'] = InsuranceProductReview::with('member')->where('product_id', $product["id"])->get()->toArray();
  4551.         $data = array(
  4552.             'provider' => $provider,
  4553.             'product' => $product,
  4554.             'custom_css' => 'product_detail.css'
  4555.         );
  4556.         // prepare feature and benefit
  4557.         $_feature = $product[$feature];
  4558.         if (isset($benefit)) {
  4559.             $_benefit = $product[$benefit];
  4560.         }
  4561.  
  4562.         $feature = [];
  4563.         $benefit = [];
  4564.  
  4565.         $x = 0;
  4566.         if (sizeof($_feature) > 0):
  4567.             $dummy = json_decode($_feature['dummy_benefit'],true);
  4568.  
  4569.             foreach ($_feature as $k => $v) {
  4570.                 if ($k != 'product_id' && $k != 'count' && $k != "sort_features" && $k != 'dummy_benefit') {
  4571.                     if($v != 0 and !is_null($v)){
  4572.                         $ben = null;
  4573.                         if(isset($dummy[$k])){
  4574.                             $ben = $dummy[$k];
  4575.                         }
  4576.                         $kess = str_replace("_", '.', $k);
  4577.                         $feature[$x] = ['name' => trans('feature.' . $kess), 'available' => $v,'benefit' => $ben];
  4578.                         $x++;
  4579.                     }
  4580.                 }
  4581.             }
  4582.         endif;
  4583.         /*foreach($featureController->property as $value){
  4584.             $feature->orWhere($value['name'], 1);
  4585.         }*/
  4586.         $data['product']['feature'] = $feature;
  4587.         if (isset($_benefit)) {
  4588.             if (sizeof($_benefit) > 0) :
  4589.                 foreach ($_benefit as $k => $v) {
  4590.                     if ($k != 'product_id') {
  4591.                         $k = ___('benefit.' . $product['type'] . '.' . $k);
  4592.                         $benefit[$k] = rupiah($v);
  4593.                     }
  4594.                 }
  4595.             endif;
  4596.         }
  4597.         $data['product']['benefit'] = $benefit;
  4598.  
  4599.         $lang = LaravelLocalization::getCurrentLocale();
  4600.         $data['product']['detail'] = Insurance_Product_Detail::where('product_id', $product['id'])->where('lang', $lang)->first()->toArray();
  4601.         $data['provider']['detail'] = Insurance_Provider_Detail::where('provider_id', $provider['id'])->first()->toArray();
  4602.         $data['title'] = $product['name'] . ' by ' . $provider['name'] . ' - Bandingin.com';
  4603.         if (Auth::check()) {
  4604.             $data['member'] = User::find(Auth::user()->id)->toArray();
  4605.             $data['member']['extra'] = json_decode($data['member']['data'], true);
  4606.         }
  4607.         // data configuration
  4608.         $data['configuration'] = $setcook;
  4609.         $data['product_ids'] = $products->id;
  4610.  
  4611.         return $data;
  4612.     }
  4613.  
  4614.     /**
  4615.      * @param $type
  4616.      * @param $value
  4617.      * @param null $formulation
  4618.      * @param null $condition
  4619.      *
  4620.      * @return array
  4621.      */
  4622.     public function doCalculation($type, $value, $formulation = null, $condition = null)
  4623.     {
  4624.         $base_premi = 0;
  4625.         $value = (integer)$value;
  4626.         $sorted = array();
  4627.         $features_breakdown = [];
  4628.         $additional_breakdown = [];
  4629.         $amount = 0;
  4630.         $percented = 0;
  4631.         $addons = 0;
  4632.         $any = [];
  4633.  
  4634.         if (isset($condition['features'])) {
  4635.             $features = Insurance_Features_Additional_Prices::where('product_id', $condition['product_id'])
  4636.                 ->whereIn('key', $condition['features'])
  4637.                 ->get()
  4638.                 ->toArray();
  4639.             // features now based on percentages
  4640.             foreach ($features as $items) {
  4641.                 if ($items['type'] == 'amount') {
  4642.                     $amount += (integer)$items['value'];
  4643.                 } elseif ($items['type'] == 'percentages') {
  4644.                     $percented += (float)$items['value'];
  4645.                 }
  4646.             }
  4647.         }
  4648.  
  4649.         switch ($type) {
  4650.             case 'car':
  4651.                 // ini gua ngambil harga yang di degradasi, belum di round ya
  4652.                 // value divide by 100
  4653.                 // then multiply by degradation rate
  4654.                 // then now date min car year
  4655.                 // the all the result will be multiply
  4656.                 $sorted['value_price'] = ['message' => rupiah($value)];
  4657.                 if ($condition['degradation_year_condition'] < (date('Y') - $formulation['car_year'])) {
  4658.                     $degradation_premi = $value - ($value / 100) * $formulation['degradation_rate'];
  4659.                 } else {
  4660.                     $degradation_premi = $value;
  4661.                 }
  4662.                 //dd($degradation_premi);
  4663.                 $sorted['degradation'] = [
  4664.                     'year' => date('Y') - $formulation['car_year'],
  4665.                     'message' => $formulation['degradation_rate'] . '%'
  4666.                 ];
  4667.  
  4668.                 // breakdown features
  4669.                 // features now based on percentages
  4670.                 if (isset($features) && is_array($features)) {
  4671.                     foreach ($features as $items) {
  4672.                         if ($items['type'] == 'amount') {
  4673.                             $val = (integer)$items['value'];
  4674.                         } elseif ($items['type'] == 'percentages') {
  4675.                             $val = ($degradation_premi / 100) * (float)$items['value'];
  4676.                         }
  4677.                         $sorted['is_features_use_trans' . str_replace('_', '.', $items['key'])] = [
  4678.                             $items['key'] => $val,
  4679.                             'message' => rupiah($val)
  4680.                         ];
  4681.                     }
  4682.                 }
  4683.  
  4684.                 // disini query harus ngeliat apa dia punya override atau gak, kalo emang gak, ya berarti di
  4685.                 // pake dong territorial ratenya, dan juga territory diliat lagi tipe zonenya.
  4686.                 // value divide by 100 then multiply by territory_rate
  4687.                 // gua cek uptonya dulu ke degradation premi
  4688.                 $tmp = array();
  4689.                 if ($degradation_premi > 0 and $degradation_premi <= 125000000) {
  4690.                     $tmp = $condition['rates_condition'][1];
  4691.                 } elseif ($degradation_premi >= 125000000 and $degradation_premi < 200000000) {
  4692.                     $tmp = $condition['rates_condition'][2];
  4693.                 } elseif ($degradation_premi >= 200000000 and $degradation_premi < 400000000) {
  4694.                     $tmp = $condition['rates_condition'][3];
  4695.                 } elseif ($degradation_premi >= 400000000 and $degradation_premi < 800000000) {
  4696.                     $tmp = $condition['rates_condition'][4];
  4697.                 } else {
  4698.                     $tmp = $condition['rates_condition'][5];
  4699.                 }
  4700.  
  4701.                 if ($condition['zone_id'] == 1) {
  4702.                     if ($formulation['territory_one_rate'] == 'bottom' or $formulation['territory_one_rate'] == 'top') {
  4703.                         $percentages = $tmp[1][$formulation['territory_one_rate']];
  4704.                     } else {
  4705.                         $percentages = (float)$formulation['territory_one_rate'];
  4706.                     }
  4707.                     $sorted['premi_percentages'] = [
  4708.                         'rate' => $percentages,
  4709.                         'message' => $percentages . '%'
  4710.                     ];
  4711.                 } else if ($condition['zone_id'] == 2) {
  4712.                     if ($formulation['territory_two_rate'] == 'bottom' or $formulation['territory_two_rate'] == 'top') {
  4713.                         $percentages = $tmp[2][$formulation['territory_two_rate']];
  4714.                     } else {
  4715.                         $percentages = (float)$formulation['territory_two_rate'];
  4716.                     }
  4717.                     $sorted['premi_percentages'] = [
  4718.                         'rate' => $percentages,
  4719.                         'message' => $percentages . '%'
  4720.                     ];
  4721.                 } else {
  4722.                     if ($formulation['territory_three_rate'] == 'bottom' or $formulation['territory_three_rate'] == 'top') {
  4723.                         $percentages = $tmp[3][$formulation['territory_three_rate']];
  4724.                     } else {
  4725.                         $percentages = (float)$formulation['territory_three_rate'];
  4726.                     }
  4727.                     $sorted['premi_percentages'] = [
  4728.                         'rate' => $percentages,
  4729.                         'message' => $percentages . '%'
  4730.                     ];
  4731.                 }
  4732.  
  4733.                 // jadi disini gua ngubah kalkukasi harusnya itung persen dulu sebelu hitung harga.
  4734.                 if ($condition['additional_year_condition'] < (date('Y') - $formulation['car_year'])) {
  4735.                     $addon_percentages = ($formulation['additional_rate'] / 100);
  4736.                 } else {
  4737.                     $addon_percentages = 0;
  4738.                 }
  4739.                
  4740.                 $sorted['loading_percentages'] = [
  4741.                     'rate' => $addon_percentages,
  4742.                     'message' => $addon_percentages . '%'
  4743.                 ];
  4744.                
  4745.                 $calculations         = $percentages + ($percentages * $addon_percentages);
  4746.                 $base_premi           = ($degradation_premi / 100) * $calculations;
  4747.                 $sorted['base_premi'] = ['premi' => $base_premi, 'message' => rupiah($base_premi)];
  4748.  
  4749.                 $passing = array(
  4750.                     'value' => $degradation_premi,
  4751.                     'type' => 'car',
  4752.                     'additional' => array(),
  4753.                     'level' => $condition['level'],
  4754.                     'id' => $condition['product_id'],
  4755.                     'zone' => $condition['zone_id']
  4756.                 );
  4757.  
  4758.                 // additional
  4759.                 if (isset($condition['additional'])) {
  4760.                     foreach ($condition['additional'] as $k => $v) {
  4761.                         $passing['additional'][$k] = $v;
  4762.                     }
  4763.                 }
  4764.                 $percented = ($degradation_premi / 100) * $percented;
  4765.                 $additions = $formulation['additional']->duplicateAdditionalCalculation($passing);
  4766.                 $subtotal = $base_premi + $amount + $percented;
  4767.                 foreach ($additions as $k => $v) {
  4768.                     $addons += $v;
  4769.                     $sorted['is_additional_use_transcar.' . str_replace('_', '.', $k)] = [
  4770.                         $k => $v,
  4771.                         'message' => rupiah($v)
  4772.                     ];
  4773.                 }
  4774.                 $subtotal = $subtotal + $addons;
  4775.  
  4776.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  4777.                 break;
  4778.  
  4779.             case 'motorcycle':
  4780.                 // ini gua ngambil harga yang di degradasi, belum di round ya
  4781.                 // value divide by 100
  4782.                 // then multiply by degradation rate
  4783.                 // then now date min motorcycle year
  4784.                 // the all the result will be multiply
  4785.                 $sorted['value_price'] = ['message' => rupiah($value)];
  4786.                 if ($condition['degradation_year_condition'] < (date('Y') - $formulation['motorcycle_year'])) {
  4787.                     $degradation_premi = $value - ($value / 100) * $formulation['degradation_rate'];
  4788.                 } else {
  4789.                     $degradation_premi = $value;
  4790.                 }
  4791.                 $sorted['degradation'] = [
  4792.                     'year' => date('Y') - $formulation['motorcycle_year'],
  4793.                     'message' => rupiah($degradation_premi)
  4794.                 ];
  4795.  
  4796.                 // breakdown features
  4797.                 // features now based on percentages
  4798.                 if (isset($features) && is_array($features)) {
  4799.                     foreach ($features as $items) {
  4800.                         if ($items['type'] == 'amount') {
  4801.                             $val = (integer)$items['value'];
  4802.                         } elseif ($items['type'] == 'percentages') {
  4803.                             $val = ($degradation_premi / 100) * (float)$items['value'];
  4804.                         }
  4805.                         $features_breakdown[] = [$items['key'] => $val];
  4806.                     }
  4807.                     $sorted['features_breakdown'] = $features_breakdown;
  4808.  
  4809.                 }
  4810.  
  4811.                 // disini query harus ngeliat apa dia punya override atau gak, kalo emang gak, ya berarti di
  4812.                 // pake dong territorial ratenya, dan juga territory diliat lagi tipe zonenya.
  4813.                 // value divide by 100 then multiply by territory_rate
  4814.                 if ($condition['zone_id'] == 1) {
  4815.                     if ($formulation['territory_one_rate'] == 'bottom' or $formulation['territory_one_rate'] == 'top') {
  4816.                         $percentages = $condition['rates_condition'][1][1][$formulation['territory_one_rate']];
  4817.                     } else {
  4818.                         $percentages = (float)$formulation['territory_one_rate'];
  4819.                     }
  4820.                     $sorted['premi_percentages'] = [
  4821.                         'rate' => $percentages,
  4822.                         'message' => $percentages . '%'
  4823.                     ];
  4824.                 } else if ($condition['zone_id'] == 2) {
  4825.                     if ($formulation['territory_two_rate'] == 'bottom' or $formulation['territory_two_rate'] == 'top') {
  4826.                         $percentages = $condition['rates_condition'][1][2][$formulation['territory_two_rate']];
  4827.                     } else {
  4828.                         $percentages = (float)$formulation['territory_two_rate'];
  4829.                     }
  4830.                     $sorted['premi_percentages'] = [
  4831.                         'rate' => $percentages,
  4832.                         'message' => $percentages . '%'
  4833.                     ];
  4834.                 } else {
  4835.                     if ($formulation['territory_three_rate'] == 'bottom' or $formulation['territory_three_rate'] == 'top') {
  4836.                         $percentages = $condition['rates_condition'][1][3][$formulation['territory_three_rate']];
  4837.                     } else {
  4838.                         $percentages = (float)$formulation['territory_three_rate'];
  4839.                     }
  4840.                     $sorted['premi_percentages'] = [
  4841.                         'rate' => $percentages,
  4842.                         'message' => $percentages . '%'
  4843.                     ];
  4844.                 }
  4845.  
  4846.                 // jadi disini gua ngubah kalkukasi harusnya itung persen dulu sebelu hitung harga.
  4847.                 if ($condition['additional_year_condition'] < (date('Y') - $formulation['motorcycle_year'])) {
  4848.                     $addon_percentages = ($formulation['additional_rate'] / 100);
  4849.                 } else {
  4850.                     $addon_percentages = 0;
  4851.                 }
  4852.  
  4853.                 $sorted['loading_percentages'] = [
  4854.                     'rate' => $addon_percentages,
  4855.                     'message' => $addon_percentages . '%'
  4856.                 ];
  4857.                
  4858.                 $calculations         = $percentages + ($percentages * $addon_percentages);
  4859.                 $base_premi           = ($degradation_premi / 100) * $calculations;
  4860.                 $sorted['base_premi'] = ['premi' => $base_premi, 'message' => rupiah($base_premi)];
  4861.  
  4862.                 $passing = array(
  4863.                     'value' => $degradation_premi,
  4864.                     'type' => 'motorcycle',
  4865.                     'additional' => array(),
  4866.                     'level' => $condition['level'],
  4867.                     'id' => $condition['product_id'],
  4868.                     'zone' => $condition['zone_id']
  4869.                 );
  4870.  
  4871.                 // additional
  4872.                 if (isset($condition['additional'])) {
  4873.                     foreach ($condition['additional'] as $k => $v) {
  4874.                         $passing['additional'][$k] = $v;
  4875.                     }
  4876.                 }
  4877.                 $percented = ($degradation_premi / 100) * $percented;
  4878.                 $additions = $formulation['additional']->duplicateAdditionalCalculation($passing);
  4879.                 $subtotal = $base_premi + $amount + $percented;
  4880.                 foreach ($additions as $k => $v) {
  4881.                     $addons += $v;
  4882.                     $sorted['is_additional_use_transmotorcycle.' . str_replace('_', '.', $k)] = [
  4883.                         $k => $v,
  4884.                         'message' => rupiah($v)
  4885.                     ];
  4886.                 }
  4887.                 $subtotal = $subtotal + $addons;
  4888.  
  4889.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  4890.                 break;
  4891.  
  4892.             case 'property':
  4893.                 // approachingnya sama kaya sql
  4894.                 // cuma ini dipersingkat banget.
  4895.                 $premi = ($value / 1000) * $formulation['custom_rate'];
  4896.                 $sorted['premi'] = ['rate' => $formulation['custom_rate'], 'message' => rupiah($premi)];
  4897.                 $percented = ($value / 100) * $percented;
  4898.  
  4899.                 // breakdown features
  4900.                 // features now based on percentages
  4901.                 if (isset($features) && is_array($features)) {
  4902.                     foreach ($features as $items) {
  4903.                         if ($items['type'] == 'amount') {
  4904.                             $val = (integer)$items['value'];
  4905.                         } elseif ($items['type'] == 'percentages') {
  4906.                             $val = ($premi / 100) * (float)$items['value'];
  4907.                         }
  4908.                         $features_breakdown[] = [$items['key'] => $val];
  4909.                     }
  4910.                     $sorted['features_breakdown'] = $features_breakdown;
  4911.                 }
  4912.                 $passing = array(
  4913.                     'value' => $value,
  4914.                     'type' => 'property',
  4915.                     'additional' => array(),
  4916.                     'level' => $condition['level'],
  4917.                     'province' => $condition['province'],
  4918.                     'bundle_zone' => $condition['bundle_zone'],
  4919.                     'rsmd_zone' => $condition['rsmd_zone'],
  4920.                     'id' => $condition['product_id']
  4921.                 );
  4922.  
  4923.                 // additional
  4924.                 if (isset($condition['additional'])) {
  4925.                     foreach ($condition['additional'] as $k => $v) {
  4926.                         $passing['additional'][$k] = $v;
  4927.                     }
  4928.                 }
  4929.  
  4930.                 $additions = $formulation['additional']->duplicateAdditionalCalculation($passing);
  4931.                 $base_premi = $premi;
  4932.                 $subtotal = $base_premi + $amount + $percented;
  4933.                 foreach ($additions as $k => $v) {
  4934.                     $addons += $v;
  4935.                     $sorted['is_additional_use_transprop.' . str_replace('_', '.', $k)] = [
  4936.                         $k => $v,
  4937.                         'message' => rupiah($v)
  4938.                     ];
  4939.                 }
  4940.                 $subtotal = $subtotal + $addons;
  4941.                 $sorted['base_premi'] = ['premi' => $base_premi, 'message' => rupiah($base_premi)];
  4942.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  4943.                 break;
  4944.  
  4945.             case 'personal.accident':
  4946.                 $premi = $value;
  4947.                 $sorted['premi'] = ['premi' => $premi, 'message' => rupiah($premi)];
  4948.                 // breakdown features
  4949.  
  4950.                 // features now based on percentages
  4951.                 if (isset($features) && is_array($features)) {
  4952.                     foreach ($features as $items) {
  4953.                         if ($items['type'] == 'amount') {
  4954.                             $val = (integer)$items['value'];
  4955.                         } elseif ($items['type'] == 'percentages') {
  4956.                             $val = ($premi / 100) * (float)$items['value'];
  4957.                         }
  4958.                         $features_breakdown[] = [$items['key'] => $val];
  4959.                     }
  4960.                     $sorted['features_breakdown'] = $features_breakdown;
  4961.                 }
  4962.                 $base_premi = $premi;
  4963.                 $subtotal = $base_premi + $amount + $percented;
  4964.                 $sorted['base_premi'] = ['premi' => $base_premi, 'message' => rupiah($base_premi)];
  4965.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  4966.                 break;
  4967.  
  4968.             case 'travel':
  4969.                 $people = $condition['people'];
  4970.  
  4971.                 if ($condition['trip_type'] != 'annual.trip') {
  4972.                     $difference = $condition['difference'];
  4973.                     if ($condition['extra'] == 'weekly') {
  4974.                         $difference = ceil($condition['difference'] / 7);
  4975.                     }
  4976.                     $extra = $difference > 0 ? $difference * $formulation['extra'] : 0;
  4977.                     $premi = $formulation['harga'] + $extra;
  4978.                 } else {
  4979.                     $premi = $formulation['annual'];
  4980.                 }
  4981.                 // breakdown features
  4982.                 // features now based on percentages
  4983.                 if (isset($features) && is_array($features)) {
  4984.                     foreach ($features as $items) {
  4985.                         if ($items['type'] == 'amount') {
  4986.                             $val = (integer)$items['value'];
  4987.                         } elseif ($items['type'] == 'percentages') {
  4988.                             $val = ($premi / 100) * (float)$items['value'];
  4989.                         }
  4990.                         $features_breakdown[] = [$items['key'] => $val];
  4991.                     }
  4992.                     $sorted['features_breakdown'] = $features_breakdown;
  4993.                 }
  4994.                 $base_premi = $premi;
  4995.                 $subtotal = $base_premi + $amount + $percented;
  4996.  
  4997.                 $sorted['base_premi'] = ['premi' => $premi, 'message' => rupiah($base_premi)];
  4998.                 $sorted['days'] = ['days' => $premi, 'message' => $condition['days']];
  4999.                 $sorted['people'] = ['people' => $people, 'message' => $people];
  5000.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  5001.                 break;
  5002.  
  5003.             case 'health':
  5004.                 // features now based on percentages
  5005.                 if (isset($features) && is_array($features)) {
  5006.                     foreach ($features as $items) {
  5007.                         if ($items['type'] == 'amount') {
  5008.                             $val = (integer)$items['value'];
  5009.                         } elseif ($items['type'] == 'percentages') {
  5010.                             $val = ($condition['premi']['main'][$formulation['use']] / 100) * (float)$items['value'];
  5011.                         }
  5012.                         $features_breakdown[] = [$items['key'] => $val];
  5013.                     }
  5014.                     $sorted['features_breakdown'] = $features_breakdown;
  5015.                 }
  5016.                 $data = [];
  5017.                 $harga = ['yearly' => 0, 'semester' => 0, 'quartal' => 0, 'monthly' => 0];
  5018.  
  5019.                 foreach ($condition['premi']['main'] as $key => $value) {
  5020.                     $harga[$key] += $value;
  5021.                     $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5022.                 }
  5023.  
  5024.                 foreach ($condition['premi']['other'] as $key => $value) {
  5025.                     foreach ($value as $item) {
  5026.                         $harga[$key] += $item;
  5027.                         $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5028.                     }
  5029.                 }
  5030.  
  5031.                 foreach ($condition['premi']['children'] as $key => $value) {
  5032.                     foreach ($value as $item) {
  5033.                         $harga[$key] += $item;
  5034.                         $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5035.                     }
  5036.                 }
  5037.  
  5038.                 $subtotal = $data[$formulation['use'] . '_subtotal'];
  5039.                 $any = [
  5040.                     'semester' => $data['semester_subtotal'],
  5041.                     'quartal' => $data['quartal_subtotal'],
  5042.                     'monthly' => $data['monthly_subtotal'],
  5043.                     'yearly' => $data['yearly_subtotal']];
  5044.                 $sorted['base_premi'] = ['base_premi' => $data['yearly_subtotal'], 'message' => rupiah($data['yearly_subtotal'])];
  5045.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  5046.                 break;
  5047.  
  5048.             case 'life':
  5049.                 // breakdown features
  5050.                 // features now based on percentages
  5051.                 if (isset($features) && is_array($features)) {
  5052.                     foreach ($features as $items) {
  5053.                         if ($items['type'] == 'amount') {
  5054.                             $val = (integer)$items['value'];
  5055.                         } elseif ($items['type'] == 'percentages') {
  5056.                             $val = ($condition['premi']['main'][$formulation['use']] / 100) * (float)$items['value'];
  5057.                         }
  5058.                         $features_breakdown[] = [$items['key'] => $val];
  5059.                     }
  5060.                     $sorted['features_breakdown'] = $features_breakdown;
  5061.                 }
  5062.                 $data = [];
  5063.                 $harga = ['yearly' => 0, 'semester' => 0, 'quartal' => 0, 'monthly' => 0];
  5064.  
  5065.                 foreach ($condition['premi']['main'] as $key => $value) {
  5066.                     $harga[$key] += $value;
  5067.                     $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5068.                 }
  5069.  
  5070.                 foreach ($condition['premi']['other'] as $key => $value) {
  5071.                     foreach ($value as $item) {
  5072.                         $harga[$key] += $item;
  5073.                         $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5074.                     }
  5075.                 }
  5076.  
  5077.                 foreach ($condition['premi']['children'] as $key => $value) {
  5078.                     foreach ($value as $item) {
  5079.                         $harga[$key] += $item;
  5080.                         $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5081.                     }
  5082.                 }
  5083.  
  5084.                 $subtotal = $data[$formulation['use'] . '_subtotal'];
  5085.                 $any = [
  5086.                     'semester' => $data['semester_subtotal'],
  5087.                     'quartal' => $data['quartal_subtotal'],
  5088.                     'monthly' => $data['monthly_subtotal'],
  5089.                     'yearly' => $data['yearly_subtotal']];
  5090.                 $sorted['base_premi'] = ['base_premi' => $data['yearly_subtotal'], 'message' => rupiah($data['yearly_subtotal'])];
  5091.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  5092.                 break;
  5093.  
  5094.             case 'personal.accident.age':
  5095.                 // breakdown features
  5096.                 // features now based on percentages
  5097.                 if (isset($features) && is_array($features)) {
  5098.                     foreach ($features as $items) {
  5099.                         if ($items['type'] == 'amount') {
  5100.                             $val = (integer)$items['value'];
  5101.                         } elseif ($items['type'] == 'percentages') {
  5102.                             $val = ($condition['premi']['main'][$formulation['use']] / 100) * (float)$items['value'];
  5103.                         }
  5104.                         $features_breakdown[] = [$items['key'] => $val];
  5105.                     }
  5106.                     $sorted['features_breakdown'] = $features_breakdown;
  5107.                 }
  5108.                 $data = [];
  5109.                 $harga = ['yearly' => 0, 'semester' => 0, 'quartal' => 0, 'monthly' => 0];
  5110.  
  5111.                 foreach ($condition['premi']['main'] as $key => $value) {
  5112.                     $harga[$key] += $value;
  5113.                     $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5114.                 }
  5115.  
  5116.                 foreach ($condition['premi']['couple'] as $key => $value) {
  5117.                     foreach ($value as $item) {
  5118.                         $harga[$key] += $item;
  5119.                         $data[$key . '_subtotal'] = $harga[$key] + $amount + $percented;
  5120.                     }
  5121.                 }
  5122.  
  5123.                 $subtotal = $data[$formulation['use'] . '_subtotal'];
  5124.                 $any = [
  5125.                     'semester' => $data['semester_subtotal'],
  5126.                     'quartal' => $data['quartal_subtotal'],
  5127.                     'monthly' => $data['monthly_subtotal'],
  5128.                     'yearly' => $data['yearly_subtotal']];
  5129.                 $sorted['base_premi'] = ['base_premi' => $data['yearly_subtotal'], 'message' => rupiah($data['yearly_subtotal'])];
  5130.                 $sorted['premi'] = ['premi' => $subtotal, 'message' => rupiah($subtotal)];
  5131.                 break;
  5132.         }
  5133.  
  5134.         $sorted['subtotal_features'] = [
  5135.             'features' => $amount + $percented,
  5136.             'message' => rupiah($amount + $percented)
  5137.         ];
  5138.         // admin fee and materai fee
  5139.         if(!is_null($formulation['admin_fee'])){
  5140.             if ($formulation['admin_fee'] < 100) {
  5141.                 $admin_fee = $subtotal / 100 * $formulation['admin_fee'];
  5142.             } else {
  5143.                 $admin_fee = $formulation['admin_fee'];
  5144.             }
  5145.         } else {
  5146.             $admin_fee = 0;
  5147.         }
  5148.  
  5149.         if(!is_null($formulation['materai_fee'])){
  5150.             if ($formulation['materai_fee'] < 100) {
  5151.                 $materai_fee = $subtotal / 100 * $formulation['materai_fee'];
  5152.             } else {
  5153.                 $materai_fee = $formulation['materai_fee'];
  5154.             }
  5155.         } else {
  5156.             $materai_fee = 0;
  5157.         }
  5158.        
  5159.         $sorted['admin_fee'] = ['admin_fee' => $formulation['admin_fee'], 'message' => rupiah($admin_fee)];
  5160.         $sorted['materai_fee'] = ['materai_fee' => $formulation['materai_fee'], 'message' => rupiah($materai_fee)];
  5161.         $subtotal = $subtotal + $admin_fee + $materai_fee;
  5162.         if (count($any) > 0) {
  5163.             $ahny = [];
  5164.             foreach ($any as $k => $v) {
  5165.                 $ahny[$k] = $v + $admin_fee + $materai_fee;
  5166.             }
  5167.             $any = $ahny;
  5168.         }
  5169.         $subtotal = round($subtotal);
  5170.         $sorted['subtotal'] = ['subtotal' => $subtotal, 'message' => rupiah($subtotal)];
  5171.  
  5172.         return array('premi' => $subtotal, 'sorted' => $sorted, 'any' => $any);
  5173.     }
  5174.  
  5175.     public function viewCompareProduct(Request $request)
  5176.     {
  5177.         $compare = array(
  5178.             $request->first,
  5179.             $request->second,
  5180.         );
  5181.         if ($request->has('third')) {
  5182.             array_push($compare, $request->third);
  5183.         }
  5184.  
  5185.         $title = trans('global.compareResult') . ' - ' . trans('global.title');
  5186.         $x = 0;
  5187.         $type = $request->type;
  5188.         $prefix = str_replace('-', '_', $type);
  5189.         if($prefix == 'personal_accident_age'){
  5190.             $prefix = 'personal_accident';
  5191.         }
  5192.         $questionnaire = 'quest_' . $prefix;
  5193.         $benefit = 'benefit_' . $prefix;
  5194.         $feature = 'feature_' . $prefix;
  5195.  
  5196.         foreach ($compare as $p) {
  5197.             if ($p != ''):
  5198.  
  5199.                 $product[$x] = Insurance_product::with(
  5200.                     $feature,
  5201.                     $benefit,
  5202.                     $questionnaire,
  5203.                     'logo',
  5204.                     'detail',
  5205.                     'providerdata',
  5206.                     'features_additional_prices',
  5207.                     'insurance_type_product_rels',
  5208.                     'insurance_product_questionnaire.questionnaire',
  5209.                     'insurance_product_reviews.member',
  5210.                     'insurance_product_partners', 'subscriber_rels')->where('slug', $p)->first()->toArray();
  5211.  
  5212.                 $product = collect($product);
  5213.                 $product->transform(function($item, $key){
  5214.                     $type = str_replace('.','_',$item['type']);
  5215.                     $prefix = $type;
  5216.                     if($prefix == 'personal_accident_age'){
  5217.                         $prefix = 'personal_accident';
  5218.                     }
  5219.  
  5220.                     $temp_feature = [];
  5221.                     if(!is_null($item['feature_'.$prefix])){
  5222.                         foreach($item['feature_'.$prefix] as $key => $val){
  5223.                             $temp_feature[$key] = $val;
  5224.                             if(!is_null($val)){
  5225.                                 if((integer)$val == 1){
  5226.                                     $temp_feature[$key] = 'Y';
  5227.                                 }
  5228.                             }
  5229.    
  5230.                             if($key == 'dummy_benefit') {
  5231.                                 if(!is_array($val)){
  5232.                                     $temp_feature[$key] = json_decode($val, true);
  5233.                                 }
  5234.                             }
  5235.                         }
  5236.    
  5237.                         $item['feature_'.$prefix] = $temp_feature;
  5238.                         if(isset($temp_feature['dummy_benefit'])){
  5239.                             if(!is_null($temp_feature['dummy_benefit']) and is_array($temp_feature['dummy_benefit'])){
  5240.                                 if(count($temp_feature['dummy_benefit']) > 0){
  5241.                                     foreach($temp_feature['dummy_benefit'] as $xxk => $xxv){
  5242.                                         foreach($xxv as $tttype => $sub_item){
  5243.                                             if($tttype == 'days'){
  5244.                                                 $item['feature_'.$prefix][$xxk] = $sub_item.$tttype;
  5245.                                             } else {
  5246.                                                 $item['feature_'.$prefix][$xxk] = $sub_item;
  5247.                                             }
  5248.                                         }
  5249.                                     }
  5250.                                 }
  5251.                             }  
  5252.                         }
  5253.                     }
  5254.  
  5255.                     /*
  5256.                     if(count($item['features_additional_prices'])>0){
  5257.                         foreach($item['features_additional_prices'] as $xk => $xv){
  5258.                             if($xv['type']=='days'){
  5259.                                 $item['feature_'.$type][$xv['key']] = str_replace('.00','',$xv['value']).$xv['type'];
  5260.                             } else {
  5261.                                 $item['feature_'.$type][$xv['key']] = $xv['value'];
  5262.                             }
  5263.                         }
  5264.                     }*/
  5265.                     return $item;
  5266.                 });
  5267.                 $product->toArray();
  5268.                 $x++;
  5269.             endif;
  5270.         }
  5271.  
  5272.         $data['product'] = $product;
  5273.         $data['type'] = $type;
  5274.         $data['title'] = $title;
  5275.         $data['feature'] = $feature;
  5276.         $data['benefit'] = $benefit;
  5277.         $data['questionnaire'] = $questionnaire;
  5278.         $data['footer_js'] = ['/js/compare.js'];
  5279.         $data['en'] = str_replace('/compare', '/en/compare', $request->fullUrl());
  5280.         $data['id'] = str_replace('/en', '', $request->fullUrl());
  5281.  
  5282.         return view('front.search.compare', $data);
  5283.     }
  5284.  
  5285.     public function getProductsByType(Request $request)
  5286.     {
  5287.         $prod = Insurance_Product::where('type', $request->type)->get();
  5288.         $htm = '';
  5289.         foreach ($prod as $pr) {
  5290.             $provider = Insurance_Provider::find($pr->provider_id)->name;
  5291.             $htm .= '<option value="' . $pr->slug . '">' . $pr->name . ' - ' . $provider . '</option>';
  5292.         }
  5293.  
  5294.         return json_encode(['html' => $htm]);
  5295.     }
  5296.  
  5297.     public function getProductsBySlug(Request $request)
  5298.     {
  5299.         $slug = $request->slug;
  5300.         $prefix = $request->type;
  5301.         $datatarget = str_replace('.', '', $request->target);
  5302.         $questionnaire = 'quest_' . $prefix;
  5303.         $benefit = 'benefit_' . $prefix;
  5304.         $feature = 'feature_' . $prefix;
  5305.         $prod = Insurance_product::with(
  5306.             $feature,
  5307.             $benefit,
  5308.             $questionnaire,
  5309.             'logo',
  5310.             'detail',
  5311.             'providerdata',
  5312.             'features_additional_prices',
  5313.             'insurance_type_product_rels',
  5314.             'insurance_product_questionnaire.questionnaire',
  5315.             'insurance_product_reviews.member',
  5316.             'insurance_product_partners', 'subscriber_rels')->where('slug', $slug)->first()->toArray();
  5317.         $prod['features'] = $prod[$feature];
  5318.         foreach ($prod[$benefit] as $k => $v) {
  5319.             $ben[$k] = rupiah($v);
  5320.         }
  5321.         $prod['benefits'] = $ben;
  5322.         $prod['thead'] = '<span data-target="' . $datatarget . '" class="compare-remove"><i class="fa fa-remove"></i></span><div class="clearfix"></div><img width="96" src="' . $prod["logo"]["image"] . '" class="img-responsive center product-image"><h4 class="text-center product-name">' . $prod["name"] . '</h4>';
  5323.  
  5324.         return json_encode(['product' => $prod]);
  5325.     }
  5326. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement