<?php

/** @var yii\web\View $this */
/** @var common\models\Customer $model */
/** @var common\models\Plan[] $plans */

use common\models\Customer;
use common\models\CustomerPlan;
use common\models\Invoice;
use yii\bootstrap5\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;

$this->title = $model->name;

// Eager-load everything needed for this page
$customerPlans = CustomerPlan::find()
    ->with('plan')
    ->where(['customer_id' => $model->id])
    ->orderBy(['created_at' => SORT_DESC])
    ->all();

$invoices = Invoice::find()
    ->where(['customer_id' => $model->id])
    ->orderBy(['created_at' => SORT_DESC])
    ->limit(10)
    ->all();

$dietPlans = $model->dietPlans;

// Financial summary
$totalBilled      = array_sum(array_column(ArrayHelper::toArray($invoices), 'total_amount'));
$totalPaid        = array_sum(array_column(ArrayHelper::toArray($invoices), 'paid_amount'));
$totalOutstanding = max(0, $totalBilled - $totalPaid);

$statusBadge = [
    Invoice::STATUS_PAID      => 'success',
    Invoice::STATUS_UNPAID    => 'danger',
    Invoice::STATUS_PARTIAL   => 'warning',
    Invoice::STATUS_CANCELLED => 'secondary',
];
?>

<!-- Page header -->
<div class="d-flex justify-content-between align-items-center mb-3">
    <a href="<?= Url::to(['/customer/index']) ?>" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-left"></i> Back
    </a>
    <div class="d-flex gap-2">
        <a href="<?= Url::to(['/invoice/create', 'customer_id' => $model->id]) ?>" class="btn btn-sm btn-outline-info">
            <i class="bi bi-receipt"></i> New Invoice
        </a>
        <a href="<?= Url::to(['/diet-plan/create', 'customer_id' => $model->id]) ?>" class="btn btn-sm btn-outline-warning">
            <i class="bi bi-clipboard2-plus"></i> Diet Plan
        </a>
        <a href="<?= Url::to(['/customer/update', 'id' => $model->id]) ?>" class="btn btn-sm btn-outline-primary">
            <i class="bi bi-pencil"></i> Edit
        </a>
    </div>
</div>

<div class="row g-3">

    <!-- ── Left column: profile + financial summary ── -->
    <div class="col-lg-4">

        <!-- Profile card -->
        <div class="card mb-3">
            <div class="card-body text-center py-4">
                <div class="bg-primary bg-opacity-10 rounded-circle d-inline-flex align-items-center
                            justify-content-center mb-3"
                     style="width:72px;height:72px;font-size:2rem">
                    <i class="bi bi-person text-primary"></i>
                </div>
                <h5 class="mb-1 fw-semibold"><?= Html::encode($model->name) ?></h5>
                <p class="text-muted small mb-1">
                    <i class="bi bi-telephone"></i> <?= Html::encode($model->phone) ?>
                </p>
                <?php if ($model->email): ?>
                <p class="text-muted small mb-2">
                    <i class="bi bi-envelope"></i> <?= Html::encode($model->email) ?>
                </p>
                <?php endif; ?>
                <span class="badge bg-<?= $model->customer_type === Customer::TYPE_BUSINESS ? 'warning text-dark' : 'primary' ?>">
                    <?= $model->isMember() ? 'Gym Member' : ucfirst($model->customer_type) ?>
                </span>
                <?php if (!$model->is_active): ?>
                    <span class="badge bg-secondary ms-1">Inactive</span>
                <?php endif; ?>
            </div>
            <?php if ($model->address): ?>
            <div class="card-footer bg-light small text-muted py-2">
                <i class="bi bi-geo-alt"></i> <?= nl2br(Html::encode($model->address)) ?>
            </div>
            <?php endif; ?>
        </div>

        <!-- Business info -->
        <?php if ($model->isBusiness()): ?>
        <div class="card mb-3">
            <div class="card-header bg-white fw-semibold small text-uppercase text-muted">Business Info</div>
            <div class="card-body small">
                <dl class="row mb-0">
                    <dt class="col-5 text-muted">Company</dt>
                    <dd class="col-7"><?= Html::encode($model->company_name) ?></dd>
                    <?php if ($model->gst_number): ?>
                    <dt class="col-5 text-muted">GST</dt>
                    <dd class="col-7"><?= Html::encode($model->gst_number) ?></dd>
                    <?php endif; ?>
                </dl>
            </div>
        </div>
        <?php endif; ?>

        <!-- Parent/member info -->
        <?php if ($model->isMember() && $model->parentCustomer): ?>
        <div class="card mb-3">
            <div class="card-header bg-white fw-semibold small text-uppercase text-muted">Member Of</div>
            <div class="card-body small">
                <a href="<?= Url::to(['/customer/view', 'id' => $model->parentCustomer->id]) ?>">
                    <?= Html::encode($model->parentCustomer->name) ?>
                </a>
            </div>
        </div>
        <?php endif; ?>

        <!-- Financial summary -->
        <div class="card">
            <div class="card-header bg-white fw-semibold small text-uppercase text-muted">Account Balance</div>
            <div class="card-body">
                <div class="row text-center g-2">
                    <div class="col-4">
                        <div class="fw-bold fs-6">₹<?= number_format($totalBilled, 0) ?></div>
                        <div class="text-muted" style="font-size:.7rem">Billed</div>
                    </div>
                    <div class="col-4">
                        <div class="fw-bold fs-6 text-success">₹<?= number_format($totalPaid, 0) ?></div>
                        <div class="text-muted" style="font-size:.7rem">Paid</div>
                    </div>
                    <div class="col-4">
                        <div class="fw-bold fs-6 <?= $totalOutstanding > 0 ? 'text-danger' : 'text-success' ?>">
                            ₹<?= number_format($totalOutstanding, 0) ?>
                        </div>
                        <div class="text-muted" style="font-size:.7rem">Due</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Notes -->
        <?php if ($model->notes): ?>
        <div class="card mt-3">
            <div class="card-header bg-white fw-semibold small text-uppercase text-muted">Notes</div>
            <div class="card-body small text-muted"><?= nl2br(Html::encode($model->notes)) ?></div>
        </div>
        <?php endif; ?>
    </div>

    <!-- ── Right column: plans, invoices, diet plans ── -->
    <div class="col-lg-8">

        <!-- ── Plans ── -->
        <div class="card mb-3">
            <div class="card-header bg-white fw-semibold d-flex justify-content-between align-items-center">
                <span>Plans</span>
                <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#assignPlanModal">
                    <i class="bi bi-plus-lg"></i> Assign Plan
                </button>
            </div>
            <?php if (empty($customerPlans)): ?>
                <div class="card-body text-muted small">No plans assigned yet.</div>
            <?php else: ?>
            <div class="card-body p-0">
                <table class="table table-sm table-hover mb-0">
                    <thead>
                        <tr>
                            <th>Plan</th>
                            <th>Type</th>
                            <th>Start</th>
                            <th>End</th>
                            <th>Status</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($customerPlans as $cp): ?>
                        <tr>
                            <td class="fw-semibold"><?= $cp->plan ? Html::encode($cp->plan->name) : '—' ?></td>
                            <td>
                                <span class="badge bg-<?= ($cp->plan && $cp->plan->plan_type === 'subscription') ? 'info text-dark' : 'warning text-dark' ?>">
                                    <?= $cp->plan ? ucfirst(str_replace('_', '-', $cp->plan->plan_type)) : '—' ?>
                                </span>
                            </td>
                            <td><?= date('d M Y', strtotime($cp->start_date)) ?></td>
                            <td><?= $cp->end_date ? date('d M Y', strtotime($cp->end_date)) : '—' ?></td>
                            <td>
                                <span class="badge bg-<?= [
                                    CustomerPlan::STATUS_ACTIVE    => 'success',
                                    CustomerPlan::STATUS_EXPIRED   => 'warning text-dark',
                                    CustomerPlan::STATUS_CANCELLED => 'secondary',
                                ][$cp->status] ?? 'secondary' ?>">
                                    <?= ucfirst($cp->status) ?>
                                </span>
                                <?php if ($cp->end_date && $cp->status === CustomerPlan::STATUS_ACTIVE && strtotime($cp->end_date) <= strtotime('+7 days')): ?>
                                    <span class="badge bg-danger ms-1">Expiring soon</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($cp->status === CustomerPlan::STATUS_ACTIVE): ?>
                                <?php echo Html::beginForm(['/customer-plan/cancel'], 'POST', ['style' => 'display:inline']) ?>
                                <?= Html::hiddenInput('id', $cp->id) ?>
                                <?= Html::hiddenInput('customer_id', $model->id) ?>
                                <?= Html::submitButton(
                                    '<i class="bi bi-x-lg"></i>',
                                    [
                                        'class'        => 'btn btn-sm btn-outline-danger',
                                        'title'        => 'Cancel plan',
                                        'data-confirm' => 'Cancel this plan?',
                                    ]
                                ) ?>
                                <?php echo Html::endForm() ?>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>

        <!-- ── Invoices ── -->
        <div class="card mb-3">
            <div class="card-header bg-white fw-semibold d-flex justify-content-between align-items-center">
                <span>Invoices</span>
                <a href="<?= Url::to(['/invoice/create', 'customer_id' => $model->id]) ?>"
                   class="btn btn-sm btn-outline-info">
                    <i class="bi bi-plus-lg"></i> New Invoice
                </a>
            </div>
            <?php if (empty($invoices)): ?>
                <div class="card-body text-muted small">No invoices yet.</div>
            <?php else: ?>
            <div class="card-body p-0">
                <table class="table table-sm table-hover mb-0">
                    <thead>
                        <tr><th>#</th><th>Date</th><th>Total</th><th>Paid</th><th>Due</th><th>Status</th><th></th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($invoices as $inv): ?>
                        <tr>
                            <td>
                                <a href="<?= Url::to(['/invoice/view', 'id' => $inv->id]) ?>" class="fw-semibold text-decoration-none">
                                    <?= Html::encode($inv->invoice_number) ?>
                                </a>
                            </td>
                            <td><?= date('d M Y', strtotime($inv->invoice_date)) ?></td>
                            <td>₹<?= number_format($inv->total_amount, 2) ?></td>
                            <td class="text-success">₹<?= number_format($inv->paid_amount, 2) ?></td>
                            <td class="<?= $inv->getOutstandingAmount() > 0 ? 'text-danger fw-semibold' : 'text-success' ?>">
                                ₹<?= number_format($inv->getOutstandingAmount(), 2) ?>
                            </td>
                            <td>
                                <span class="badge bg-<?= $statusBadge[$inv->status] ?? 'secondary' ?>">
                                    <?= ucfirst($inv->status) ?>
                                </span>
                            </td>
                            <td>
                                <?php if (in_array($inv->status, [Invoice::STATUS_UNPAID, Invoice::STATUS_PARTIAL])): ?>
                                <button class="btn btn-sm btn-success py-0 px-2"
                                        onclick="openQuickPay(<?= $inv->id ?>, '<?= Html::encode($inv->invoice_number) ?>', <?= $inv->getOutstandingAmount() ?>)">
                                    <i class="bi bi-cash"></i> Pay
                                </button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>

        <!-- ── Diet Plans ── -->
        <div class="card">
            <div class="card-header bg-white fw-semibold d-flex justify-content-between align-items-center">
                <span>Diet Plans</span>
                <a href="<?= Url::to(['/diet-plan/create', 'customer_id' => $model->id]) ?>"
                   class="btn btn-sm btn-outline-warning">
                    <i class="bi bi-plus-lg"></i> New Plan
                </a>
            </div>
            <?php if (empty($dietPlans)): ?>
                <div class="card-body text-muted small">No diet plans yet.</div>
            <?php else: ?>
            <div class="card-body p-0">
                <table class="table table-sm table-hover mb-0">
                    <thead><tr><th>Title</th><th>Calories</th><th>Status</th><th>Date</th><th></th></tr></thead>
                    <tbody>
                    <?php foreach (array_slice($dietPlans, 0, 8) as $dp): ?>
                        <tr>
                            <td>
                                <a href="<?= Url::to(['/diet-plan/view', 'id' => $dp->id]) ?>" class="text-decoration-none fw-semibold">
                                    <?= Html::encode($dp->title) ?>
                                </a>
                            </td>
                            <td><?= number_format($dp->total_calories, 0) ?> kcal</td>
                            <td>
                                <span class="badge bg-<?= ['draft' => 'secondary', 'active' => 'success', 'archived' => 'dark'][$dp->status] ?>">
                                    <?= ucfirst($dp->status) ?>
                                </span>
                            </td>
                            <td><?= date('d M Y', $dp->created_at) ?></td>
                            <td>
                                <a href="<?= Url::to(['/diet-plan/pdf', 'id' => $dp->id]) ?>" target="_blank"
                                   class="btn btn-sm btn-outline-danger py-0 px-2" title="Download PDF">
                                    <i class="bi bi-file-earmark-pdf"></i>
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>
        </div>

    </div><!-- /col-lg-8 -->
</div><!-- /row -->

<!-- ══════════════════════════════════════════════════════════
     Modal: Assign Plan
════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="assignPlanModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-semibold">Assign Plan to <?= Html::encode($model->name) ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <?php echo Html::beginForm(['/customer-plan/assign'], 'POST', ['id' => 'assign-plan-form']) ?>
            <?= Html::hiddenInput('customer_id', $model->id) ?>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-semibold">Select Plan <span class="text-danger">*</span></label>
                    <select name="plan_id" id="plan-selector" class="form-select" required
                            onchange="onPlanChange(this)">
                        <option value="">— Loading plans… —</option>
                    </select>
                    <div id="plan-preview" class="mt-2 small text-muted"></div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold">Start Date</label>
                    <input type="date" name="start_date" class="form-control"
                           value="<?= date('Y-m-d') ?>" required>
                    <div class="form-text" id="end-date-hint"></div>
                </div>
                <div class="form-check form-switch mb-2">
                    <input class="form-check-input" type="checkbox" name="generate_invoice"
                           value="1" id="gen-invoice-check" checked>
                    <label class="form-check-label" for="gen-invoice-check">
                        Generate Invoice automatically
                    </label>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <?= Html::submitButton('<i class="bi bi-check-lg"></i> Assign', ['class' => 'btn btn-primary']) ?>
            </div>
            <?php echo Html::endForm() ?>
        </div>
    </div>
</div>

<!-- ══════════════════════════════════════════════════════════
     Modal: Quick Payment
════════════════════════════════════════════════════════════ -->
<div class="modal fade" id="quickPayModal" tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title fw-semibold">Record Payment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="quick-pay-form" method="POST">
                <?= Html::hiddenInput(Yii::$app->request->csrfParam, Yii::$app->request->csrfToken) ?>
                <div class="modal-body">
                    <p class="text-muted small mb-3" id="qp-invoice-label"></p>
                    <div class="mb-3">
                        <label class="form-label">Amount (₹)</label>
                        <input type="number" name="amount" id="qp-amount" class="form-control"
                               min="0.01" step="0.01" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Method</label>
                        <select name="payment_method" class="form-select">
                            <option value="cash">Cash</option>
                            <option value="upi">UPI</option>
                            <option value="card">Card</option>
                            <option value="bank_transfer">Bank Transfer</option>
                            <option value="cheque">Cheque</option>
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Date</label>
                        <input type="date" name="payment_date" class="form-control"
                               value="<?= date('Y-m-d') ?>">
                    </div>
                    <div class="mb-2">
                        <label class="form-label">Reference No.</label>
                        <input type="text" name="reference_no" class="form-control"
                               placeholder="UTR / Cheque no.">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success btn-sm">
                        <i class="bi bi-check-lg"></i> Record Payment
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ── Load plans into assign-modal ──
let allPlans = [];

document.getElementById('assignPlanModal').addEventListener('show.bs.modal', () => {
    if (allPlans.length) return; // already loaded

    fetch('<?= Url::to(['/customer-plan/plans-json']) ?>')
        .then(r => r.json())
        .then(data => {
            allPlans = data;
            const sel = document.getElementById('plan-selector');
            sel.innerHTML = '<option value="">— Select a plan —</option>';
            data.forEach(p => {
                const opt = document.createElement('option');
                opt.value = p.id;
                opt.dataset.plan = JSON.stringify(p);
                opt.textContent = p.name + ' — ₹' + parseFloat(p.price).toLocaleString('en-IN');
                sel.appendChild(opt);
            });
        });
});

function onPlanChange(sel) {
    const opt = sel.options[sel.selectedIndex];
    if (!opt.value) {
        document.getElementById('plan-preview').innerHTML = '';
        document.getElementById('end-date-hint').textContent = '';
        return;
    }
    const plan = JSON.parse(opt.dataset.plan);
    document.getElementById('plan-preview').innerHTML =
        `<span class="badge bg-info text-dark">${plan.plan_type.replace('_','-')}</span> &nbsp;`
      + `<strong>₹${parseFloat(plan.price).toLocaleString('en-IN')}</strong>`
      + (plan.duration_months ? ` &nbsp;· ${plan.duration_months} months` : '');

    // Show calculated end date
    const startEl = document.querySelector('[name="start_date"]');
    if (plan.duration_months && startEl.value) {
        const start = new Date(startEl.value);
        start.setMonth(start.getMonth() + parseInt(plan.duration_months));
        document.getElementById('end-date-hint').textContent =
            'Plan ends on: ' + start.toLocaleDateString('en-IN', {day:'2-digit', month:'short', year:'numeric'});
    } else {
        document.getElementById('end-date-hint').textContent = plan.plan_type === 'one_time' ? 'One-time plan — no expiry.' : '';
    }
}

// Recalc end date when start date changes
document.querySelector('[name="start_date"]')?.addEventListener('change', () => {
    onPlanChange(document.getElementById('plan-selector'));
});

// ── Quick pay modal ──
function openQuickPay(invoiceId, invoiceNumber, outstanding) {
    document.getElementById('qp-invoice-label').textContent =
        `Invoice: ${invoiceNumber} — Outstanding: ₹${parseFloat(outstanding).toFixed(2)}`;
    document.getElementById('qp-amount').value   = parseFloat(outstanding).toFixed(2);
    document.getElementById('qp-amount').max     = outstanding;
    document.getElementById('quick-pay-form').action =
        '<?= Url::base(true) ?>/invoice/pay/' + invoiceId;
    new bootstrap.Modal(document.getElementById('quickPayModal')).show();
}
</script>
