<?php

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

use Mtc\Modules\B2B\Enums\TradeCustomerStatus;
use Mtc\Modules\B2B\Events\TradeApplicationApprovedEvent;
use Mtc\Modules\B2B\Models\TradeCustomer;
use Mtc\Modules\B2B\Models\TradeTier;

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

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

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

// Handle approve action
if ($_REQUEST['action'] === 'approve' && is_numeric($_REQUEST['id'])) {
    $customer = TradeCustomer::with('member')->find($_REQUEST['id']);
    if ($customer && $customer->isPending()) {
        $tierId = $_POST['tier_id'] ?? null;
        if (!$tierId || !TradeTier::find($tierId)) {
            $errors[] = 'Please select a trade tier';
        } else {
            $customer->status = TradeCustomerStatus::Approved->value;
            $customer->tier_id = $tierId;
            $customer->approved_at = now();
            $customer->approved_by = $_SESSION['adminId'] ?? null;
            $customer->save();

            TradeApplicationApprovedEvent::dispatch($customer->load(['member', 'tier']));

            $success = 'Trade customer approved successfully';
        }
    }
}

// Handle reject action
if ($_REQUEST['action'] === 'reject' && is_numeric($_REQUEST['id'])) {
    $customer = TradeCustomer::with('member')->find($_REQUEST['id']);
    if ($customer && $customer->isPending()) {
        $customer->status = TradeCustomerStatus::Rejected->value;
        $customer->rejected_at = now();
        $customer->save();

        // Optionally send rejection email
        if (!empty($_POST['send_rejection_email'])) {
            $twig = app('twig');
            $html = $twig->render('b2b/emails/application_rejected.twig', [
                'trade_customer' => $customer,
                'member' => $customer->member,
                'rejection_reason' => $_POST['rejection_reason'] ?? '',
            ]);
            email(
                $customer->member->email,
                'Trade Account Application Update',
                $html
            );
        }

        $success = 'Trade application rejected';
    }
}

// Handle tier change
if ($_REQUEST['action'] === 'change_tier' && is_numeric($_REQUEST['id'])) {
    $customer = TradeCustomer::find($_REQUEST['id']);
    if ($customer && isset($_POST['tier_id'])) {
        $customer->tier_id = $_POST['tier_id'] !== '' ? $_POST['tier_id'] : null;
        $customer->save();
        $success = 'Tier updated 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 Customers</li>
</ul>

<h1>Trade Customers</h1>

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

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

<?php if ($_REQUEST['action'] === 'view' && is_numeric($_REQUEST['id'])) { ?>

    <?php
    $customer = TradeCustomer::with(['member.addressBilling', 'tier', 'address', 'accountOrders'])->find($_REQUEST['id']);
    $tiers = TradeTier::ordered()->get();

    if (!$customer) {
        showerrors(['Trade customer not found']);
    } else {
    ?>

        <h2><?= clean_page($customer->company_name) ?></h2>

        <table class="manage-items">
            <tr>
                <th>Status</th>
                <td>
                    <?= ucfirst($customer->status) ?>
                </td>
            </tr>
            <tr>
                <th>Contact Name</th>
                <td><?= clean_page($customer->member->addressBilling->firstname ?? '') ?> <?= clean_page($customer->member->addressBilling->lastname ?? '') ?></td>
            </tr>
            <tr>
                <th>Email</th>
                <td><?= clean_page($customer->member->email ?? '') ?></td>
            </tr>
            <tr>
                <th>Phone</th>
                <td><?= clean_page($customer->phone) ?></td>
            </tr>
            <tr>
                <th>Tier</th>
                <td><?= $customer->tier ? clean_page($customer->tier->name) . ' (' . $customer->tier->discount_percentage . '%)' : 'Trade pricing disabled' ?></td>
            </tr>
            <?php if ($customer->address) { ?>
            <tr>
                <th>Address</th>
                <td>
                    <?= clean_page($customer->address->address_1) ?><br>
                    <?php if ($customer->address->address_2) { ?><?= clean_page($customer->address->address_2) ?><br><?php } ?>
                    <?= clean_page($customer->address->city) ?><br>
                    <?= clean_page($customer->address->postcode) ?>
                </td>
            </tr>
            <?php } ?>
            <?php if ($customer->message) { ?>
            <tr>
                <th>Message</th>
                <td><?= clean_page($customer->message) ?></td>
            </tr>
            <?php } ?>
            <tr>
                <th>Applied</th>
                <td><?= $customer->created_at ? $customer->created_at->format('d/m/Y H:i') : '-' ?></td>
            </tr>
            <?php if ($customer->approved_at) { ?>
            <tr>
                <th>Approved</th>
                <td><?= $customer->approved_at->format('d/m/Y H:i') ?></td>
            </tr>
            <?php } ?>
        </table>

        <?php if ($customer->isPending()) { ?>
        <h3>Approve Application</h3>
        <form method="post" action="?action=approve&id=<?= $customer->id ?>" class="style">
            <div class="row">
                <label for="approve_tier_id">Assign Tier</label>
                <select name="tier_id" id="approve_tier_id" required>
                    <option value="">Select tier...</option>
                    <?php foreach ($tiers as $tier) { ?>
                        <option value="<?= $tier->id ?>"><?= clean_page($tier->name) ?> (<?= $tier->discount_percentage ?>%)</option>
                    <?php } ?>
                </select>
            </div>
            <div class="row">
                <button type="submit" class="btn" onclick="return confirm('Approve this application?')">Approve</button>
            </div>
        </form>

        <h3>Reject Application</h3>
        <form method="post" action="?action=reject&id=<?= $customer->id ?>" class="style">
            <input type="hidden" name="send_rejection_email" value="1">
            <div class="row">
                <label for="rejection_reason">Reason (optional)</label>
                <input type="text" id="rejection_reason" name="rejection_reason" class="text">
            </div>
            <div class="row">
                <button type="submit" class="btn delete" onclick="return confirm('Reject this application?')">Reject</button>
            </div>
        </form>
        <?php } ?>

        <?php if ($customer->isApproved()) { ?>
        <h3>Change Tier</h3>
        <form method="post" action="?action=change_tier&id=<?= $customer->id ?>" class="style">
            <div class="row">
                <label for="change_tier_id">Tier</label>
                <select name="tier_id" id="change_tier_id">
                    <option value="" <?= !$customer->tier_id ? 'selected' : '' ?>>Trade pricing disabled</option>
                    <?php foreach ($tiers as $tier) { ?>
                        <option value="<?= $tier->id ?>" <?= $customer->tier_id == $tier->id ? 'selected' : '' ?>><?= clean_page($tier->name) ?> (<?= $tier->discount_percentage ?>%)</option>
                    <?php } ?>
                </select>
            </div>
            <div class="row">
                <button type="submit" class="btn">Update Tier</button>
            </div>
        </form>
        <?php } ?>

        <?php
        $outstandingOrders = $customer->accountOrders()->unpaid()->with('order')->get();
        $paidOrders = $customer->accountOrders()->paid()->with('order')->latest()->limit(20)->get();
        $outstandingBalance = $outstandingOrders->sum('amount_due');
        ?>

        <?php if ($outstandingOrders->count() > 0) { ?>
        <h3>Outstanding Orders (<?= number_format($outstandingBalance, 2) ?>)</h3>
        <table class="manage-items">
            <thead>
                <tr>
                    <th>PO Number</th>
                    <th>Order Ref</th>
                    <th>Amount Due</th>
                    <th>Date</th>
                </tr>
            </thead>
            <tbody class="tabular">
                <?php foreach ($outstandingOrders as $accountOrder) { ?>
                <tr>
                    <td><?= clean_page($accountOrder->po_number) ?></td>
                    <td><?= $accountOrder->order ? $accountOrder->order->id : '-' ?></td>
                    <td>&pound;<?= number_format($accountOrder->amount_due, 2) ?></td>
                    <td><?= $accountOrder->created_at ? $accountOrder->created_at->format('d/m/Y') : '-' ?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php } ?>

        <?php if ($paidOrders->count() > 0) { ?>
        <h3>Recent Paid Orders</h3>
        <table class="manage-items">
            <thead>
                <tr>
                    <th>PO Number</th>
                    <th>Order Ref</th>
                    <th>Amount</th>
                    <th>Paid</th>
                </tr>
            </thead>
            <tbody class="tabular">
                <?php foreach ($paidOrders as $accountOrder) { ?>
                <tr>
                    <td><?= clean_page($accountOrder->po_number) ?></td>
                    <td><?= $accountOrder->order ? $accountOrder->order->id : '-' ?></td>
                    <td>&pound;<?= number_format($accountOrder->amount_due, 2) ?></td>
                    <td><?= $accountOrder->paid_at ? $accountOrder->paid_at->format('d/m/Y') : '-' ?></td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
        <?php } ?>

    <?php } ?>

<?php } else { ?>

    <?php
    // List view
    $query = TradeCustomer::with(['member.addressBilling', 'tier']);

    if (!empty($_REQUEST['status'])) {
        $query->where('status', $_REQUEST['status']);
    }
    if (!empty($_REQUEST['tier_id'])) {
        $query->where('tier_id', $_REQUEST['tier_id']);
    }
    if (!empty($_REQUEST['search'])) {
        $search = $_REQUEST['search'];
        $query->where(function ($q) use ($search) {
            $q->where('company_name', 'like', "%{$search}%")
              ->orWhereHas('member', function ($mq) use ($search) {
                  $mq->where('email', 'like', "%{$search}%");
              });
        });
    }

    $customers = $query->orderBy('created_at', 'desc')->paginate(25);
    $customers->appends($_GET);
    $tiers = TradeTier::ordered()->get();
    ?>

    <form method="get" class="style">
        <fieldset class="show">
            <h1><a class="show el">Filter <i class="fa fa-caret-right"></i></a></h1>
            <div class="row">
                <label for="status">Status</label>
                <select name="status" id="status">
                    <option value="">All Statuses</option>
                    <option value="<?= TradeCustomerStatus::Pending->value ?>" <?= $_REQUEST['status'] === TradeCustomerStatus::Pending->value ? 'selected' : '' ?>>Pending</option>
                    <option value="<?= TradeCustomerStatus::Approved->value ?>" <?= $_REQUEST['status'] === TradeCustomerStatus::Approved->value ? 'selected' : '' ?>>Approved</option>
                    <option value="<?= TradeCustomerStatus::Rejected->value ?>" <?= $_REQUEST['status'] === TradeCustomerStatus::Rejected->value ? 'selected' : '' ?>>Rejected</option>
                </select>
            </div>
            <div class="row">
                <label for="tier_id">Tier</label>
                <select name="tier_id" id="tier_id">
                    <option value="">All Tiers</option>
                    <?php foreach ($tiers as $tier) { ?>
                        <option value="<?= $tier->id ?>" <?= $_REQUEST['tier_id'] == $tier->id ? 'selected' : '' ?>><?= clean_page($tier->name) ?></option>
                    <?php } ?>
                </select>
            </div>
            <div class="row">
                <label for="search">Search</label>
                <input type="text" name="search" id="search" class="text" value="<?= clean_page($_REQUEST['search'] ?? '') ?>" placeholder="Company or email...">
            </div>
            <div class="row">
                <input type="submit" value="Filter" class="btn">
                <a href="customers.php" class="btn cancel">Reset</a>
            </div>
        </fieldset>
    </form>

    <?php if ($customers->total() > 0) { ?>
    <table class="manage-items">
        <thead>
            <tr>
                <th>Company</th>
                <th>Contact</th>
                <th>Email</th>
                <th>Status</th>
                <th>Tier</th>
                <th>Applied</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody class="tabular">
            <?php foreach ($customers as $customer) { ?>
            <tr>
                <td><?= clean_page($customer->company_name) ?></td>
                <td><?= clean_page($customer->member->addressBilling->firstname ?? '') ?> <?= clean_page($customer->member->addressBilling->lastname ?? '') ?></td>
                <td><?= clean_page($customer->member->email ?? '') ?></td>
                <td><?= ucfirst($customer->status) ?></td>
                <td><?= $customer->tier ? clean_page($customer->tier->name) : 'Trade pricing disabled' ?></td>
                <td><?= $customer->created_at ? $customer->created_at->format('d/m/Y') : '-' ?></td>
                <td><a href="?action=view&id=<?= $customer->id ?>" class="btn btn-smaller">View</a></td>
            </tr>
            <?php } ?>
        </tbody>
    </table>

    <?= $customers->render() ?>

    <?php } else { ?>
        <p>No trade customers found.</p>
    <?php } ?>

<?php } ?>

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