<?php
/**
 * @var object $customer
 * @var object $stats
 * @var array $visits
 * @var array $invoices
 * @var array $photos
 * @var array $notes
 * @var object|null $membership
 * @var int $loyaltyPoints
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-user-circle me-2 text-gold"></i><?= e($customer->first_name . ' ' . $customer->last_name) ?></h5>
</div>

<div class="row g-4 mb-4">
    <div class="col-lg-4">
        <div class="glass-card text-center">
            <div class="card-body py-4">
                <?php if (!empty($customer->photo)): ?>
                    <img src="<?= uploadUrl($customer->photo) ?>" alt="" class="rounded-circle mb-3" 
                         width="120" height="120" style="object-fit:cover;border:3px solid var(--gold);">
                <?php else: ?>
                    <div class="rounded-circle d-inline-flex align-items-center justify-content-center mb-3" 
                         style="width:120px;height:120px;background:var(--gold);color:#000;font-size:48px;font-weight:600;">
                        <?= strtoupper(substr($customer->first_name ?? '?', 0, 1) . substr($customer->last_name ?? '', 0, 1)) ?>
                    </div>
                <?php endif; ?>
                <h5 class="mb-1"><?= e($customer->first_name . ' ' . $customer->last_name) ?></h5>
                <p class="text-muted small mb-2"><?= e($customer->email ?? '') ?></p>
                <span class="badge bg-<?= statusBadge($customer->status ?? 'active') ?> mb-3">
                    <?= e(ucfirst($customer->status ?? 'active')) ?>
                </span>
                <div class="d-flex justify-content-center gap-3 mt-2">
                    <?php if (can('customers_edit')): ?>
                        <a href="<?= url('customers/edit/' . $customer->id) ?>" class="btn btn-sm btn-outline-gold">
                            <i class="fas fa-edit me-1"></i>Edit
                        </a>
                    <?php endif; ?>
                    <?php if (can('appointments_create')): ?>
                        <a href="<?= url('appointments/create?customer_id=' . $customer->id) ?>" class="btn btn-sm btn-gold">
                            <i class="fas fa-calendar-plus me-1"></i>Book
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-8">
        <div class="row g-3">
            <div class="col-md-3 col-6">
                <div class="glass-card text-center py-3">
                    <div class="fs-3 text-gold fw-bold"><?= $stats->total_visits ?></div>
                    <div class="small text-muted">Total Visits</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="glass-card text-center py-3">
                    <div class="fs-3 text-gold fw-bold"><?= currency($stats->total_spent) ?></div>
                    <div class="small text-muted">Total Spent</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="glass-card text-center py-3">
                    <div class="fs-3 text-gold fw-bold"><?= $loyaltyPoints ?></div>
                    <div class="small text-muted">Loyalty Points</div>
                </div>
            </div>
            <div class="col-md-3 col-6">
                <div class="glass-card text-center py-3">
                    <div class="fs-3 text-gold fw-bold"><?= $stats->last_visit_date ?? '-' ?></div>
                    <div class="small text-muted">Last Visit</div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="glass-card p-0">
    <div class="card-header">
        <ul class="nav nav-tabs card-header-tabs" id="customerTabs" role="tablist">
            <li class="nav-item" role="presentation">
                <button class="nav-link active" id="overview-tab" data-bs-toggle="tab" data-bs-target="#overview" 
                        type="button" role="tab" aria-selected="true">
                    <i class="fas fa-info-circle me-1"></i>Overview
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" 
                        type="button" role="tab" aria-selected="false">
                    <i class="fas fa-history me-1"></i>Visit History
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="invoices-tab" data-bs-toggle="tab" data-bs-target="#invoices" 
                        type="button" role="tab" aria-selected="false">
                    <i class="fas fa-file-invoice me-1"></i>Invoices
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="photos-tab" data-bs-toggle="tab" data-bs-target="#photos" 
                        type="button" role="tab" aria-selected="false">
                    <i class="fas fa-images me-1"></i>Photos
                </button>
            </li>
            <li class="nav-item" role="presentation">
                <button class="nav-link" id="notes-tab" data-bs-toggle="tab" data-bs-target="#notes" 
                        type="button" role="tab" aria-selected="false">
                    <i class="fas fa-sticky-note me-1"></i>Notes
                </button>
            </li>
        </ul>
    </div>
    <div class="card-body">
        <div class="tab-content" id="customerTabsContent">

            <!-- Overview Tab -->
            <div class="tab-pane fade show active" id="overview" role="tabpanel" aria-labelledby="overview-tab">
                <div class="row g-4">
                    <div class="col-md-6">
                        <h6 class="text-gold mb-3"><i class="fas fa-address-card me-2"></i>Personal Information</h6>
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td class="text-muted" width="140">First Name</td>
                                <td><?= e($customer->first_name) ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Last Name</td>
                                <td><?= e($customer->last_name) ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Email</td>
                                <td><?= e($customer->email ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Phone</td>
                                <td><?= e($customer->phone ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Mobile</td>
                                <td><?= e($customer->mobile ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Date of Birth</td>
                                <td><?= !empty($customer->date_of_birth) ? formatDate($customer->date_of_birth) : '-' ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Gender</td>
                                <td><?= e(ucfirst($customer->gender ?? '-')) ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">Source</td>
                                <td><?= e(ucwords(str_replace('_', ' ', $customer->source ?? '-'))) ?></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <h6 class="text-gold mb-3"><i class="fas fa-map-marker-alt me-2"></i>Address</h6>
                        <table class="table table-sm table-borderless">
                            <tr>
                                <td class="text-muted" width="140">Address</td>
                                <td><?= nl2br(e($customer->address ?? '-')) ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">City</td>
                                <td><?= e($customer->city ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">State</td>
                                <td><?= e($customer->state ?? '-') ?></td>
                            </tr>
                            <tr>
                                <td class="text-muted">ZIP Code</td>
                                <td><?= e($customer->zip ?? '-') ?></td>
                            </tr>
                        </table>

                        <?php if ($membership): ?>
                            <h6 class="text-gold mb-3 mt-4"><i class="fas fa-crown me-2"></i>Membership</h6>
                            <table class="table table-sm table-borderless">
                                <tr>
                                    <td class="text-muted" width="140">Plan</td>
                                    <td><?= e($membership->plan_name ?? 'N/A') ?></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Status</td>
                                    <td><span class="badge bg-success">Active</span></td>
                                </tr>
                                <tr>
                                    <td class="text-muted">Points</td>
                                    <td><?= $loyaltyPoints ?> pts</td>
                                </tr>
                            </table>
                        <?php endif; ?>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <h6 class="text-gold mb-3"><i class="fas fa-notes-medical me-2"></i>Health Notes</h6>
                        <div class="row">
                            <div class="col-md-6">
                                <label class="text-muted small">Allergies</label>
                                <p class="mb-3"><?= !empty($customer->allergies) ? nl2br(e($customer->allergies)) : '<span class="text-muted">None recorded</span>' ?></p>
                            </div>
                            <div class="col-md-6">
                                <label class="text-muted small">Hair History</label>
                                <p class="mb-3"><?= !empty($customer->hair_history) ? nl2br(e($customer->hair_history)) : '<span class="text-muted">None recorded</span>' ?></p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12">
                        <label class="text-muted small">Skin Notes</label>
                        <p><?= !empty($customer->skin_notes) ? nl2br(e($customer->skin_notes)) : '<span class="text-muted">None recorded</span>' ?></p>
                    </div>
                </div>
                <div class="row mt-3">
                    <div class="col-12">
                        <label class="text-muted small">General Notes</label>
                        <p><?= !empty($customer->notes) ? nl2br(e($customer->notes)) : '<span class="text-muted">None recorded</span>' ?></p>
                    </div>
                </div>
            </div>

            <!-- Visit History Tab -->
            <div class="tab-pane fade" id="history" role="tabpanel" aria-labelledby="history-tab">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Service</th>
                                <th>Employee</th>
                                <th>Duration</th>
                                <th>Price</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($visits)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        <i class="fas fa-calendar-times fa-2x mb-2"></i>
                                        <p class="mb-0">No visit history</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($visits as $visit): ?>
                                    <tr>
                                        <td><?= formatDateTime($visit->start_time) ?></td>
                                        <td><?= e($visit->service_names ?? '-') ?></td>
                                        <td><?= e($visit->employee_names ?? '-') ?></td>
                                        <td><?= $visit->duration ? $visit->duration . ' min' : '-' ?></td>
                                        <td><?= $visit->price ? currency($visit->price) : '-' ?></td>
                                        <td>
                                            <span class="badge bg-<?= statusBadge($visit->status ?? 'pending') ?>">
                                                <?= e(ucwords(str_replace('_', ' ', $visit->status ?? 'pending'))) ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Invoices Tab -->
            <div class="tab-pane fade" id="invoices" role="tabpanel" aria-labelledby="invoices-tab">
                <div class="table-responsive">
                    <table class="table table-dark table-hover mb-0">
                        <thead>
                            <tr>
                                <th>Invoice #</th>
                                <th>Date</th>
                                <th>Items</th>
                                <th class="text-end">Total</th>
                                <th>Status</th>
                                <th class="text-center">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($invoices)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        <i class="fas fa-file-invoice-dollar fa-2x mb-2"></i>
                                        <p class="mb-0">No invoices found</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($invoices as $invoice): ?>
                                    <tr>
                                        <td><strong><?= e($invoice->invoice_number ?? 'N/A') ?></strong></td>
                                        <td><?= formatDateTime($invoice->created_at) ?></td>
                                        <td><?= (int)($invoice->item_count ?? $invoice->total_items ?? 0) ?></td>
                                        <td class="text-end"><?= currency($invoice->total ?? 0) ?></td>
                                        <td>
                                            <span class="badge bg-<?= statusBadge($invoice->status ?? 'pending') ?>">
                                                <?= e(ucfirst($invoice->status ?? 'pending')) ?>
                                            </span>
                                        </td>
                                        <td class="text-center">
                                            <a href="<?= url('invoices/show/' . $invoice->id) ?>" class="btn btn-sm btn-outline-info">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- Photos Tab -->
            <div class="tab-pane fade" id="photos" role="tabpanel" aria-labelledby="photos-tab">
                <?php if (can('customers_edit')): ?>
                    <div class="mb-4">
                        <form id="photoUploadForm" enctype="multipart/form-data">
                            <?= csrf_field() ?>
                            <div class="row g-2 align-items-end">
                                <div class="col-auto">
                                    <label class="form-label mb-0">Upload Photo</label>
                                    <input type="file" name="photo" class="form-control form-control-sm bg-transparent" 
                                           accept="image/jpeg,image/png,image/gif,image/webp" required>
                                </div>
                                <div class="col-auto">
                                    <button type="submit" class="btn btn-sm btn-gold">
                                        <i class="fas fa-upload me-1"></i>Upload
                                    </button>
                                </div>
                            </div>
                            <div id="photoUploadFeedback" class="mt-2"></div>
                        </form>
                    </div>
                <?php endif; ?>

                <div class="row g-3" id="photoGrid">
                    <?php if (empty($photos)): ?>
                        <div class="col-12 text-center text-muted py-4">
                            <i class="fas fa-camera fa-2x mb-2"></i>
                            <p class="mb-0">No photos uploaded</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($photos as $photo): ?>
                            <div class="col-md-3 col-sm-4 col-6">
                                <div class="glass-card p-2 text-center">
                                    <a href="<?= uploadUrl($photo->file_path) ?>" target="_blank">
                                        <img src="<?= uploadUrl($photo->file_path) ?>" alt="" class="img-fluid rounded" 
                                             style="height:150px;width:100%;object-fit:cover;">
                                    </a>
                                    <div class="small text-muted mt-1">
                                        <?= timeAgo($photo->created_at) ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Notes Tab -->
            <div class="tab-pane fade" id="notes" role="tabpanel" aria-labelledby="notes-tab">
                <?php if (can('customers_edit')): ?>
                    <div class="mb-4">
                        <form id="addNoteForm">
                            <?= csrf_field() ?>
                            <div class="mb-3">
                                <label class="form-label">Add Note</label>
                                <textarea name="note" class="form-control bg-transparent" rows="3" 
                                          maxlength="5000" required placeholder="Enter note..."></textarea>
                            </div>
                            <button type="submit" class="btn btn-sm btn-gold">
                                <i class="fas fa-plus me-1"></i>Add Note
                            </button>
                            <div id="noteFeedback" class="mt-2"></div>
                        </form>
                    </div>
                    <hr class="border-secondary">
                <?php endif; ?>

                <div id="notesList">
                    <?php if (empty($notes)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-comment-slash fa-2x mb-2"></i>
                            <p class="mb-0">No notes recorded</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($notes as $note): ?>
                            <div class="glass-card p-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <strong><?= e(($note->user_first_name ?? '') . ' ' . ($note->user_last_name ?? '')) ?></strong>
                                        <span class="text-muted small ms-2"><?= timeAgo($note->created_at) ?></span>
                                    </div>
                                </div>
                                <p class="mb-0"><?= nl2br(e($note->note)) ?></p>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
</div>

<?php $inlineScripts = <<<'EOS'
const baseUrl = '___BASEURL___';
const customerId = ___CUSTID___;

$('#photoUploadForm').submit(function(e) {
    e.preventDefault();
    const formData = new FormData(this);
    formData.append('_csrf_token', $('meta[name="csrf-token"]').attr('content'));
    $('#photoUploadFeedback').html('<div class="text-info"><i class="fas fa-spinner fa-spin me-1"></i>Uploading...</div>');
    $.ajax({
        url: baseUrl + '/customers/upload-photo/' + customerId,
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(res) {
            if (res.success) {
                location.reload();
            } else {
                $('#photoUploadFeedback').html('<div class="text-danger">' + (res.message || 'Upload failed') + '</div>');
            }
        },
        error: function(xhr) {
            const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Upload failed';
            $('#photoUploadFeedback').html('<div class="text-danger">' + msg + '</div>');
        }
    });
});

$('#addNoteForm').submit(function(e) {
    e.preventDefault();
    const formData = $(this).serialize() + '&_csrf_token=' + encodeURIComponent($('meta[name="csrf-token"]').attr('content'));
    $('#noteFeedback').html('<div class="text-info"><i class="fas fa-spinner fa-spin me-1"></i>Saving...</div>');
    $.post(baseUrl + '/customers/add-note/' + customerId, formData, function(res) {
        if (res.success) {
            location.reload();
        } else {
            $('#noteFeedback').html('<div class="text-danger">' + (res.message || 'Failed to add note') + '</div>');
        }
    }, 'json').fail(function(xhr) {
        const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Failed to add note';
        $('#noteFeedback').html('<div class="text-danger">' + msg + '</div>');
    });
});
EOS;
$inlineScripts = str_replace('___BASEURL___', rtrim(APP_URL, '/'), $inlineScripts);
$inlineScripts = str_replace('___CUSTID___', $customer->id, $inlineScripts);
?>
