<?php

namespace App\Http\Controllers;

use App\Models\Discount;
use App\Models\CelebrityDiscountRecord;
use Illuminate\Http\Request;

class DiscountController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function __construct()
    {
       return $this->middleware('auth');
    }

    public function store(Request $request)
    {  
       
    if ($request->submit_celeb == "Apply Code") {

        $this->validate(request(), [
            'discount_code'=> 'required|max:50'
        ]);
        
        // check if code exist
        $check_code = \DB::table('celebrity_discounts')
        ->where('discount_code', $request->discount_code)
        ->orWhere('discount_barcode', $request->discount_code)
        ->first();

        if (empty($check_code) || null) {
            abort(419, "Mismatch Gift Card");
        }else {
            $sum = 0;
            $checkseesion = session()->get('cart');
                if (!empty($checkseesion) || null) {
                    foreach ($checkseesion as $item) {
                    $result = (float)$item['invoice_quantity'] * (float)$item['invoice_unit_price'];
                    $sum+=$result;
                    }
                }

                $data = [
                    'type' => "Percentage",
                    'discount' => $check_code->discount_percentage,
                ];
            
            session()->put('discount', $data);

        }
    }else {
        if (request('type') == "Percentage") {
            if (request('discount') > 100) {
                abort(419, "Percentage Can not be greater than 100");
            }
        }
        $sum = 0;
            $checkseesion = session()->get('cart');
                if (!empty($checkseesion) || null) {
                    foreach ($checkseesion as $item) {
                    $result = (float)$item['invoice_quantity'] * (float)$item['invoice_unit_price'];
                    $sum+=$result;
                    }
                }

                $data = [
                    'type' => request('type'),
                    'discount' => request('discount'),
                ];
            
            session()->put('discount', $data);
            
         }
         return 123;

    }

}
