<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$messages = array();
$errors = array();
if (!$pdo) {
    $customer = null;
} else {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
            $errors[] = 'Invalid security token.';
        } else {
            $action = isset($_POST['action']) ? (string) $_POST['action'] : '';
            try {
                if ($action === 'verify_email') {
                    $stmt = $pdo->prepare('UPDATE customers SET email_verified_at = COALESCE(email_verified_at, NOW()), email_verification_token_hash = NULL, email_verification_expires_at = NULL, updated_at = NOW() WHERE id = ?');
                    $stmt->execute(array($id));
                    $messages[] = 'Customer email marked as verified.';
                } elseif ($action === 'status') {
                    $status = in_array(isset($_POST['status']) ? $_POST['status'] : '', array('active','disabled'), true) ? $_POST['status'] : 'active';
                    $stmt = $pdo->prepare('UPDATE customers SET status = ?, updated_at = NOW() WHERE id = ?');
                    $stmt->execute(array($status, $id));
                    $messages[] = 'Customer status updated.';
                }
            } catch (Exception $e) { $errors[] = 'Update failed.'; }
        }
    }
    $stmt = $pdo->prepare('SELECT * FROM customers WHERE id = ? LIMIT 1');
    $stmt->execute(array($id));
    $customer = $stmt->fetch();
}
$title = $customer ? 'Customer: ' . $customer['full_name'] : 'Customer';
$orders = $reups = $customs = array();
if ($pdo && $customer) {
    try {
        $stmt = $pdo->prepare('SELECT id, order_number, total, payment_status, status, created_at FROM orders WHERE customer_id = ? OR customer_email = ? ORDER BY created_at DESC LIMIT 20');
        $stmt->execute(array($id, $customer['email']));
        $orders = $stmt->fetchAll();
        $stmt = $pdo->prepare('SELECT id, request_number, estimate_low, estimate_high, final_quote, status, created_at FROM reup_requests WHERE customer_id = ? OR customer_email = ? ORDER BY created_at DESC LIMIT 20');
        $stmt->execute(array($id, $customer['email']));
        $reups = $stmt->fetchAll();
        $stmt = $pdo->prepare('SELECT id, request_number, sofa_type, estimate_low, estimate_high, final_quote, status, created_at FROM custom_sofa_quotes WHERE customer_id = ? OR customer_email = ? ORDER BY created_at DESC LIMIT 20');
        $stmt->execute(array($id, $customer['email']));
        $customs = $stmt->fetchAll();
    } catch (Exception $e) {}
}
require __DIR__ . '/_header.php';
?>
<?php foreach ($messages as $msg): ?><div class="alert alert-success"><?= e($msg) ?></div><?php endforeach; ?>
<?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>
<?php if (!$pdo): ?>
<div class="admin-card p-4"><h1 class="h4">MySQL setup required</h1></div>
<?php elseif (!$customer): ?>
<div class="admin-card p-4"><h1 class="h4">Customer not found</h1><a href="customers.php" class="btn btn-outline-primary">Back</a></div>
<?php else: ?>
<div class="row g-4">
    <div class="col-lg-4"><div class="admin-card p-4"><h1 class="h4"><?= e($customer['full_name']) ?></h1><p class="admin-muted mb-1"><?= e($customer['email']) ?></p><p class="mb-1"><?= e($customer['phone']) ?></p><p class="mb-3"><?= e($customer['address']) ?> <?= e($customer['city']) ?></p><div class="mb-3"><?= !empty($customer['email_verified_at']) ? '<span class="badge text-bg-success">Email verified</span>' : '<span class="badge text-bg-warning">Email not verified</span>' ?></div><form method="post" class="mb-3"><input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="verify_email"><button class="btn btn-outline-primary" type="submit" <?= !empty($customer['email_verified_at']) ? 'disabled' : '' ?>>Mark Email Verified</button></form><form method="post"><input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="status"><label class="form-label">Account status</label><select class="form-select mb-2" name="status"><option value="active" <?= $customer['status']==='active'?'selected':'' ?>>Active</option><option value="disabled" <?= $customer['status']==='disabled'?'selected':'' ?>>Disabled</option></select><button class="btn btn-primary" type="submit">Save Status</button></form></div></div>
    <div class="col-lg-8"><div class="admin-card p-4 mb-4"><h2 class="h5">Orders</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Order</th><th>Total</th><th>Payment</th><th>Status</th></tr></thead><tbody><?php foreach ($orders as $row): ?><tr><td><a href="order-view.php?id=<?= (int)$row['id'] ?>"><?= e($row['order_number']) ?></a></td><td><?= money($row['total']) ?></td><td><?= e($row['payment_status']) ?></td><td><?= e($row['status']) ?></td></tr><?php endforeach; ?><?php if (!$orders): ?><tr><td colspan="4" class="text-center admin-muted py-4">No orders.</td></tr><?php endif; ?></tbody></table></div></div><div class="admin-card p-4 mb-4"><h2 class="h5">Custom Sofa Quotes</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Request</th><th>Sofa</th><th>Quote</th><th>Status</th></tr></thead><tbody><?php foreach ($customs as $row): ?><tr><td><a href="custom-quote-view.php?id=<?= (int)$row['id'] ?>"><?= e($row['request_number']) ?></a></td><td><?= e($row['sofa_type']) ?></td><td><?= $row['final_quote']!==null ? money($row['final_quote']) : money($row['estimate_low']).' - '.money($row['estimate_high']) ?></td><td><?= e($row['status']) ?></td></tr><?php endforeach; ?><?php if (!$customs): ?><tr><td colspan="4" class="text-center admin-muted py-4">No custom quotes.</td></tr><?php endif; ?></tbody></table></div></div><div class="admin-card p-4"><h2 class="h5">Re-Up Requests</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><th>Request</th><th>Quote</th><th>Status</th></tr></thead><tbody><?php foreach ($reups as $row): ?><tr><td><a href="reup-view.php?id=<?= (int)$row['id'] ?>"><?= e($row['request_number']) ?></a></td><td><?= $row['final_quote']!==null ? money($row['final_quote']) : money($row['estimate_low']).' - '.money($row['estimate_high']) ?></td><td><?= e($row['status']) ?></td></tr><?php endforeach; ?><?php if (!$reups): ?><tr><td colspan="3" class="text-center admin-muted py-4">No Re-Up requests.</td></tr><?php endif; ?></tbody></table></div></div></div>
</div>
<?php endif; ?>
<?php require __DIR__ . '/_footer.php'; ?>
