<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;
use Dashboard\Services\ProductService;
use PDO;

class GamingNightController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_GAMING_NIGHT');
    }

    public function index()
    {
        $gamingNightStart = moduleSettings('gaming_night', 'start');
        $gamingNightEnd = moduleSettings('gaming_night', 'end');
        $gamingNightProducts = db()->query("SELECT P.id as productID, P.name, P.price, GNP.price as discountedPrice, GNP.stock FROM GamingNightProducts GNP INNER JOIN Products P ON GNP.productID = P.id");
        $gamingNightProducts = $gamingNightProducts->fetchAll(PDO::FETCH_ASSOC);

        $categories = db()->query("SELECT id, name, parentID FROM ProductCategories ORDER BY priority DESC");
        $categories = $categories->fetchAll(PDO::FETCH_ASSOC);

        $products = db()->query("SELECT id, name, categoryID FROM Products ORDER BY priority DESC");
        $products = $products->fetchAll(PDO::FETCH_ASSOC);

        $productList = ProductService::buildTree($categories, $products);

        $days = [
          'Monday',
          'Tuesday',
          'Wednesday',
          'Thursday',
          'Friday',
          'Saturday',
          'Sunday',
        ];

        return view('gaming-night.index', compact('gamingNightProducts', 'gamingNightStart', 'gamingNightEnd', 'productList', 'days'));
    }

    public function update()
    {
        validate([
          'day' => 'required',
          'start' => 'required',
          'end' => 'required',
        ]);

        if (empty(array_filter($_POST["product"])) || empty(array_filter($_POST["discountedPrice"])) || empty(array_filter($_POST["stock"]))) {
            return back()->flash('error', t__('Please fill all the fields!'));
        }

        updateModuleSettings('gaming_night', [
            "day" => input("day"),
            "start" => str_replace(':', '', input("start")),
            "end" => str_replace(':', '', input("end"))
        ]);

        $deleteGamingNightProducts = db()->query("TRUNCATE TABLE GamingNightProducts");
        foreach ($_POST["product"] as $key => $value) {
            $_POST["product"][$key] = strip_tags($_POST["product"][$key]);
            $_POST["discountedPrice"][$key] = strip_tags($_POST["discountedPrice"][$key]);
            $_POST["stock"][$key] = strip_tags($_POST["stock"][$key]);
            $insertGamingNightProducts = db()->prepare("INSERT INTO GamingNightProducts (productID, price, stock) VALUES (?, ?, ?)");
            $insertGamingNightProducts->execute(array($_POST["product"][$key], $_POST["discountedPrice"][$key], $_POST["stock"][$key]));
        }
        createLog("GAMING_NIGHT_UPDATED");
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }
}