<?php

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

use Mtc\Modules\B2B\Models\TradeTier;

$page_meta['title'] = 'Trade Tiers';

init_request_values([
    'action' => null,
    'id' => null,
]);

$errors = [];
$success = '';

// Handle save (create/update)
if ($_REQUEST['action'] === 'save') {
    $name = trim($_POST['name'] ?? '');
    $discountPercentage = (float) ($_POST['discount_percentage'] ?? 0);

    if (empty($name)) {
        $errors[] = 'Please enter a tier name';
    }
    if ($discountPercentage < 0 || $discountPercentage > 100) {
        $errors[] = 'Discount percentage must be between 0 and 100';
    }

    if (empty($errors)) {
        if (!empty($_POST['id'])) {
            $tier = TradeTier::find($_POST['id']);
            if ($tier) {
                $tier->update([
                    'name' => $name,
                    'discount_percentage' => $discountPercentage,
                ]);
                $success = 'Tier updated successfully';
            }
        } else {
            TradeTier::create([
                'name' => $name,
                'discount_percentage' => $discountPercentage,
            ]);
            $success = 'Tier created successfully';
        }
    }
}

// Handle delete
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete' && is_numeric($_POST['id'] ?? '')) {
    if (!CSRF::checkToken('b2b_tier_delete')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $tier = TradeTier::withCount('customers')->find($_POST['id']);
        if ($tier) {
            if ($tier->customers_count > 0) {
                $errors[] = "Cannot delete tier '{$tier->name}' — {$tier->customers_count} customer(s) are assigned to it. Please reassign them first.";
            } else {
                $tier->delete();
                $success = 'Tier deleted successfully';
            }
        }
    }
}

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

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end">Trade Tiers</li>
</ul>

<h1>Trade Tiers</h1>

<?php include __DIR__ . '/tabnav.php'; ?>

<?php
if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($success)) {
    showmsg($success, 'success', $path);
}
?>

<?php if ($_REQUEST['action'] === 'edit' || $_REQUEST['action'] === 'create') { ?>

    <?php
    $tier = null;
    if ($_REQUEST['action'] === 'edit' && is_numeric($_REQUEST['id'])) {
        $tier = TradeTier::find($_REQUEST['id']);
    }
    ?>

    <h2><?= $tier ? 'Edit Tier' : 'Create Tier' ?></h2>

    <form method="post" action="?action=save" class="style">
        <?php if ($tier) { ?>
            <input type="hidden" name="id" value="<?= $tier->id ?>">
        <?php } ?>

        <div class="row">
            <label for="name">Tier Name</label>
            <input type="text" id="name" name="name" class="text" value="<?= clean_page($tier->name ?? '') ?>" required>
        </div>

        <div class="row">
            <label for="discount_percentage">Discount Percentage (%)</label>
            <input type="number" id="discount_percentage" name="discount_percentage" class="text" step="0.01" min="0" max="100" value="<?= $tier ? $tier->discount_percentage : '0' ?>" required>
        </div>

        <div class="row">
            <button type="submit" class="btn"><?= $tier ? 'Update Tier' : 'Create Tier' ?></button>
            <a href="tiers.php" class="btn cancel">Cancel</a>
        </div>
    </form>

<?php } else { ?>

    <?php $tiers = TradeTier::withCount('customers')->ordered()->get(); ?>

    <p><a href="?action=create" class="btn">Create New Tier</a></p>

    <div class="el msg alert">Tiers can only be deleted when no customers are assigned to them. Reassign customers to another tier first. <i class="fa fa-info-circle"></i></div>

    <?php if ($tiers->count() > 0) { ?>
    <table class="manage-items">
        <thead>
            <tr>
                <th>Name</th>
                <th>Discount</th>
                <th>Customers</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody class="tabular">
            <?php foreach ($tiers as $tier) { ?>
            <tr>
                <td><?= clean_page($tier->name) ?></td>
                <td><?= $tier->discount_percentage ?>%</td>
                <td><?= $tier->customers_count ?></td>
                <td>
                    <a href="?action=edit&id=<?= $tier->id ?>" class="btn btn-smaller">Edit</a>
                    <?php if ($tier->customers_count == 0) { ?>
                        <form method="post" action="tiers.php" style="display:inline" onsubmit="return confirm('Delete this tier?')">
                            <?= CSRF::token('b2b_tier_delete') ?>
                            <input type="hidden" name="action" value="delete">
                            <input type="hidden" name="id" value="<?= $tier->id ?>">
                            <button type="submit" class="btn btn-smaller delete">Delete</button>
                        </form>
                    <?php } ?>
                </td>
            </tr>
            <?php } ?>
        </tbody>
    </table>
    <?php } else { ?>
        <p>No trade tiers configured. Create your first tier to get started.</p>
    <?php } ?>

<?php } ?>

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