<?php

namespace App\Http\Controllers\Web;

use App\Helpers\ImageHelper;
use App\Http\Controllers\Controller;
use App\Page;
use App\PageDescription;
use App\Mail;
use App\About;
use App\Cobon;
use App\Package;
use App\Subscribe;
use App\Account;
use App\Contact;
use App\Type;
use App\Question;
use App\Check;
use Illuminate\Http\Request;
use \Illuminate\Support\Str;
use App\Http\Requests\Web\SubscribeRequest;
use App\Http\Requests\Web\ContactRequest;
use App\Http\Requests\Web\PayRequest;
use App\Http\Requests\Web\CommissionRequest;
use Illuminate\View\View;

class PageController extends Controller
{
    private $viewDirectory = 'web.pages.';
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        // $this->middleware('auth')->except('lang');
    }

    /**
     * Show the Pages.
     *
     * @return \View
     */
     
     public function faq(){
         $questions = Question::cursor();
         return view($this->viewDirectory.'faq',compact('questions'));
     }
     
     public function forgetpassword(){
         return view($this->viewDirectory.'forgetpassword');
     }
      public function commissionsave(CommissionRequest $request){
         $request->merge(['user_id'=>\Auth::user()->id]);
         $check = Check::create($request->all());
         $img = upload($request->file('images')[0]);
         $check->image= $img;
         $check->save();
     }
  
     
       public function commission(){
           $accounts = Account::cursor();
                 $token =  "Tfwjij9tbcHVD95LUQfsOtbfcEEkw1hkDGvUbWPs9CscSxZOttanv3olA6U6f84tBCXX93GpEqkaP_wfxEyNawiqZRb3Bmflyt5Iq5wUoMfWgyHwrAe1jcpvJP6xRq3FOeH5y9yXuiDaAILALa0hrgJH5Jom4wukj6msz20F96Dg7qBFoxO6tB62SRCnvBHe3R-cKTlyLxFBd23iU9czobEAnbgNXRy0PmqWNohXWaqjtLZKiYY-Z2ncleraDSG5uHJsC5hJBmeIoVaV4fh5Ks5zVEnumLmUKKQQt8EssDxXOPk4r3r1x8Q7tvpswBaDyvafevRSltSCa9w7eg6zxBcb8sAGWgfH4PDvw7gfusqowCRnjf7OD45iOegk2iYSrSeDGDZMpgtIAzYVpQDXb_xTmg95eTKOrfS9Ovk69O7YU-wuH4cfdbuDPTQEIxlariyyq_T8caf1Qpd_XKuOaasKTcAPEVUPiAzMtkrts1QnIdTy1DYZqJpRKJ8xtAr5GG60IwQh2U_-u7EryEGYxU_CUkZkmTauw2WhZka4M0TiB3abGUJGnhDDOZQW2p0cltVROqZmUz5qGG_LVGleHU3-DgA46TtK8lph_F9PdKre5xqXe6c5IYVTk4e7yXd6irMNx4D4g1LxuD8HL4sYQkegF2xHbbN8sFy4VSLErkb9770-0af9LT29kzkva5fERMV90w"; #token value to be placed here;
$basURL = "https://apitest.myfatoorah.com";
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "$basURL/v2/InitiatePayment",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"InvoiceAmount\": 000,\"CurrencyIso\": \"SAR\"}",
  CURLOPT_HTTPHEADER => array("Authorization: Bearer $token","Content-Type: application/json"),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$data = json_decode($response,true)['Data']['PaymentMethods'];

$ways = collect();
foreach($data as $row){
    
        $ways->push(['PaymentMethodId'=>$row['PaymentMethodId'],'PaymentMethodAr'=>$row['PaymentMethodAr'],'PaymentMethodEn'=>$row['PaymentMethodAr'],'ImageUrl'=>$row['ImageUrl']]);
    
}
         return view($this->viewDirectory.'commission', compact( 'ways','accounts'));
     }
    
     
     
     
      public function packagesub(PayRequest $request){
          $request->merge(['user_id'=>\Auth::user()->id]);
          
        if($request->package_id == '1' || $request->pay_type == 'wallet'){
            if($request->package_id == '1'){
            $request->merge(['type'=>'1']);
            $user = \Auth::user();
            
            Subscribe::create($request->all());
            if(is_null($user->hanqr)){
             $random = rand(1002,9999);
                 $arr = str_split($random);
                 $arr_uni = array_unique($arr);
                 do {
 
 $random = rand(1002,9999);
                 $arr = str_split($random);
                 $arr_uni = array_unique($arr);
                 if(count($arr_uni) != '2'){
                    $user->update(['hanqr'=>$random]); 
                 }
} while (count($arr_uni) == '2');
}
            return redirect(getCurrentLocale().'/profile')->with('success',__('web.success'));
            }
            else{
                 $user = \Auth::user();
                $product = Package::find($request->package_id);
                if($product->cost > $user->wallet){
                    
return json_encode('error');
                }
                else{
               
                $user->update(['wallet'=>$user->wallet-$product->cost]);
            Subscribe::create($request->all());
return json_encode('success');
                }
            }
        }
        else{
            
            /*$credit = null;
            foreach($request->credit as $row){
              $credit .= $row;  
            }*/
            
$token =  "Tfwjij9tbcHVD95LUQfsOtbfcEEkw1hkDGvUbWPs9CscSxZOttanv3olA6U6f84tBCXX93GpEqkaP_wfxEyNawiqZRb3Bmflyt5Iq5wUoMfWgyHwrAe1jcpvJP6xRq3FOeH5y9yXuiDaAILALa0hrgJH5Jom4wukj6msz20F96Dg7qBFoxO6tB62SRCnvBHe3R-cKTlyLxFBd23iU9czobEAnbgNXRy0PmqWNohXWaqjtLZKiYY-Z2ncleraDSG5uHJsC5hJBmeIoVaV4fh5Ks5zVEnumLmUKKQQt8EssDxXOPk4r3r1x8Q7tvpswBaDyvafevRSltSCa9w7eg6zxBcb8sAGWgfH4PDvw7gfusqowCRnjf7OD45iOegk2iYSrSeDGDZMpgtIAzYVpQDXb_xTmg95eTKOrfS9Ovk69O7YU-wuH4cfdbuDPTQEIxlariyyq_T8caf1Qpd_XKuOaasKTcAPEVUPiAzMtkrts1QnIdTy1DYZqJpRKJ8xtAr5GG60IwQh2U_-u7EryEGYxU_CUkZkmTauw2WhZka4M0TiB3abGUJGnhDDOZQW2p0cltVROqZmUz5qGG_LVGleHU3-DgA46TtK8lph_F9PdKre5xqXe6c5IYVTk4e7yXd6irMNx4D4g1LxuD8HL4sYQkegF2xHbbN8sFy4VSLErkb9770-0af9LT29kzkva5fERMV90w"; #token value to be placed here;
$product = Package::find($request->package_id);
$user = \Auth::user();

$cost= $product->cost;
if(!is_null($request->code)){
$cobon = Cobon::where('code',$request->code)->first();
       
        if($cobon){
           
            if($cobon->discount_type=='1'){
                $val = $cost -$cobon->discount_amount;
            }
            else{
                $val = $cost - ($cost * ($cobon->discount_amount/100));
            }
            $cost = $val;
        }
}
$username= $request->fullname;
$email = $user->email;
$phone = $user->phone;
$month = $request->month;
$year = $request->year;
$code = $request->cvv;
$credit = $request->credit;
$pay = $request->pay_type;
$package_name = 'Request';
$basURL = "https://apitest.myfatoorah.com";




$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "$basURL/v2/ExecutePayment",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"PaymentMethodId\":\"".$pay."\",\"CustomerName\": \"".$username."\",\"DisplayCurrencyIso\": \"SAR\", \"MobileCountryCode\":\"+965\",\"CustomerMobile\": \"".$phone."\",\"CustomerEmail\": \"".$email."\",\"InvoiceValue\": ".$cost.",\"CallBackUrl\": \"https://google.com\",\"ErrorUrl\": \"https://google.com\",\"Language\": \"en\",\"CustomerReference\" :\"ref 1\",\"CustomerCivilId\":12345678,\"UserDefinedField\": \"Custom field\",\"ExpireDate\": \"\",\"CustomerAddress\" :{\"Block\":\"\",\"Street\":\"\",\"HouseBuildingNo\":\"\",\"Address\":\"\",\"AddressInstructions\":\"\"},\"InvoiceItems\": [{\"ItemName\": \"".$package_name."\",\"Quantity\": 1,\"UnitPrice\": $cost}]}",
  CURLOPT_HTTPHEADER => array("Authorization: Bearer $token","Content-Type: application/json"),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);

$err = curl_error($curl);
curl_close($curl);
if ($err) {
   return redirect()->back();
}

 $json  = json_decode((string)$response, true);

 if ($json['IsSuccess'] == false) 
 {
     
   return json_encode($json['ValidationErrors'][0]['Error']);
}
 //echo "json  json: $json '<br />'";

$payment_url = $json["Data"]["PaymentURL"];

    # after getting the payment url call it as a post API and pass card info to it
    # if you saved the card info before you can pass the token for the api
    
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "$payment_url",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"paymentType\": \"card\",\"card\": {\"Number\":\"".$credit."\",\"expiryMonth\":\"".$month."\",\"expiryYear\":\"".$year."\",\"securityCode\":\"".$code."\"},\"saveToken\": false}",
  CURLOPT_HTTPHEADER => array("Authorization: Bearer $token","Content-Type: application/json"),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);

$data = json_decode((string)$response, true);

$paymentid = $data['Data']['PaymentId'];
if ($json['IsSuccess'] == false) 
 {
   return json_encode('error');
}
Subscribe::create(['paymentId'=>$paymentid,'user_id'=>$user->id,'package_id'=>$request->package_id,'type'=>'0']);
$err = curl_error($curl);
if ($err) {
   return json_encode($json['ValidationErrors']['0']['Error']);
}
curl_close($curl);
return json_encode('success');
  
        }
    } 
    
    
    
    
    
    
    
    
    
     public function package(){
        $first = Package::orderBy('id','ASC')->first();
        $second = Package::orderBy('id','ASC')->skip(1)->take(1)->first();
       
        $third = Package::orderBy('id','DESC')->first();
                $token =  "Tfwjij9tbcHVD95LUQfsOtbfcEEkw1hkDGvUbWPs9CscSxZOttanv3olA6U6f84tBCXX93GpEqkaP_wfxEyNawiqZRb3Bmflyt5Iq5wUoMfWgyHwrAe1jcpvJP6xRq3FOeH5y9yXuiDaAILALa0hrgJH5Jom4wukj6msz20F96Dg7qBFoxO6tB62SRCnvBHe3R-cKTlyLxFBd23iU9czobEAnbgNXRy0PmqWNohXWaqjtLZKiYY-Z2ncleraDSG5uHJsC5hJBmeIoVaV4fh5Ks5zVEnumLmUKKQQt8EssDxXOPk4r3r1x8Q7tvpswBaDyvafevRSltSCa9w7eg6zxBcb8sAGWgfH4PDvw7gfusqowCRnjf7OD45iOegk2iYSrSeDGDZMpgtIAzYVpQDXb_xTmg95eTKOrfS9Ovk69O7YU-wuH4cfdbuDPTQEIxlariyyq_T8caf1Qpd_XKuOaasKTcAPEVUPiAzMtkrts1QnIdTy1DYZqJpRKJ8xtAr5GG60IwQh2U_-u7EryEGYxU_CUkZkmTauw2WhZka4M0TiB3abGUJGnhDDOZQW2p0cltVROqZmUz5qGG_LVGleHU3-DgA46TtK8lph_F9PdKre5xqXe6c5IYVTk4e7yXd6irMNx4D4g1LxuD8HL4sYQkegF2xHbbN8sFy4VSLErkb9770-0af9LT29kzkva5fERMV90w"; #token value to be placed here;
$basURL = "https://apitest.myfatoorah.com";
$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "$basURL/v2/InitiatePayment",
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "{\"InvoiceAmount\": 000,\"CurrencyIso\": \"SAR\"}",
  CURLOPT_HTTPHEADER => array("Authorization: Bearer $token","Content-Type: application/json"),
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$data = json_decode($response,true)['Data']['PaymentMethods'];

$ways = collect();
foreach($data as $row){
    
        $ways->push(['PaymentMethodId'=>$row['PaymentMethodId'],'PaymentMethodAr'=>$row['PaymentMethodAr'],'PaymentMethodEn'=>$row['PaymentMethodAr'],'ImageUrl'=>$row['ImageUrl']]);
    
}
        return view($this->viewDirectory.'package', compact( 'first','second','third','ways'));
    }
     public function contactus(){
        $types = Type::cursor();
        return view($this->viewDirectory.'contactus', compact( 'types'));
    }
     public function aboutus(){
        $about = About::first();
        return view($this->viewDirectory.'aboutus', compact( 'about'));
    }
     public function contacting(ContactRequest $request){
        Contact::create($request->all());
        return json_encode('success');  
    }
    public function subcribe(SubscribeRequest $request){
        Mail::create($request->all());
        return json_encode('success');  
    }
    public function index(): View
    {
        $query= Page::latest()
            ->join('page_descriptions AS pd', 'pages.id', 'pd.page_id')
            ->where('status', 1)
            ->where('language_id', currentLanguage()->id)
            ->select(['pd.*', 'pages.*'])->get();

        $pages= [];
        if($query){
            $pages= $query->toArray();
        }
        foreach ($pages as $key => $value) {
            $pages[$key]['image']= ImageHelper::get($value['image']);
            $pages[$key]['intro']= Str::words(strip_tags($value['description']), 10, '...');
            $pages[$key]['route']= route('page_details', ['page'=> $value['page_id'], 'slug'=> str_slug($value['slug'])] );
        }
        // dd($pages);
        $settings= settings();
        $title= $settings['website_name'];
        $keywords= $settings['keywords'];
        $meta_description= $settings['meta_description'];

        return view($this->viewDirectory.'index', compact( 'pages', 'title', 'keywords', 'meta_description'));
    }

    /**
     * Show the Page details.
     * @param Page
     * @return \View
     */
    public function details(Page $page, Request $request) :View
    {
        $image= ImageHelper::get($page->image);
        $description = PageDescription::where('page_id', $page->id)
        ->where('language_id', currentLanguage()->id)
        ->first();
        // dd($description->toArray(), $image);

        $title= $description->title;
        $keywords= $description->keywords;
        $meta_description= $description->meta_description;

        return view( $this->viewDirectory.'details', compact('page', 'description', 'image', 'title', 'keywords', 'meta_description') );
    }
}
