<?php
use Mtc\Core\PaginationTemplate;
use Mtc\Shop\Brand;
use Illuminate\Support\Facades\DB;


$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

init_request_values([
    'name' => null,
]);

$page_meta['title'] = 'Manage Brands';
$errors = [];

$message = filter_input(INPUT_GET, 'message');

$page = !empty($_REQUEST['page']) ? (int)$_REQUEST['page'] : 1;
$per_page = 25;
$errors = [];

if (!empty($_REQUEST['action'])
    && $_REQUEST['action'] == 'update'
    && is_array($_REQUEST['ids'])
    && count($_REQUEST['ids']) > 0
) {
    foreach ($_REQUEST['ids'] as $id) {
        $hide = !empty($_REQUEST[$id . '_hide']) ? 1 : 0;

        Brand::where('id', $id)
            ->update([
                'hide' => $hide
            ]);
    }
    $message = 'Brands updated';
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'export_brands') {
    $rows = Brand::query()
        ->where('brands.deleted', false)
        ->addSelect(Brand::getExportableFields())
        ->get()
        ->toArray();
    $csv = array_to_csv($rows);
    \Util::force_download('brands__' . date('Ymd_His') . '.csv', $csv);
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'import_brands') {
    $result = validate_csv_upload('import');
    $update_log = ['updated' => [], 'failed' => [], 'not_found' => [], 'skipped' => []];

    if (! $result['errors']) {
        $first = true;
        $columns = [];
        while (($csv_data = fgetcsv($result['handle'], null, ',')) !== false) {
            if ($first) {
                $columns = $csv_data;
                $first = false;
                continue;
            }
            if (count($columns) !== count($csv_data)) {
                $update_log['skipped'][] = $csv_data[0] ?? '(empty row)';
                continue;
            }
            $data = array_combine($columns, $csv_data);
            if (empty($data['id'])) {
                $update_log['skipped'][] = '(missing id)';
                continue;
            }
            $brand = Brand::find($data['id']);
            if ($brand) {
                $brand->fill($data);
                if ($brand->save()) {
                    $update_log['updated'][] = $brand->id;
                } else {
                    $update_log['failed'][] = $brand->id;
                }
            } else {
                $update_log['not_found'][] = $data['id'];
            }
        }

        $msg = 'Updated ' . count($update_log['updated']) . ' records.<br />';
        if ($update_log['failed']) {
            $msg .= 'Could not update the following records: ' . implode(', ', $update_log['failed']) . '.<br />';
        }
        if ($update_log['not_found']) {
            $msg .= 'Could not find the following records: ' . implode(', ', $update_log['not_found']) . '.<br />';
        }
        if ($update_log['skipped']) {
            $msg .= 'Skipped ' . count($update_log['skipped']) . ' malformed rows.<br />';
        }

        $query_params = $_GET;
        $query_params['success'] = 'import_successful';
        $_SESSION['flash_messages']['success'] = $msg;
        header('Location: manage.brands.php?' . http_build_query($query_params));
        exit;
    } else {
        $errors = $result['errors'];
    }
}

if (BRANDS_HIDE === true) {
    $hidepage = [
        'action' => 'hidepage',
    ];
    $showpage = [
        'action' => 'showpage',
    ];
    $hideall  = [
        'action' => 'hideall',
    ];
    $showall  = [
        'action' => 'showall',
    ];
}


//  Delete This Brand
if ($_REQUEST['action'] == 'delete' && is_numeric($_REQUEST['delete_id'])) {
    try {
        $brand = Brand::findOrFail($_REQUEST['delete_id']);

        if (BRANDS_IMAGES === true && !empty($brand->image)) {
            foreach ($image_folders['brand_images'] as $folder) {
                if (file_exists(SITE_PATH . '/' . $folder['path'] . '/' . $brand->image)) {
                    unlink(SITE_PATH . '/' . $folder['path'] . '/' . $brand->image);
                }
            }
        }

        if (BRANDS_LOGOS === true && !empty($brand->logo)) {
            foreach ($image_folders['brand_images'] as $folder) {
                if (file_exists(SITE_PATH . '/' . $folder['path'] . '/' . $brand->logo)) {
                    unlink(SITE_PATH . '/' . $folder['path'] . '/' . $brand->logo);
                }
            }
        }

        DB::table('items_brands')
            ->where('brand_id', $brand->id)
            ->delete();
        $brand->delete();
        $message = 'Brand Removed';
    } catch (Exception $e) {
        $errors[] = $e->getMessage();
    }
}

$brands = Brand::query()
    ->selectRaw('brands.*')
;

if (!empty($_REQUEST['name'])) {
    $brands->where('brands.name', 'LIKE', '%' . $_REQUEST['name'] . '%');
} else {
    $brands->where('brands.id', '>', 0);
}

if (BRANDS_ORDERING === true) {
    $brands->orderBy('order', 'ASC');
} else {
    $brands->orderBy('name', 'ASC');
}

$pagination_items = $brands->get()->slice(($page - 1) * $per_page, $per_page)->all();

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'hidepage') {
    foreach ($pagination_items as $brand) {
        Brand::where('id', $brand->id)
             ->update(['hide' => 1]);
    }
    $message = 'All Brands on this page are set to be hidden';
    $params = [
        'page'    => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/brands/manage.brands.php?' . http_build_query($params));
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'showpage') {
    foreach ($pagination_items as $brand) {
        Brand::where('id', $brand->id)
             ->update(['hide' => 0]);
    }
    $message = 'All Brands on this page are set to be shown';
    $params = [
        'page'    => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/brands/manage.brands.php?' . http_build_query($params));
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'hideall') {
    $allbrands = $brands->get();
    foreach ($allbrands as $brand) {
        Brand::where('id', $brand->id)
             ->update(['hide' => 1]);
    }
    $message = 'All Brands are set to be hidden';
    $params = [
        'page'    => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/brands/manage.brands.php?' . http_build_query($params));
    exit;
}

if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'showall') {
    $allbrands = $brands->get();
    foreach ($allbrands as $brand) {
        Brand::where('id', $brand->id)
             ->update(['hide' => 0]);
    }
    $message = 'All Brands set to be shown';
    $params = [
        'page'    => $page,
        'message' => $message
    ];
    header('Location:' . SITE_URL . '/shop/admin/brands/manage.brands.php?' . http_build_query($params));
    exit;
}

$query_string = '';
if (!empty($_REQUEST['name'])) {
    $query_string = "?action=search&name=" . $_REQUEST['name'];
}

$pagination = new PaginationTemplate([
    'item_count' => $brands->count(),
    'per_page' => $per_page,
    'active_page' => $page,
    'show_view_all' => false,
    'page_url' => '/shop/admin/brands/manage.brands.php' . $query_string,
]);

$pagination = $pagination->render($twig);

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>

    <li class="end">Manage Brands</li>
</ul>
<h1>Manage Brands</h1>

<?php

include 'tabnav.php';

if (empty($errors) && isset($GLOBALS['flash_messages']) && !empty($GLOBALS['flash_messages']['success'])) {
    echo showmsg($GLOBALS['flash_messages']['success'], 'success', $path);
}

if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($message)) {
    echo showmsg($message, 'success', $path);
}
?>
<form action="manage.brands.php" method="get" class="style">
    <fieldset class="show">
        <h1><a class="show el">Search <i class="fa fa-caret-right"></i></a></h1>

        <div class="row">
            <label for="name">Name</label>
            <input type="text" name="name" id="name" value="<?= clean_page($_REQUEST['name']) ?>">
        </div>

        <input type="hidden" name="action" value="search">
        <div class="search-button"><input type="submit" value="Search" class="BUTTON"/></div>
    </fieldset>
</form>
<?php
if (count($pagination_items) > 0) {
    echo $pagination;
    ?>

    <form action="<?= Util::add_query_arg([])?>" method="post">
        <table class="manage-items">
            <tr>
                <?php
                if (BRANDS_ORDERING === true) {
                    ?>
                    <th class="center">Order</th>
                    <?php
                }
                ?>
                <th class="fieldname">Name</th>
                <?php
                if (BRANDS_IMAGES === true) {
                    ?>
                    <th class="center">Image</th>
                    <?php
                }

                if (BRANDS_HIDE === true) {
                    ?>
                    <th class="center">Hide<br/>
                        <small>
                            <a href="<?= Util::add_query_arg($hidepage) ?>"
                               class="alert"
                               title="Are you sure you want to set everything on this page to be hidden?">
                                <small>Hide&nbsp;All</small>
                            </a>
                            <br/>
                            <a href="<?= Util::add_query_arg($showpage) ?>"
                               class="alert"
                               title="Are you sure you want to set everything on this page to be viewable?">
                                <small>Show&nbsp;All</small>
                            </a>
                        </small>
                    </th>
                    <?php
                }
                ?>
                <th class="center">Edit</th>
                <th class="center">Delete</th>
            </tr>
            <tbody class="tabular ui-sortable">
                <?php
                foreach ($pagination_items as $brand) {
                    ?>
                    <tr id="rorder-<?= clean_page($brand->id) ?>">
                        <?php
                        if (BRANDS_ORDERING === true) {
                            ?>
                            <td class="center order">
                                <i class="fa fa-arrows"></i>
                            </td>
                            <?php
                        }
                        ?>
                        <td>
                            <a href="edit.brands.php?id=<?= clean_page($brand->id); ?>">
                                <?= clean_page($brand->name) ?>
                            </a>
                            <input type="hidden"
                                   name="ids[]"
                                   value="<?= clean_page($brand->id) ?>" />
                        </td>
                        <?php
                        if (BRANDS_IMAGES === true) {
                            ?>
                            <td class="center">
                                <?php
                                if (!empty($brand->image)) {
                                    ?>
                                    <img src="<?= SITE_URL . '/' . $image_folders['brand_images']['small']['path']
                                        . '/' . clean_page($brand->image) ?>">
                                    <?php
                                }
                                ?>
                            </td>
                            <?php
                        }


                        if (BRANDS_HIDE === true) {
                            ?>
                            <td class="center">
                                <input type="checkbox"
                                       name="<?= clean_page($brand->id); ?>_hide"
                                    <?= $brand->hide == 1 ? 'checked="checked"' : '' ?>/>
                            </td>
                        <?php } ?>
                        <td class="center">
                            <a href="edit.brands.php?id=<?= clean_page($brand->id); ?>"
                               class="edit picto">
                                <i class="fa fa-pencil"></i>
                            </a>
                        </td>
                        <td class="center">
                            <a href="manage.brands.php?action=delete&delete_id=<?= clean_page($brand->id); ?>"
                               class="alert error"
                               title="Are you sure you want to delete this brand?">
                                <i class="fa fa-times-circle"></i>
                            </a>
                        </td>
                    </tr>
                    <?php
                }
                ?>
            </tbody>
        </table>
        <p>
            <?php
            if (BRANDS_HIDE === true) { ?>
                <input type="hidden" name="action" value="update">
                <input type="submit" value="Update" />
                <input type="hidden" id="orderbytable" value="brands" />
                <input type="hidden" id="orderbyfield" value="order" />

                <?php
                echo $pagination;
                if (BRANDS_HIDE === true) { ?>
                    <br/>
                    <br/>
                    <div class="style">
                        <fieldset class="show">
                            <h1><a class="show el">Advanced Options <i class="fa fa-caret-right"></i></a></h1>
                            <h5>Site-Wide Hide Settings</h5>
                            <div class="row">

                                <a href="<?= Util::add_query_arg($hideall) ?>"
                                   class="alert"
                                   title="This will set ALL Brands on the site to be hidden, are you sure you want to do that?">
                                    Hide All Brands
                                </a>
                                <br/>
                                <b class="error">Warning:</b> This will set all Brands across the site to be set to <b>hidden</b>
                            </div>

                            <div class="row">
                                <a href="<?= Util::add_query_arg($showall) ?>"
                                   class="alert"
                                   title="This will set ALL Brands on the site to be viewable, are you sure you want to do that?">
                                    Show All Brands
                                </a>
                                <br/>
                                <b class="error">Warning:</b> This will set all Brands across the site to be set to <b>visible</b>
                            </div>
                        </fieldset>
                    </div>
                    <?php
                }
            }
            ?>
            <input type="hidden" name="page" value="<?= clean_page($page) ?>" />
        </p>

        <div id="res"></div>
    </form>
    <?php
} elseif ($_REQUEST['action'] == 'search') {
    ?>
    <p>No brands found matching your search criteria</p>
    <?php
} else {
    ?>
    <p>No Brands have been created</p>
    <?php
}

?>


<form method="post" class="style">
    <h2>Export</h2>

    <div class="row">
        <input type="hidden" name="action" value="export_brands"/>
        <button type="submit" class="btn">Export</button>
    </div>
</form>

<form method="post" enctype="multipart/form-data" class="style">
    <h2>Import</h2>
    <fieldset>
        <div class="row">
            <label for="select_file">File selection</label>
            <input type="file" name="import" />
        </div>
        <div class="row">
            <input type="hidden" name="action" value="import_brands"/>
            <button
                type="submit"
                class="btn"
            >
                Import
            </button>
        </div>
    </fieldset>
</form>


<?php require_once $path . 'core/admin/templates/adminfooter.html.php'; ?>
