<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$title = 'View Custom Sofa Quote';

if (!$pdo) {
    admin_redirect('custom-quotes.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'] : ''), 1200);
        $finalQuoteValue = ($finalQuote === '') ? null : (float) $finalQuote;
        if ($newStatus !== '') {
            $stmt = $pdo->prepare('UPDATE custom_sofa_quotes SET status = ?, final_quote = ?, admin_notes = ? WHERE id = ?');
            $stmt->execute(array($newStatus, $finalQuoteValue, $adminNotes, $id));
        }
    }
    admin_redirect('custom-quote-view.php?id=' . $id);
}

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

$typeOptions = custom_sofa_type_options();
$styleOptions = custom_style_options();
$materialOptions = custom_material_options();
$firmnessOptions = custom_firmness_options();
$featureOptions = custom_feature_options();
$features = decode_json_array(isset($request['feature_json']) ? $request['feature_json'] : '[]');
$statusOptions = array('For design review', 'Need more details', 'Need room measurement', 'Quoted', 'Confirmed', 'Production pending', 'In production', '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">Custom sofa 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>

            <div class="row g-3 mb-4">
                <?php if ($request['inspiration_photo_path']): ?>
                    <div class="col-md-6"><div class="reup-admin-photo"><img src="../<?= e($request['inspiration_photo_path']) ?>" alt="Inspiration photo"></div><p class="small admin-muted mt-2">Inspiration photo</p></div>
                <?php endif; ?>
                <?php if ($request['room_photo_path']): ?>
                    <div class="col-md-6"><div class="reup-admin-photo"><img src="../<?= e($request['room_photo_path']) ?>" alt="Room photo"></div><p class="small admin-muted mt-2">Room / space photo</p></div>
                <?php endif; ?>
            </div>

            <div class="row g-3">
                <div class="col-md-6"><div class="p-3 border rounded-4"><span class="admin-muted">Sofa type</span><br><strong><?= e(isset($typeOptions[$request['sofa_type']]) ? $typeOptions[$request['sofa_type']] : $request['sofa_type']) ?></strong></div></div>
                <div class="col-md-6"><div class="p-3 border rounded-4"><span class="admin-muted">Design style</span><br><strong><?= e(isset($styleOptions[$request['design_style']]) ? $styleOptions[$request['design_style']] : $request['design_style']) ?></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-4"><div class="p-3 border rounded-4"><span class="admin-muted">Material</span><br><strong><?= e(isset($materialOptions[$request['material_preference']]) ? $materialOptions[$request['material_preference']] : $request['material_preference']) ?></strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Firmness</span><br><strong><?= e(isset($firmnessOptions[$request['firmness']]) ? $firmnessOptions[$request['firmness']] : $request['firmness']) ?></strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Color</span><br><strong><?= e($request['color_preference'] ? $request['color_preference'] : 'Not specified') ?></strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Chaise side</span><br><strong><?= e($request['chaise_side'] ? $request['chaise_side'] : 'Not specified') ?></strong></div></div>
                <div class="col-md-4"><div class="p-3 border rounded-4"><span class="admin-muted">Timeline</span><br><strong><?= e($request['timeline'] ? $request['timeline'] : 'Not specified') ?></strong></div></div>
            </div>
            <hr>
            <h2 class="h5">Special features</h2>
            <div class="badge-row mb-3">
                <?php foreach ($features as $feature): ?>
                    <span><?= e(isset($featureOptions[$feature]) ? $featureOptions[$feature] : $feature) ?></span>
                <?php endforeach; ?>
                <?php if (!$features): ?><span>No special feature selected</span><?php endif; ?>
            </div>
            <?php if ($request['message']): ?>
                <h2 class="h5">Customer design 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; ?>
                <?php if ($request['budget_range']): ?><dt>Budget</dt><dd><?= e($request['budget_range']) ?></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: 45000">
                <label class="form-label">Admin notes</label>
                <textarea class="form-control mb-3" name="admin_notes" rows="4" placeholder="Internal notes, fabric, final dimensions, drawing status, production plan, etc."><?= e($request['admin_notes']) ?></textarea>
                <button class="btn btn-primary w-100" type="submit">Save Custom Quote Status</button>
            </form>
        </div>
    </div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
