<?php
/**
 * Install Featured Products
 *
 * Add FEATURED_ITEMS constant to allow enabling / disabling.
 * Set up database for admin panel.
 *
 * @author Andrew Morgan <andrew.morgan@mtcmedia.co.uk>
 */

if (empty($path)) {
    $path = '../../../../';
    require_once $path . "core/includes/header.inc.php";
    $display_message = true;
}

use Illuminate\Database\Capsule\Manager as Capsule;
use Mtc\Core\Setting;

$data = [
    [
        'key' => 'FEATURED_PRODUCTS',
        'type' => 'bool',
        'value' => true,
        'module' => 'Featured Products',
        'description' => 'Set true to enable Featured Products',
        'created_at' => new \DateTime(),
    ]
];

foreach ($data as $key => $values) {
    if (defined($values['key'])) {
        unset($data[$key]);
    }
}

Setting::Insert($data);

// Add Tables to database

$path_to_admin_folder = str_replace(SITE_PATH, "", dirname(__DIR__));

$schema = Capsule::connection()->getSchemaBuilder();

// Check if the table exists. If it doesn't, build it.
if ($schema->hasTable('featured_products') === false) {
    // Build the table
    $schema->create('featured_products', function ($table) {
        $table->increments('id');
        $table->integer('item_id');
        $table->string('sex');
        $table->smallInteger('order');
        $table->timestamps();
        $table->index('id');
        $table->index('item_id');
        $table->index('order');
    });
}

// Insert admin entry (assumes shop is ID 100)
$setting_check = Capsule::table("admin_menu")->where('constant', 'FEATURED_PRODUCTS')->exists();

if (empty($setting_check)) {

    Capsule::table("admin_menu")->insertGetId([
        "sub_id"     => 100,
        "title"      => "Featured Products",
        "path"       => $path_to_admin_folder,
        "activePath" => $path_to_admin_folder,
        "constant"   => "FEATURED_PRODUCTS",
        "icon"       => "fa fa-fire",
        "new_window" => 0,
        "order"      => 100
    ]);
}

if ($display_message === true) {
    exit('Install successful');
}
