<?php

namespace Dashboard\Controllers;

use Dashboard\Core\Controller;

class CustomFieldController extends Controller
{
    public function __construct()
    {
        abort_perm('MANAGE_ACCOUNTS');
    }

    public function index()
    {
        $customFields = db()->query("SELECT * FROM AccountCustomFields ORDER BY id DESC");
        $customFields = $customFields->fetchAll();

        return view('custom-fields.index', compact('customFields'));
    }

    public function create()
    {
        return view('custom-fields.create');
    }

    public function store()
    {
        validate([
            'name' => 'required',
            'type' => 'required',
            'isRequired' => 'required',
            'isPublic' => 'required',
        ]);

        $insertCustomFields = db()->prepare("INSERT INTO AccountCustomFields (name, description, type, isRequired, isPublic) VALUES (?, ?, ?, ?, ?)");
        $insertCustomFields->execute(array(input("name"), input("description"), input("type"), input("isRequired"), input("isPublic")));
        return back()->flash("success", t__('Custom Field has been added successfully!'));
    }

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

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

        return view('custom-fields.edit', compact('customField'));
    }

    public function update($id)
    {
        validate([
            'name' => 'required',
            'type' => 'required',
            'isRequired' => 'required',
            'isPublic' => 'required',
        ]);

        $updateCustomFields = db()->prepare("UPDATE AccountCustomFields SET name = ?, description = ?, type = ?, isRequired = ?, isPublic = ? WHERE id = ?");
        $updateCustomFields->execute(array(input("name"), input("description"), input("type"), input("isRequired"), input("isPublic"), $id));
        return back()->flash("success", t__('Changes has been saved successfully!'));
    }

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