<?php $pageTitle = 'Create Settlement'; ?>
<div class="panel form-panel">
    <div class="panel-header"><div><p class="eyebrow">Accounting</p><h2>Create Driver Settlement</h2><p class="muted">Calculate driver pay from load rate, miles, or fixed driver rate.</p></div></div>

    <?php if ($loads): ?>
        <div class="quick-links">
            <strong>Ready loads:</strong>
            <?php foreach (array_slice($loads, 0, 5) as $load): ?>
                <a href="<?= url('/settlements/create?load_id=' . $load['id']) ?>"><?= e($load['load_number']) ?></a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="post" action="<?= url('/settlements/store') ?>" class="form-grid">
        <?= csrf_field() ?>
        <label><span>Settlement Number</span><input name="settlement_number" value="<?= e(old('settlement_number', $nextNumber)) ?>"></label>
        <label><span>Status</span><select name="status"><option value="pending">Pending</option><option value="paid">Paid</option></select></label>
        <label>
            <span>Driver *</span>
            <select name="driver_id" required>
                <option value="">Select driver</option>
                <?php foreach ($drivers as $driver): ?>
                    <option value="<?= e((string) $driver['id']) ?>" <?= (string) old('driver_id', $calculatedLoad['driver_id'] ?? '') === (string) $driver['id'] ? 'selected' : '' ?>><?= e($driver['name']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label>
            <span>Load</span>
            <select name="load_id">
                <option value="">No load selected</option>
                <?php foreach ($loads as $load): ?>
                    <option value="<?= e((string) $load['id']) ?>" <?= (string) old('load_id', $calculatedLoad['id'] ?? '') === (string) $load['id'] ? 'selected' : '' ?>><?= e($load['load_number']) ?> — <?= e($load['driver_name']) ?></option>
                <?php endforeach; ?>
            </select>
        </label>
        <label><span>Gross Amount *</span><input type="number" step="0.01" name="gross_amount" value="<?= e(old('gross_amount', $calculatedLoad['calculated_gross'] ?? '0')) ?>" required></label>
        <label><span>Deductions</span><input type="number" step="0.01" name="deductions" value="<?= e(old('deductions', '0')) ?>"></label>
        <label class="span-2"><span>Notes</span><textarea name="notes" rows="4"><?= e(old('notes')) ?></textarea></label>
        <div class="form-actions span-2"><button class="btn btn-primary" type="submit">Save Settlement</button><a class="btn btn-light" href="<?= url('/settlements') ?>">Cancel</a></div>
    </form>
</div>
