<?php

declare(strict_types=1);

// Si on n'est pas exécuté depuis la ligne de commande, on arrête tout !
if ('cli' != \PHP_SAPI) {
    exit(1);
}

// ///////////////////////////////////////////////
// Bootstrap PrestaShop
try {
    require_once __DIR__ . '/../../../config/config.inc.php';

    // Gestion multiboutique (au cas où) : Ce module est global
    if (Shop::isFeatureActive()) {
        Shop::setContext(Shop::CONTEXT_ALL);
    }
} catch (Exception $e) {
    echo $e->getMessage() . "\n" . $e->getTraceAsString();
    exit(1);
}

Module::getInstanceByName('myvetshopclinique');

$display_usage = false;

if ($argc >= 3) {
    $event = $argv[1];
    $objectId = $argv[2];
    $code = $argv[3] ?? null;

    if (
        !in_array($event, ['customer_join', 'customer_leave', 'customer_update', 'customer_disabled', 'order_updated'])
        || !is_numeric($objectId)
    ) {
        $display_usage = true;
    }
} else {
    $display_usage = true;
}

if ($display_usage) {
    echo "Usage : php create_event.php [type] [object_id] <privilege_code>\n";
    echo "\t type : customer_join, customer_leave, customer_update, customer_disabled, order_updated\n";
    echo "\t object_id : order id or customer id (dependending on type)\n";
    echo "\t privilege_code : Not required, override the privilege code\n";
    exit(1);
}

switch ($event) {
    case 'customer_join':
    case 'customer_leave':
    case 'customer_update':
    case 'customer_disabled':
        $customer = new Customer($objectId);
        if (!Validate::isLoadedObject($customer)) {
            echo "Can't load the customer";
            exit(1);
        }
        $eventObject = EstablishmentEvent::createCustomerEvent($event, $customer);
        break;

    case 'order_updated':
        $order = new Order($objectId);
        if (!Validate::isLoadedObject($order)) {
            echo "Can't load the order";
            exit(1);
        }
        $eventObject = EstablishmentEvent::createOrderEvent($event, $order);
        break;
}

if (!isset($eventObject)) {
    echo 'Unkown event type : ' . $event . "\n";
    exit(1);
}

if ($code) {
    $clinique = Clinique::getByCodePrivilege($code);

    if ($clinique) {
        $eventObject->id_myvetshop_clinique = $clinique->id;
    }
}

// Save event in database
$eventObject->save();

echo 'Event created : ' . $eventObject->id . "\n";
echo "\t id : " . $eventObject->id . "\n";
echo "\t id_myvetshop_clinique : " . $eventObject->id_myvetshop_clinique . "\n";
echo "\t event : " . $eventObject->event . "\n";
echo "\t id_customer : " . $eventObject->id_customer . "\n";
echo "\t customer_data : " . $eventObject->customer_data . "\n";
echo "\t id_order : " . $eventObject->id_order . "\n";
echo "\t order_data : " . $eventObject->order_data . "\n";
echo "\t date_add : " . $eventObject->date_add . "\n";
