<?php

namespace Dashboard\Controllers\Store;

use Dashboard\Core\Controller;

class CreatorCodeController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_STORE');
    }

    public function index()
    {
        $creatorCodes = db()->query("SELECT C.*, A.realname, A.username FROM CreatorCodes C INNER JOIN Accounts A ON A.id = C.creatorID ORDER BY C.id DESC");
		    $creatorCodes = $creatorCodes->fetchAll();

        return view('store.creator-codes.index', compact('creatorCodes'));
    }

    public function create()
    {
        return view('store.creator-codes.create');
    }

    public function store()
    {
        validate([
            'code' => 'required',
            'creatorID' => 'required',
	          'discount' => 'required',
	          'share' => 'required',
        ]);
				
				$checkCodeExist = db()->prepare("SELECT * FROM CreatorCodes WHERE code = ?");
				$checkCodeExist->execute([str_replace(" ", "_", input("code"))]);
				$checkCodeExist = $checkCodeExist->fetch();
				if ($checkCodeExist) {
					return back()->flash("error", t__('Creator Code already exists!'));
				}

        $insertCreatorCodes = db()->prepare("INSERT INTO CreatorCodes (code, creatorID, discount, share, creationDate) VALUES (?, ?, ?, ?, ?)");
        $insertCreatorCodes->execute([str_replace(" ", "_", input("code")), input("creatorID"), input("discount"), input("share"), datetime()]);
        return back()->flash("success", t__('Creator Code has been added successfully!'));
    }

    public function edit($id)
    {
        $creatorCode = db()->prepare("SELECT * FROM CreatorCodes WHERE id = ?");
		    $creatorCode->execute(array($id));
		    $creatorCode = $creatorCode->fetch();

        if (!$creatorCode) return view('404');

        return view('store.creator-codes.edit', compact('creatorCode'));
    }

    public function update($id)
    {
		    validate([
			    'code' => 'required',
			    'creatorID' => 'required',
			    'discount' => 'required',
			    'share' => 'required',
		    ]);

        $updateCreatorCodes = db()->prepare("UPDATE CreatorCodes SET code = ?, creatorID = ?, discount = ?, share = ? WHERE id = ?");
        $updateCreatorCodes->execute([str_replace(" ", "_", input("code")), input("creatorID"), input("discount"), input("share"), $id]);
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

    public function destroy($id)
    {
        $deleteCreatorCode = db()->prepare("DELETE FROM CreatorCodes WHERE id = ?");
	      $deleteCreatorCode->execute(array($id));
        return back();
    }
}