<?php

namespace App\Http\Controllers;

use App\Helpers\Utility;
use App\Mail\PurchaseCompletedMail;
use App\Models\AddressPurchase;
use App\Models\MercadoPagoData;
use App\Models\Product;
use App\Models\ProductPricePurchase;
use App\Models\Purchase;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class DashBoardController extends Controller
{
    //
    public function home()
    {
        $section = 1;
        return view('pages.dashboard', compact('section'));
    }
    public function about()
    {
        $section = 2;
        return view('pages.dashboard', compact('section'));
    }

    public function products()
    {
        $section = 3;
        return view('pages.dashboard', compact('section'));
    }

    public function cafeConCausa()
    {
        $section = 4;
        return view('pages.dashboard', compact('section'));
    }

    public function contact()
    {
        $section = 5;
        return view('pages.dashboard', compact('section'));
    }

    public function product(Product $product)
    {
        if ($product->status_id == 5) {
            abort(404, 'Producto No encontrado');
        }
        $section = 6;
        return view('pages.dashboard', compact('section', 'product'));
    }

    public function summary()
    {
        $section = 7;
        return view('pages.dashboard', compact('section'));
    }

    public function checkout($id)
    {
        $purchase = Purchase::where([
            ['id', '=', $id], 
            ['user_id', '=', auth()->user()->id],
            ['status_id', '=', 24]
        ])->first();
        if (is_null($purchase)) {
            return redirect()->route('home');
        }
        $section = 8;
        return view('pages.dashboard', compact('section', 'purchase'));
    }

    public function purchaseResponse($id)
    {
        // info($id);
        // info(request());
        $purchase = Purchase::where('id', $id)->first();
        // info($purchase);
        try {
            if (!is_null($purchase)) {
                if ($purchase->status_id == 24) {
                    // return request();
                    if ((request()['type'] == 1 && request()['status'] == 'approved') || (request()['type'] == 2 && request()['status'] == 'rejected')) {
                        // return request();
                        $purchase->update(['status_id' => request()['type'] == 1 ? 10 : 14]);
                        // $url = auth()->check() ? 'compras.index' : 'home';
                        MercadoPagoData::create([
                            'collection_id' => request()['collection_id'],
                            'collection_status' => request()['collection_status'],
                            'payment_id' => request()['payment_id'],
                            'status' => request()['status'],
                            'external_reference' => request()['external_reference'],
                            'payment_type' => request()['payment_type'],
                            'merchant_order_id' => request()['merchant_order_id'],
                            'preference_id' => request()['preference_id'],
                            'site_id' => request()['site_id'],
                            'processing_mode' => request()['processing_mode'],
                            'merchant_account_id' => request()['merchant_account_id'],

                            'external_reference' => $purchase->id,
                            'purchase_id' => $purchase->id,
                        ]);

                        // if (request()['type'] == 2) {
                        //     $this->generateCart($purchase);
                        // }
                        // if (request()['type'] == 1) {
                        //     // if ($purchase->user->role_id == 3) {
                        //     //     $password = Str::random(10);
                        //     //     $purchase->user->update([
                        //     //         'password' => Hash::make($password),
                        //     //         'role_id' => 2,
                        //     //         'status_id' => 1,
                        //     //     ]);
                        //     //     Utility::sendEmail($purchase->user->email, new NewClientMail($purchase->user, $password));
                        //     // }
                        //     // Cookie::queue(Cookie::forget('device_id'));
                        // }

                        Utility::sendEmail($purchase->user->email, new PurchaseCompletedMail($purchase));
                        $admin = User::where('id',1)->first();
                        Utility::sendEmail($admin->email, new PurchaseCompletedMail($purchase));
                        $admin = User::where('id',2)->first();
                        Utility::sendEmail($admin->email, new PurchaseCompletedMail($purchase));
                        // return 'info';
                        session()->flash('success', $purchase->status->name);
                        return redirect()->route('compras.index');
                    }
                }
            }
            // return 'no se pudo';
            session()->flash('server', 'La compra no fue realizada, no se termino el proceso de pago.');
            return redirect()->route('home');
        } catch (\Throwable $th) {
            info($th->getMessage());
        }
    }

    public function generateCart($purchase)
    {
        try {
            $new_purchase = Purchase::create([
                'home_delivery' => 1,
                'invoice' => 0,
                'user_id' => $purchase->user_id,
                'status_id' => 19,
                'token' => (string) Str::uuid(),
                'ip' => $purchase->ip,
                'mac' => $purchase->arpScan,
                'updated' => $purchase->updated,
            ]);
            foreach ($purchase->product_price_purchases as $key) {
                ProductPricePurchase::create([
                    'quantity' => $key->quantity,
                    'purchase_id' => $new_purchase->id,
                    'product_price_id' => $key->product_price_id,
                    // 'clothing_sizes_product_id' => $key->clothing_sizes_product_id,
                ]);
            }
            if (!is_null($purchase->address_purchase)) {
                AddressPurchase::create([
                    'address_id' => $purchase->address_purchase->address_id,
                    'purchase_id' => $purchase->id,
                ]);
            }
        } catch (\Throwable $th) {
            info($th->getMessage());
        }
    }
}
