<?php
$pageTitle = $driverId ? 'My Fuel Allowance' : 'Fuel Allocation';
$isManager = can('fuel.manage');
?>
<div class="page-heading fuel-heading">
    <div>
        <p class="eyebrow">Fuel Control</p>
        <h1><?= $driverId ? 'My Fuel Allowance' : 'Fuel Allocation & Allowance' ?></h1>
        <p><?= $driverId ? 'View your available fuel balance and submit purchases with receipts.' : 'Plan fuel per load, issue allowances or advances, review purchases, and reconcile actual spend.' ?></p>
    </div>
    <div class="page-actions"><?php if (can('ai.use')): ?><a class="btn btn-light" href="<?= url('/ai#fuel-planner') ?>">AI Fuel Review</a><?php endif; ?><?php if ($isManager): ?><button class="btn btn-primary" type="button" data-panel-toggle="fuel-allocation-form">New Allocation</button><?php endif; ?></div>
</div>

<div class="stats-grid fuel-stats">
    <article class="stat-card"><span>Allocated</span><strong><?= money($summary['allocated'] ?? 0) ?></strong><small>Active allowances</small></article>
    <article class="stat-card"><span>Used</span><strong><?= money($summary['spent'] ?? 0) ?></strong><small>Approved fuel purchases</small></article>
    <article class="stat-card"><span>Remaining</span><strong><?= money($summary['remaining'] ?? 0) ?></strong><small>Available balance</small></article>
    <article class="stat-card"><span>Awaiting Issue</span><strong><?= (int) ($summary['pending_count'] ?? 0) ?></strong><small>Draft or approved</small></article>
</div>

<?php if ($isManager): ?>
<section class="panel fuel-form-panel" id="fuel-allocation-form" data-collapsible-panel hidden>
    <div class="panel-header"><div><h2>Create Fuel Allocation</h2><p>Use load miles, expected MPG, fuel price, and reserve to calculate a recommended allowance.</p></div><button class="btn btn-light btn-sm" type="button" data-panel-close>Close</button></div>
    <form method="post" action="<?= url('/fuel/allocations/store') ?>" class="form-stack" data-fuel-allocation-form>
        <?= csrf_field() ?>
        <div class="form-grid three">
            <label><span>Load</span><select name="load_id" data-fuel-load><option value="">Optional</option><?php foreach($loads as $load): ?><option value="<?= e((string)$load['id']) ?>" data-miles="<?= e((string)$load['miles']) ?>" data-driver="<?= e((string)$load['driver_id']) ?>" data-truck="<?= e((string)$load['truck_id']) ?>" data-carrier="<?= e((string)$load['carrier_id']) ?>"><?= e($load['load_number']) ?><?= $load['driver_name'] ? ' · '.e($load['driver_name']) : '' ?></option><?php endforeach; ?></select></label>
            <label><span>Carrier</span><select name="carrier_id" data-fuel-carrier><option value="">Optional</option><?php foreach($carriers as $carrier): ?><option value="<?= e((string)$carrier['id']) ?>"><?= e($carrier['company_name']) ?></option><?php endforeach; ?></select></label>
            <label><span>Driver</span><select name="driver_id" data-fuel-driver><option value="">Select driver</option><?php foreach($drivers as $driver): ?><option value="<?= e((string)$driver['id']) ?>"><?= e($driver['name']) ?></option><?php endforeach; ?></select></label>
            <label><span>Truck</span><select name="truck_id" data-fuel-truck><option value="">Optional</option><?php foreach($trucks as $truck): ?><option value="<?= e((string)$truck['id']) ?>"><?= e($truck['unit_number']) ?></option><?php endforeach; ?></select></label>
            <label><span>Funding Method</span><select name="allocation_method"><option value="fuel_card">Fuel Card</option><option value="cash_advance">Cash Advance</option><option value="company_card">Company Card</option><option value="reimbursement">Reimbursement Limit</option></select></label>
            <label><span>Funding Account</span><select name="bank_account_id"><option value="">Optional</option><?php foreach($accounts as $account): ?><option value="<?= e((string)$account['id']) ?>"><?= e($account['account_name']) ?> · <?= e(readable_status($account['account_type'])) ?></option><?php endforeach; ?></select></label>
            <label><span>Planned Miles</span><input type="number" step="0.1" min="0" name="planned_miles" value="0" data-fuel-miles></label>
            <label><span>Target MPG</span><input type="number" step="0.1" min="0.1" name="target_mpg" value="6.5" data-fuel-mpg></label>
            <label><span>Expected Fuel Price / Gallon</span><input type="number" step="0.01" min="0" name="expected_price_per_gallon" value="0" data-fuel-price></label>
            <label><span>Reserve %</span><input type="number" step="0.1" min="0" name="reserve_percent" value="10" data-fuel-reserve></label>
            <label><span>Recommended Gallons</span><input type="text" value="0.00" readonly data-fuel-gallons></label>
            <label><span>Recommended Amount</span><input type="text" value="<?= money(0) ?>" readonly data-fuel-recommended></label>
            <label><span>Allocated Amount</span><input type="number" step="0.01" min="0" name="allocated_amount" placeholder="Leave zero to use recommendation" data-fuel-allocated></label>
            <label><span>Valid From</span><input type="date" name="valid_from" value="<?= date('Y-m-d') ?>"></label>
            <label><span>Valid Until</span><input type="date" name="valid_until"></label>
            <label><span>Initial Status</span><select name="status"><option value="draft">Draft</option><option value="approved">Approved</option><option value="issued">Issued</option></select></label>
        </div>
        <label><span>Instructions / Limits</span><textarea name="notes" rows="3" placeholder="Approved stations, route restrictions, maximum gallons, emergency reserve…"></textarea></label>
        <div class="fuel-calculation-note"><strong>Calculation:</strong> planned miles ÷ target MPG × expected price, plus reserve.</div>
        <div class="form-actions"><button class="btn btn-primary">Create Allocation</button></div>
    </form>
</section>
<?php endif; ?>

<div class="content-grid fuel-layout">
    <section class="panel">
        <div class="panel-header"><div><h2>Fuel Allocations</h2><p>Allowance balance by load, driver, and truck.</p></div><form class="compact-filter" method="get"><select name="status" onchange="this.form.submit()"><option value="">All statuses</option><?php foreach(['draft','approved','issued','partially_used','used','closed','cancelled'] as $s): ?><option value="<?= e($s) ?>" <?= $status===$s?'selected':'' ?>><?= e(readable_status($s)) ?></option><?php endforeach; ?></select></form></div>
        <div class="fuel-card-list">
        <?php foreach($allocations as $allocation): ?>
            <article class="fuel-allocation-card">
                <div class="fuel-card-top">
                    <div><span class="fuel-id"><?= e($allocation['allocation_number']) ?></span><h3><?= e($allocation['driver_name'] ?: $allocation['carrier_name'] ?: 'Unassigned') ?></h3><p><?= e($allocation['load_number'] ? 'Load '.$allocation['load_number'] : 'General allowance') ?><?= $allocation['unit_number'] ? ' · Truck '.e($allocation['unit_number']) : '' ?></p></div>
                    <span class="badge badge-<?= status_class($allocation['status']) ?>"><?= e(readable_status($allocation['status'])) ?></span>
                </div>
                <?php $pct = (float)$allocation['allocated_amount'] > 0 ? min(100, max(0, ((float)$allocation['spent_amount']/(float)$allocation['allocated_amount'])*100)) : 0; ?>
                <div class="fuel-progress"><span style="width:<?= number_format($pct,1,'.','') ?>%"></span></div>
                <div class="fuel-money-grid"><div><small>Allocated</small><strong><?= money($allocation['allocated_amount']) ?></strong></div><div><small>Used</small><strong><?= money($allocation['spent_amount']) ?></strong></div><div><small>Remaining</small><strong class="<?= (float)$allocation['remaining_amount'] < 0 ? 'text-danger':'' ?>"><?= money($allocation['remaining_amount']) ?></strong></div></div>
                <div class="fuel-meta"><span><?= e(readable_status($allocation['allocation_method'])) ?></span><span><?= number_format((float)$allocation['recommended_gallons'],1) ?> gal planned</span><span><?= date_display($allocation['valid_until'], 'No expiry') ?></span></div>
                <?php if(in_array($allocation['status'], ['approved','issued','partially_used'], true)): ?>
                <details class="fuel-purchase-form">
                    <summary>Submit Fuel Purchase</summary>
                    <form method="post" action="<?= url('/fuel/transactions/store') ?>" enctype="multipart/form-data" class="form-stack" data-location-form>
                        <?= csrf_field() ?><input type="hidden" name="allocation_id" value="<?= e((string)$allocation['id']) ?>"><input type="hidden" name="latitude" data-latitude><input type="hidden" name="longitude" data-longitude>
                        <div class="form-grid three"><label><span>Date</span><input type="date" name="transaction_date" value="<?= date('Y-m-d') ?>" required></label><label><span>Merchant / Station</span><input name="merchant" placeholder="Truck stop or station"></label><label><span>City / State</span><input name="city_state"></label><label><span>Gallons</span><input type="number" step="0.001" min="0" name="gallons" data-purchase-gallons></label><label><span>Price / Gallon</span><input type="number" step="0.001" min="0" name="price_per_gallon" data-purchase-price></label><label><span>Total Amount</span><input type="number" step="0.01" min="0" name="amount" data-purchase-amount required></label><label><span>Odometer</span><input type="number" min="0" name="odometer"></label><label><span>Receipt</span><input type="file" name="receipt" accept="image/*,application/pdf" capture="environment"></label><label><span>Location</span><input name="location_address" data-location-address></label></div>
                        <label><span>Notes</span><textarea name="notes" rows="2"></textarea></label><button class="btn btn-primary">Submit Purchase</button>
                    </form>
                </details>
                <?php endif; ?>
                <?php if($isManager): ?><form method="post" action="<?= url('/fuel/allocations/status') ?>" class="inline-form fuel-status-form"><?= csrf_field() ?><input type="hidden" name="id" value="<?= e((string)$allocation['id']) ?>"><select name="status"><?php foreach(['draft','approved','issued','closed','cancelled'] as $s): ?><option value="<?= e($s) ?>" <?= $allocation['status']===$s?'selected':'' ?>><?= e(readable_status($s)) ?></option><?php endforeach; ?></select><button class="btn btn-light btn-sm">Update</button></form><?php endif; ?>
            </article>
        <?php endforeach; ?>
        <?php if(!$allocations): ?><p class="empty">No fuel allocations found.</p><?php endif; ?>
        </div>
    </section>

    <section class="panel fuel-transactions-panel">
        <div class="panel-header"><div><h2>Recent Fuel Purchases</h2><p>Receipts and approval status.</p></div></div>
        <div class="fuel-transaction-list">
        <?php foreach(array_slice($transactions,0,80) as $transaction): ?>
            <article class="fuel-transaction-card">
                <div><strong><?= e($transaction['merchant'] ?: $transaction['transaction_number']) ?></strong><span><?= e(date_display($transaction['transaction_date'])) ?> · <?= e($transaction['driver_name'] ?: '-') ?></span><small><?= e($transaction['load_number'] ? 'Load '.$transaction['load_number'] : $transaction['allocation_number']) ?><?= $transaction['gallons'] ? ' · '.number_format((float)$transaction['gallons'],2).' gal' : '' ?></small></div>
                <div class="fuel-transaction-right"><strong><?= money($transaction['amount']) ?></strong><span class="badge badge-<?= status_class($transaction['status']) ?>"><?= e(readable_status($transaction['status'])) ?></span><?php if($transaction['receipt_document_id']): ?><a class="text-link" href="<?= url('/documents/download?id='.(int)$transaction['receipt_document_id']) ?>">Receipt</a><?php endif; ?></div>
                <?php if($isManager): ?><form method="post" action="<?= url('/fuel/transactions/status') ?>" class="inline-form fuel-review-form"><?= csrf_field() ?><input type="hidden" name="id" value="<?= e((string)$transaction['id']) ?>"><select name="status"><option value="submitted" <?= $transaction['status']==='submitted'?'selected':'' ?>>Submitted</option><option value="approved" <?= $transaction['status']==='approved'?'selected':'' ?>>Approve & post</option><option value="rejected" <?= $transaction['status']==='rejected'?'selected':'' ?>>Reject</option></select><button class="btn btn-light btn-sm">Save</button></form><?php endif; ?>
            </article>
        <?php endforeach; ?>
        <?php if(!$transactions): ?><p class="empty">No fuel purchases submitted yet.</p><?php endif; ?>
        </div>
    </section>
</div>
