<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$title = 'View Re-Up Request';

if (!$pdo) {
    admin_redirect('reup.php');
}

$id = (int) (isset($_GET['id']) ? $_GET['id'] : 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $newStatus = clean_text((string) (isset($_POST['status']) ? $_POST['status'] : ''), 80);
        $finalQuote = trim((string) (isset($_POST['final_quote']) ? $_POST['final_quote'] : ''));
        $adminNotes = clean_text((string) (isset($_POST['admin_notes']) ? $_POST['admin_notes'] : ''), 1000);
        $finalQuoteValue = ($finalQuote === '') ? null : (float) $finalQuote;
        if ($newStatus !== '') {
            $stmt = $pdo->prepare('UPDATE reup_requests SET status = ?, final_quote = ?, admin_notes = ? WHERE id = ?');
            $stmt->execute(array($newStatus, $finalQuoteValue, $adminNotes, $id));
        }
    }
    admin_redirect('reup-view.php?id=' . $id);
}

$stmt = $pdo->prepare('SELECT * FROM reup_requests WHERE id = ? LIMIT 1');
$stmt->execute(array($id));
$request = $stmt->fetch();
if (!$request) {
    admin_redirect('reup.php');
}

$serviceOptions = reup_service_options();
$conditionOptions = reup_condition_options();
$issueOptions = reup_issue_options();
$issues = decode_json_array(isset($request['issue_json']) ? $request['issue_json'] : '[]');
$statusOptions = array('For review', 'Need more photos', 'Quoted', 'Confirmed', 'For pickup', 'In progress', 'Ready for delivery', 'Completed', 'Cancelled');

require __DIR__ . '/_header.php';
?>
<div class="row g-4">
    <div class="col-lg-8">
        <div class="admin-card p-4 mb-4">
            <div class="d-flex justify-content-between align-items-start mb-4">
                <div>
                    <p class="eyebrow mb-1">Re-Up reference</p>
                    <h1 class="h3 mb-1"><?= e($request['request_number']) ?></h1>
                    <p class="admin-muted mb-0"><?= e(date('M d, Y h:i A', strtotime($request['created_at']))) ?></p>
                </div>
                <span class="badge badge-soft fs-6"><?= e($request['status']) ?></span>
            </div>
            <?php if ($request['photo_path']): ?>
                <div class="reup-admin-photo mb-4">
                    <img src="../<?= e($request['photo_path']) ?>" alt="Uploaded sofa photo">
                </div>
            <?php endif; ?>
            <div class="row g-3">
                <div class="col-md-6"><div class="p-3 border rounded-4"><span class="admin-muted">Service</span><br><strong><?= e(isset($serviceOptions[$request['service_type']]) ? $serviceOptions[$request['service_type']] : $request['service_type']) ?></strong></div></div>
                <div class="col-md-6"><div class="p-3 border rounded-4"><span class="admin-muted">Condition</span><br><strong><?= e(isset($conditionOptions[$request['condition_level']]) ? $conditionOptions[$request['condition_level']] : $request['condition_level']) ?></strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Width</span><br><strong><?= e(number_format((float) $request['width_cm'], 0)) ?> cm</strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Depth</span><br><strong><?= e(number_format((float) $request['depth_cm'], 0)) ?> cm</strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Height</span><br><strong><?= e(number_format((float) $request['height_cm'], 0)) ?> cm</strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Seats</span><br><strong><?= (int) $request['seat_count'] ?></strong></div></div>
                <div class="col-md-8"><div class="p-3 border rounded-4"><span class="admin-muted">Fabric preference</span><br><strong><?= e($request['fabric_preference'] ? $request['fabric_preference'] : 'Not specified') ?></strong></div></div>
            </div>
            <hr>
            <h2 class="h5">Issues</h2>
            <div class="badge-row mb-3">
                <?php foreach ($issues as $issue): ?>
                    <span><?= e(isset($issueOptions[$issue]) ? $issueOptions[$issue] : $issue) ?></span>
                <?php endforeach; ?>
                <?php if (!$issues): ?><span>No issue selected</span><?php endif; ?>
            </div>
            <?php if ($request['message']): ?>
                <h2 class="h5">Customer notes</h2>
                <p><?= nl2br(e($request['message'])) ?></p>
            <?php endif; ?>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="admin-card p-4 mb-4">
            <h2 class="h5">Customer</h2>
            <dl class="mb-0">
                <dt>Name</dt><dd><?= e($request['customer_name']) ?></dd>
                <dt>Phone</dt><dd><a href="tel:<?= e(preg_replace('/[^+0-9]/', '', $request['customer_phone'])) ?>"><?= e($request['customer_phone']) ?></a></dd>
                <?php if ($request['customer_email']): ?><dt>Email</dt><dd><a href="mailto:<?= e($request['customer_email']) ?>"><?= e($request['customer_email']) ?></a></dd><?php endif; ?>
                <dt>City</dt><dd><?= e($request['customer_city']) ?></dd>
                <?php if ($request['customer_address']): ?><dt>Address</dt><dd><?= e($request['customer_address']) ?></dd><?php endif; ?>
            </dl>
        </div>
        <div class="admin-card p-4 mb-4">
            <h2 class="h5">Estimate</h2>
            <p class="display-6 mb-1"><?= money($request['estimate_low']) ?></p>
            <p class="admin-muted">to <?= money($request['estimate_high']) ?></p>
            <?php if ($request['final_quote'] !== null && $request['final_quote'] !== ''): ?>
                <hr><span class="admin-muted">Final quote</span><h3><?= money($request['final_quote']) ?></h3>
            <?php endif; ?>
        </div>
        <div class="admin-card p-4">
            <h2 class="h5">Update quotation</h2>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                <label class="form-label">Status</label>
                <select class="form-select mb-3" name="status">
                    <?php foreach ($statusOptions as $option): ?>
                        <option value="<?= e($option) ?>" <?= $request['status'] === $option ? 'selected' : '' ?>><?= e($option) ?></option>
                    <?php endforeach; ?>
                </select>
                <label class="form-label">Final quote</label>
                <input class="form-control mb-3" type="number" step="0.01" min="0" name="final_quote" value="<?= e($request['final_quote']) ?>" placeholder="Example: 12500">
                <label class="form-label">Admin notes</label>
                <textarea class="form-control mb-3" name="admin_notes" rows="4" placeholder="Internal notes, material, pickup plan, etc."><?= e($request['admin_notes']) ?></textarea>
                <button class="btn btn-primary w-100" type="submit">Save Re-Up Status</button>
            </form>
        </div>
    </div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
