<?php

namespace App\Http\Controllers;

use App\Order;
use App\PaymentMethod;
use App\ShippingMethod;
use Illuminate\Http\Request;
use App\Product;
use Cart;
use Illuminate\Support\Facades\DB;

class CartController extends Controller
{
    public function action(Request $request)
    {
        switch($request->action) {
            case 'add':
                $product = Product::findOrFail($request->product_id);

                Cart::add($product->code ?? $product->id, $product->post->title, $request->qty ?? 1, $product->actual_price, [
                    'image' => $product->thumbnail,
                    'category_id' => $product->post->category->id ?? null,
                    'url' => route('product', $product->post->slug)
                ]);
                $message = 'Ver carrito';
                break;
            case 'update':
                Cart::update($request->row_id, $request->qty);
                $message = 'El carrito ha sido actualizado';
                break;
            case 'remove':
                Cart::remove($request->row_id);
                $message = 'El producto ha sido eliminado';
                break;
        }
        $output['message'] = $message;
        $output['count'] = Cart::count();
        $output['cart'] = view('partials.cart')->render();
        $output['cart_full'] = view('partials.cart-full')->render();

        return response()->json($output);
    }

    public function index()
    {
        return view('templates.cart');
    }

    public function checkout()
    {
        $shipping_methods = ShippingMethod::where('active', 1)->orderBy('order')->get();
        $payment_methods = PaymentMethod::where('active', 1)->orderBy('order')->get();

        return view('templates.checkout', [
            'shipping_methods' => $shipping_methods,
            'payment_methods' => $payment_methods,
        ]);
    }

    public function place(Request $request)
    {
        if(!Cart::count()) abort(404);

        $shipping_method = ShippingMethod::findOrFail($request->shipping_method_id);
        $payment_method = PaymentMethod::findOrFail($request->payment_method_id);
        $order = auth()->user()->orders()->create($request->except('_token') + [
            'shipping_method' => $shipping_method->title,
            'shipping_price' => $shipping_method->price ?? 0,
            'payment_method' => $payment_method->title
        ]);
        $items = [];
        foreach(Cart::content() as $item) {
            $items[] = [
                'order_id' => $order->id,
                'code' => $item->id,
                'name' => $item->name,
                'price' => $item->price,
                'qty' => $item->qty,
                'attributes' => $item->options
            ];
        }
        $order->items()->insert($items);

        return $this->notify($order);
    }

    public function notify($order)
    {
        if(!$order->status_id) {
            $order->fill([
                'status_id' => 1
            ])->save();

            try {
//                Mail::send('emails.confirm', ['order' => $order], function ($message) use ($order) {
//                    $message->subject('Confirmación de pago');
//                    $message->to($order->email);
//                    foreach(toArray(options('contact_email')) as $email) {
//                        if(filter_var($email, FILTER_VALIDATE_EMAIL)) $message->bcc($email);
//                    }
//                    $message->from(env('MAIL_FROM_ADDRESS'), options('title'));
//                });
            } catch(\Exception $e) {
                Log::error($e);
            }
        }

        Cart::destroy();

        return redirect()->route('cart.finish', md5($order->id));
    }

    public function finish($hash)
    {
        $order = Order::where(DB::raw('MD5(id)'), $hash)->firstOrFail();
        if($order->user_id != auth()->id()) abort(404);

        return view('templates.finish', [
            'order' => $order
        ]);
    }
}
