<?php
namespace Mtc\Plugins\Prescriptions\Classes;

use Illuminate\Support\Facades\DB;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';
$per_page = 100;
$page = filter_input(INPUT_GET, 'page') ?? 1;
$messages = [];

$page_meta['title'] = 'Manage Private Prescription products';

if (filter_input(INPUT_POST, 'action') === 'upload' && !empty($_FILES['file'])) {

    if (mime_content_type($_FILES['file']['tmp_name']) !== 'text/plain' ) {
        $messages[] = [
            'type' => 'error',
            'content' => 'File must be a csv file'
        ];
    } else {

        $reader = \League\Csv\Reader::createFromPath($_FILES['file']['tmp_name']);
        $reader->setDelimiter(filter_input(INPUT_POST, 'delimiter'));
        $products = $reader->getRecords();


        $products = collect($products)
            ->map(function ($product_data) {
                if (trim($product_data[0]) === 'Product Description') {
                    return null;
                }

                return [
                    'name' => trim($product_data[0]),
                    'price' => preg_replace("/[^0-9\.]/", '', $product_data[3]),
                    'store_cost' => preg_replace("/[^0-9\.]/", '', $product_data[2]),
                    'pack_size' => $product_data[1]
                ];
            })
            ->filter();

        Medication::truncate();
        foreach ($products->chunk(200) as $chunk) {
            Medication::query()->insert($chunk->toArray());
        }

        $_SESSION['message'] = 'Products updated';
        header('Location: ' . \Util::add_query_arg([]));
        exit;
    }
}

if (!empty($_SESSION['message'])) {
    $messages[] = [
        'type' => 'success',
        'content' => $_SESSION['message']
    ];
    unset($_SESSION['message']);
}

$items = \Mtc\Plugins\Prescriptions\Classes\Medication::query();

$pagination = new \Mtc\Core\PaginationTemplate([
    'item_count' => $items->count(),
    'per_page' => $per_page,
    'active_page' => $page,
    'show_view_all' => false,
    'page_url' => '/private_prescriptions/admin/',
]);
$pagination = $pagination->render($twig);

$twig->display('Prescriptions/admin/index.twig', [
    'page_meta' => $page_meta,
    'items' => $items->take($per_page)->offset(($page - 1) * $per_page)->get(),
    'pagination' => $pagination,
    'messages' => $messages
]);