<?php

namespace Main\Controllers;

use Main\Core\Controller;
use Main\Core\Redirect;
use Main\Services\DeliveryService;
use Main\Services\SeoService;
use PDO;

class GiftController extends Controller
{
		protected string $route_type = 'gift';
		
    public function index()
    {
	      SeoService::set('gifts.index');
				
        $logs = db()->prepare("SELECT PGH.*, PG.name as giftName FROM ProductGiftsHistory PGH INNER JOIN ProductGifts PG ON PGH.giftID = PG.id WHERE PGH.accountID = ? ORDER by PGH.id DESC LIMIT 5");
		    $logs->execute(array(auth()->user()->id()));
		    $logs = $logs->fetchAll();

        return $this->view('gifts.index', compact('logs'));
    }

    function check()
    {
        validate([
            "gift" => "required"
        ]);
	    
		    $gift = db()->prepare("SELECT * FROM ProductGifts WHERE name = ?");
		    $gift->execute(array(input("gift")));
		    $gift = $gift->fetch();
	    
		    if (!$gift) {
			    return back()->flash('error', t__('Gift not found!'));
		    }

        $giftLogs = db()->prepare("SELECT COUNT(id) FROM ProductGiftsHistory WHERE giftID = ?");
        $giftLogs->execute(array($gift["id"]));
        $giftLogsCount = $giftLogs->fetchColumn();
	    
		    $userGiftLogs = db()->prepare("SELECT COUNT(id) FROM ProductGiftsHistory WHERE accountID = ? AND giftID = ?");
		    $userGiftLogs->execute(array(auth()->user()->id(), $gift["id"]));
		    $userGiftLogsCount = $userGiftLogs->fetchColumn();

        if ($userGiftLogsCount > 0) {
            return back()->flash('error', t__('You already used this code!'));
        }

        if ($gift["expiryDate"] < datetime() && $gift["expiryDate"] != '1000-01-01 00:00:00') {
            return back()->flash('error', t__('This code has expired!'));
        }

        if ($gift["redeemLimit"] <= $giftLogsCount && $gift["redeemLimit"] != -1) {
            return back()->flash('error', t__('This code has expired!'));
        }

        redirect(url('gifts.show', ['id' => $gift["id"]]));
    }

    public function show($id)
    {
        $gift = db()->prepare("SELECT * FROM ProductGifts WHERE id = ?");
		    $gift->execute(array($id));
		    $gift = $gift->fetch();
	
        if (!$gift) abort_404();
	    
	      SeoService::set('gifts.index');
	    
		    if ($gift["giftType"] == 1) {
			    $product = db()->prepare("SELECT P.*, PC.name as categoryName FROM Products P INNER JOIN ProductCategories PC ON P.categoryID = PC.id WHERE P.id = ?");
			    $product->execute(array($gift["gift"]));
			    $product = $product->fetch();
			    
			    $gift["gift"] = $product;
				}

        return $this->view('gifts.show', compact('gift'));
    }

    public function use($id)
    {
        $gift = db()->prepare("SELECT * FROM ProductGifts WHERE id = ?");
        $gift->execute(array($id));
        $gift = $gift->fetch();

        if (!$gift) abort_404();
	    
		    $giftLogs = db()->prepare("SELECT COUNT(id) FROM ProductGiftsHistory WHERE giftID = ?");
		    $giftLogs->execute(array($gift["id"]));
		    $giftLogsCount = $giftLogs->fetchColumn();

        $userGiftLogs = db()->prepare("SELECT COUNT(id) FROM ProductGiftsHistory WHERE accountID = ? AND giftID = ?");
		    $userGiftLogs->execute(array(auth()->user()->id(), $gift["id"]));
		    $userGiftLogsCount = $userGiftLogs->fetchColumn();
	    
		    $redirect = new Redirect(url("gifts.index"));

        if ($userGiftLogsCount > 0) {
            return $redirect->flash('error', t__('You already used this code!'));
        }

        if ($gift["expiryDate"] < datetime() && $gift["expiryDate"] != '1000-01-01 00:00:00') {
            return $redirect->flash('error', t__('This code has expired!'));
        }

        if ($gift["redeemLimit"] <= $giftLogsCount && $gift["redeemLimit"] != -1) {
            return $redirect->flash('error', t__('This code has expired!'));
        }

        $insertLog = db()->prepare("INSERT INTO ProductGiftsHistory (accountID, giftID, creationDate) VALUES (?, ?, ?)");
		    $insertLog->execute(array(auth()->user()->id(), $gift["id"], datetime()));
        $logID = db()->lastInsertId();

        if ($gift["giftType"] == 1) {
            if (!modules('chest')->isActive()) {
		            DeliveryService::deliver(
			            [[
				            'id' => $gift["gift"],
				            'quantity' => 1
			            ]],
			            auth()->user()->id(),
			            "gift",
			            $logID,
		            );
                
                return $redirect->flash('success', t__('The gift has been delivered successfully!'));
            } else {
                $insertChest = db()->prepare("INSERT INTO Chests (accountID, productID, status, creationDate) VALUES (?, ?, ?, ?)");
                $insertChest->execute(array(auth()->user()->id(), $gift["gift"], 0, datetime()));

                return $redirect->flash('success', t__('The gift has been successfully added to your chest!'));
            }
        } else {
            $updateCredits = db()->prepare("UPDATE Accounts SET credit = credit + ? WHERE id = ?");
		        $updateCredits->execute(array($gift["gift"], auth()->user()->id()));
            $insertCreditLog = db()->prepare("INSERT INTO CreditHistory (accountID, type, price, creationDate) VALUES (?, ?, ?, ?)");
		        $insertCreditLog->execute(array(auth()->user()->id(), 4, $gift["gift"], datetime()));

            return $redirect->flash('success', t__('The gift has been delivered successfully!'));
        }
    }
	
		public function logs()
		{
			SeoService::set('gifts.logs');
			
			$logs = db()->prepare("SELECT PGH.*, PG.name, PG.giftType, PG.gift FROM ProductGiftsHistory PGH INNER JOIN ProductGifts PG ON PGH.giftID = PG.id WHERE PGH.accountID = ? ORDER by PGH.id DESC LIMIT 50");
			$logs->execute(array(auth()->user()->id()));
			$logs = array_map(function($log) {
				if ($log["giftType"] == 1) {
					$product = db()->prepare("SELECT name FROM Products WHERE id = ?");
					$product->execute(array($log["gift"]));
					$product = $product->fetch();
					$log["gift"] = $product["name"];
				}
				
				return $log;
			}, $logs->fetchAll());
			
			return $this->view('gifts.logs', compact('logs'));
		}
}