<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Modules\PaymentModule;
use App\Modules\OrderModule;
use App\Modules\MailerModule;

use Validator;

class CheckoutController extends Controller
{
    public function checkout(OrderModule $ordermodule, PaymentModule $paymentmodule)
    {
    	$inputs = request()->all();

        $rules = [
            'lastname' => 'required|string|min:2',
            'firstname' => 'required|string'
        ];

        $validator = Validator::make($inputs, $rules);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

    	$order_id = session('order_id');
        $order = $ordermodule->getOneById($order_id);

    	$data = [];
    	$data['firstname'] = strip_tags($inputs['firstname']);
    	$data['lastname'] = strip_tags($inputs['lastname']);
    	$payment_method = strip_tags($inputs['payment_method']);
    	$data['express'] = 0;

    	$data['sms_included'] = 0;
        if(isset($inputs['is_sms_included'])) { 
    		$data['sms_included'] = strip_tags($inputs['phone_number']);
        }
			
		if (preg_match ("/[^0-9]/", $data['sms_included'])) {
			$data['sms_included'] = 0;
		}
			
 		if( !empty($data['sms_included']) ) {
			//ADD 1€ ON TOP OF THE UNLOCK PRICE
			//AS WE CHARGE 1€ PER SMS MESSAGE
			$data['amount'] = session('price') + 1;
		}
		
		$hash_time = time();

		if(!preg_match("/Paypal/i", $payment_method)) {
			$payment_method = 'Credit Card';
			$data['express'] = 1;
		}
		$data['datemodified'] = $hash_time;

		if ($ordermodule->update($order_id, $data)) {
			return $paymentmodule->checkout($order_id);
		}

		return redirect()->back()->withInput();

	
    }

    public function paymentSuccessful(OrderModule $ordermodule, MailerModule $mailer)
    {
    	$inputs = request()->all();

    	$hash = $inputs['hash'];
		$puid = $inputs['puid'];
		
		$order = $ordermodule->getOneByHashAndId($hash, $puid);

        $paypal_info = $this->fetchInfo($order);

        if($paypal_info) {

            if(!array_key_exists('PAYMENTINFO_0_TRANSACTIONID', $paypal_info)) {
                return Redirect::to('/')->with('error', 'Payment not completed.');
            }

            $ordermodule->update($order->order_id, array('status' => 'paid'));
            session()->forget('price');
            session()->forget('order_id');

            $data = ['lastname' => $order->lastname, 'imei' => $order->imei, 'phone' => $order->phone, 'model' => $order->model, 'operator' => $order->operator];
            $mailer->sendOrderConfirmation($order->email, $data);

            return redirect('merci');
        }
    }

    public function fetchInfo($order)
    {
    	$paymentmodule = new PaymentModule();

        $purchase = [];

       	$items['name'] = '1 Code deblocage '.$order->operator.':'. $order->phone.' '.$order->model.' ('.$order->imei.')';
        $items['price'] = $order->amount;

        $purchase[] = $items;

        $hash_time = $order->datemodified;
        $hash = md5($order->operator . $order->phone . $order->imei . $hash_time);

        $return_url = url('payment-successful').'?hash='.$hash.'&puid='.md5($order->id);
        $cancel_url = url('payment-cancelled');

        $response = $paymentmodule->getGetway()->completePurchase(
                           array(
                               'cancelUrl' => $cancel_url,
                               'returnUrl' => $return_url,
                               'amount' => (float) $order->amount,
                               'currency' => 'EUR',
                           )
                   )->setItems($purchase)->send();

        return $response->getData();
    }

    public function paymentCancelled()
    {
    	return redirect('/');
    }

    public function testEmail(MailerModule $mailer)
    {
        $email = 'analizapandac@gmail.com';
        $data = ['lastname' => 'Liza', 'imei' => '123456789012345', 'phone' => 'Samsung', 'model' => 'u600', 'operator' => 'Bouygues'];
        return view('emails.order_confirmation', $data);
        return $mailer->sendOrderConfirmation($email, $data);
    }
}
