<?php
// =============================================
// SHARK CRM - Single Customer View Page
// =============================================

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

if (!$customer_id) {
    header('Location: index.php?page=customers');
    exit;
}

$customerQ = $conn->query("
    SELECT c.*, co.name AS country_name, co.phone_code, u.name AS added_by_name
    FROM customers c
    LEFT JOIN countries co ON co.id = c.country_id
    LEFT JOIN users u ON u.id = c.created_by_user_id
    WHERE c.id = $customer_id
      AND c.account_id = $account_id
    LIMIT 1
");

if (!$customerQ || $customerQ->num_rows === 0) {
    header('Location: index.php?page=customers');
    exit;
}

$customer = $customerQ->fetch_assoc();

$contacts = $conn->query("
    SELECT *
    FROM customer_contacts
    WHERE customer_id = $customer_id
    ORDER BY id DESC
");


// Labels: schema-safe support for customer_lable_customers.lable_id or label_id
$labels = false;
if (tableExists($conn, 'customer_lable_customers') && tableExists($conn, 'customer_lable')) {
    $labelKey = columnExists($conn, 'customer_lable_customers', 'lable_id') ? 'lable_id' : (columnExists($conn, 'customer_lable_customers', 'label_id') ? 'label_id' : '');
    if ($labelKey) {
        $labels = $conn->query("
            SELECT l.name, l.color
            FROM customer_lable_customers clc
            JOIN customer_lable l ON l.id = clc.`$labelKey` AND l.account_id = clc.account_id
            WHERE clc.customer_id = $customer_id AND clc.account_id = $account_id
            ORDER BY l.name
        ");
    }
}
$canCustomerDelete = userCan($conn, 'customers', 'delete');

$leads = $conn->query("
    SELECT l.*, i.name AS item_name, s.name AS stage_name, s.color AS stage_color, u.name AS assigned_name
    FROM leads l
    LEFT JOIN items i ON i.id = l.item_id
    LEFT JOIN stage s ON s.id = l.stage_id
    LEFT JOIN users u ON u.id = l.assigned_user_id
    WHERE l.customer_id = $customer_id
      AND l.account_id = $account_id
      AND l.datetime_deleted IS NULL
    ORDER BY l.datetime_created DESC
");

$reminders = $conn->query("
    SELECT r.*, at.name AS type_name, u.name AS user_name, l.title AS lead_title
    FROM reminder r
    LEFT JOIN activity_type at ON at.id = r.activity_type_id
    LEFT JOIN users u ON u.id = r.user_id
    LEFT JOIN leads l ON l.id = r.lead_id
    WHERE r.customer_id = $customer_id
      AND r.account_id = $account_id
    ORDER BY r.date DESC, r.time DESC
");

$communications = $conn->query("
    SELECT cm.*, mt.name AS message_type
    FROM communications cm
    LEFT JOIN message_type mt ON mt.id = cm.message_type_id
    WHERE cm.customer_id = $customer_id
    ORDER BY cm.date_created DESC
    LIMIT 40
");

$activity_types = $conn->query("SELECT id, name FROM activity_type ORDER BY name");

$leadsForReminder = $conn->query("
    SELECT id, title
    FROM leads
    WHERE customer_id = $customer_id
      AND account_id = $account_id
      AND datetime_deleted IS NULL
    ORDER BY datetime_created DESC
");
?>

<div class="fade-in">

    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:24px;gap:12px;flex-wrap:wrap;">
        <div>
            <a href="index.php?page=customers" style="display:inline-flex;gap:8px;text-decoration:none;color:var(--text);margin-bottom:10px;">
                ← Back to Customers
            </a>
            <h1 style="margin:0;font-size:28px;">
                <?= htmlspecialchars($customer['customer_name']) ?>
            </h1>
            <p class="text-muted" style="margin-top:6px;">
                Customer ID: #<?= $customer_id ?>
            </p>
        </div>

        <div style="display:flex;gap:8px;">
            <!--<button class="btn btn-primary" onclick="openModal('reminderModal')">+ Add Reminder</button>-->
            <button type="button" class="btn btn-primary" onclick="openModal('reminderModal')">
    + Add Reminder
</button>
            <a href="index.php?page=customer_report&search=<?= urlencode($customer['customer_name']) ?>" class="btn btn-secondary">Customer Report</a>
            <a href="index.php?page=leads&customer_id=<?= crmEid($customer_id) ?>" class="btn btn-secondary">View Leads</a>
            <?php if ($canCustomerDelete): ?><button class="btn btn-danger" data-permission="delete" onclick="deleteCustomerFromView(<?= $customer_id ?>)">🗑 Delete</button><?php endif; ?>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:1fr 1.3fr;gap:24px;">

        <!-- LEFT -->
        <div>

            <div class="card" style="padding:20px;margin-bottom:20px;">
                <h3 style="margin-top:0;">Customer Information</h3>

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                    <div>
                        <label class="form-label">Customer</label>
                        <p><strong><?= htmlspecialchars($customer['customer_name']) ?></strong></p>
                    </div>

                    <div>
                        <label class="form-label">Business</label>
                        <p><?= htmlspecialchars($customer['business_name'] ?: '—') ?></p>
                    </div>

                    <div>
                        <label class="form-label">Phone</label>
                        <p><?= htmlspecialchars($customer['phone'] ?: '—') ?></p>
                    </div>

                    <div>
                        <label class="form-label">Email</label>
                        <p><?= htmlspecialchars($customer['email'] ?: '—') ?></p>
                    </div>

                    <div>
                        <label class="form-label">Country</label>
                        <p><?= htmlspecialchars($customer['country_name'] ?: '—') ?></p>
                    </div>

                    <div>
                        <label class="form-label">Priority</label>
                        <p><?= renderStars($customer['priority']) ?></p>
                    </div>

                    <div class="span-2">
                        <label class="form-label">Labels</label>
                        <p>
                        <?php if ($labels && $labels->num_rows): while($lb=$labels->fetch_assoc()): ?>
                            <span class="badge" style="background:<?= htmlspecialchars($lb['color']) ?>22;color:<?= htmlspecialchars($lb['color']) ?>;border:1px solid <?= htmlspecialchars($lb['color']) ?>44;margin-right:5px"><?= htmlspecialchars($lb['name']) ?></span>
                        <?php endwhile; else: ?>
                            <span class="text-muted">No labels</span>
                        <?php endif; ?>
                        </p>
                    </div>

                    <div>
                        <label class="form-label">Address</label>
                        <p><?= htmlspecialchars($customer['address'] ?: '—') ?></p>
                    </div>

                    <div>
                        <label class="form-label">Since</label>
                        <p class="text-muted text-sm"><?= formatDate($customer['date_created']) ?></p>
                    </div>

                    <div>
                        <label class="form-label">Added By</label>
                        <p><?= htmlspecialchars($customer['added_by_name'] ?: '—') ?></p>
                    </div>
                </div>

                <div class="hr"></div>

                <label class="form-label">Notes</label>
                <div style="background:var(--bg-secondary);border-radius:8px;padding:12px;min-height:80px;">
                    <?= $customer['notes'] ? nl2br(htmlspecialchars($customer['notes'])) : '<span class="text-muted text-sm">No notes</span>' ?>
                </div>
            </div>

            <div class="card" style="padding:20px;">
                <h3 style="margin-top:0;">Contacts</h3>

                <?php if ($contacts && $contacts->num_rows > 0): ?>
                    <?php while ($ct = $contacts->fetch_assoc()): ?>
                        <div style="padding:12px;background:var(--bg-secondary);border-radius:8px;margin-bottom:10px;">
                            <strong><?= htmlspecialchars($ct['name']) ?></strong>
                            <?php if ($ct['job_title']): ?>
                                <span class="text-muted"> - <?= htmlspecialchars($ct['job_title']) ?></span>
                            <?php endif; ?>

                            <?php if ($ct['phone']): ?>
                                <div class="text-sm">📞 <?= htmlspecialchars($ct['phone']) ?></div>
                            <?php endif; ?>

                            <?php if ($ct['email']): ?>
                                <div class="text-sm">✉️ <?= htmlspecialchars($ct['email']) ?></div>
                            <?php endif; ?>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?>
                    <p class="text-muted text-sm">No contacts added</p>
                <?php endif; ?>
            </div>

        </div>

        <!-- RIGHT -->
        <div class="card" style="padding:20px;">
            <div class="tabs" style="display:flex;gap:8px;border-bottom:1px solid var(--border);margin-bottom:16px;flex-wrap:wrap;">
                <button class="tab-btn active" data-tab="tab-leads">📌 Leads (<?= $leads->num_rows ?>)</button>
                <button class="tab-btn" data-tab="tab-reminders">⏰ Reminders (<?= $reminders->num_rows ?>)</button>
                <button class="tab-btn" data-tab="tab-communications">💬 Communications (<?= $communications->num_rows ?>)</button>
            </div>

            <!-- Leads -->
            <div class="tab-pane active scroll-panel" id="tab-leads">
                <?php if ($leads->num_rows === 0): ?>
                    <p class="text-muted text-sm" style="text-align:center;padding:30px;">No leads found</p>
                <?php else: ?>
                    <?php while ($l = $leads->fetch_assoc()): ?>
                        <div class="timeline-card">
                            <div style="display:flex;justify-content:space-between;gap:12px;">
                                <div>
                                    <strong><?= htmlspecialchars($l['title'] ?: 'Lead') ?></strong>
                                    <div class="text-xs text-muted">
                                        <?= htmlspecialchars($l['item_name'] ?: 'No item') ?>
                                    </div>
                                </div>

                                <span style="background:<?= $l['stage_color'] ?? '#3b82f6' ?>22;color:<?= $l['stage_color'] ?? '#3b82f6' ?>;padding:4px 10px;border-radius:20px;font-size:12px;">
                                    <?= htmlspecialchars($l['stage_name'] ?: 'No stage') ?>
                                </span>
                            </div>

                            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:12px;">
                                <div>
                                    <label class="form-label">Price</label>
                                    <div><?= crmMoney($l['estimated_price'], $l['item_currency'] ?? 'USD') ?></div>
                                </div>

                                <div>
                                    <label class="form-label">Opportunity</label>
                                    <div><?= (int)$l['opportunity'] ?>%</div>
                                </div>

                                <div>
                                    <label class="form-label">Status</label>
                                    <div><?= htmlspecialchars($l['status']) ?></div>
                                </div>
                            </div>

                            <div style="margin-top:12px;">
                                <a class="btn btn-secondary btn-sm" href="index.php?page=lead&id=<?= crmEid($l['id']) ?>">Open Lead</a>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif; ?>
            </div>

            <!-- Reminders -->
            <div class="tab-pane scroll-panel" id="tab-reminders" style="display:none;">
                <?php if ($reminders->num_rows === 0): ?>
                    <p class="text-muted text-sm" style="text-align:center;padding:30px;">No reminders found</p>
                <?php else: ?>
                    <?php while ($r = $reminders->fetch_assoc()): ?>
                        <div class="timeline-card">
                            <div style="display:flex;justify-content:space-between;gap:12px;">
                                <div>
                                    <strong><?= htmlspecialchars($r['type_name'] ?: 'Reminder') ?></strong>
                                    <div class="text-xs text-muted">
                                        By <?= htmlspecialchars($r['user_name'] ?: 'User') ?>
                                    </div>
                                </div>

                                <span class="badge badge-blue">
                                    <?= htmlspecialchars($r['date']) ?>
                                    <?= $r['time'] ? htmlspecialchars(substr($r['time'], 0, 5)) : '' ?>
                                </span>
                            </div>

                            <div style="margin-top:10px;">
                                <?= nl2br(htmlspecialchars($r['comment'])) ?>
                            </div>

                            <?php if ($r['lead_id']): ?>
                                <div class="text-xs text-muted" style="margin-top:8px;">
                                    Linked Lead: <?= htmlspecialchars($r['lead_title'] ?: 'Lead') ?>
                                </div>
                            <?php else: ?>
                                <div class="text-xs text-muted" style="margin-top:8px;">
                                    General customer reminder
                                </div>
                            <?php endif; ?>

                            <div class="text-xs text-muted" style="margin-top:6px;">
                                Status: <?= htmlspecialchars($r['status']) ?>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif; ?>
            </div>

            <!-- Communications -->
            <div class="tab-pane scroll-panel" id="tab-communications" style="display:none;">
                <?php if ($communications->num_rows === 0): ?>
                    <p class="text-muted text-sm" style="text-align:center;padding:30px;">No communications found</p>
                <?php else: ?>
                    <?php while ($cm = $communications->fetch_assoc()): ?>
                        <div class="timeline-card">
                            <div style="display:flex;justify-content:space-between;gap:12px;">
                                <div>
                                    <strong><?= htmlspecialchars($cm['message_type'] ?: 'Message') ?></strong>
                                    <div class="text-xs text-muted">
                                        To: <?= htmlspecialchars($cm['recipient']) ?>
                                    </div>
                                </div>

                                <span class="badge <?= $cm['status'] === 'sent' ? 'badge-green' : 'badge-red' ?>">
                                    <?= htmlspecialchars($cm['status']) ?>
                                </span>
                            </div>

                            <?php if ($cm['subject']): ?>
                                <div style="margin-top:8px;">
                                    <strong>Subject:</strong> <?= htmlspecialchars($cm['subject']) ?>
                                </div>
                            <?php endif; ?>

                            <div style="margin-top:8px;">
                                <?= nl2br(htmlspecialchars($cm['message'])) ?>
                            </div>

                            <div class="text-xs text-muted" style="margin-top:8px;">
                                <?= formatDate($cm['date_created']) ?>
                            </div>
                        </div>
                    <?php endwhile; ?>
                <?php endif; ?>
            </div>

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

<!-- ADD REMINDER MODAL -->
<!--<div class="modal-overlay" id="reminderModal" style="display:none;">-->
<div class="modal-overlay" id="reminderModal">
    <div class="modal">
        <div class="modal-header">
            <span class="modal-title">Add Reminder</span>
            <button class="modal-close" onclick="closeModal('reminderModal')">✕</button>
        </div>

        <div class="modal-body">
            <input type="hidden" id="remCustomerId" value="<?= crmEid($customer_id) ?>">

            <div class="form-group">
                <label class="form-label">Reminder Type</label>
                <select id="reminderType" class="form-control">
                    <?php $activity_types->data_seek(0); while ($at = $activity_types->fetch_assoc()): ?>
                        <option value="<?= $at['id'] ?>"><?= htmlspecialchars($at['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label class="form-label">Date *</label>
                    <input type="date" id="reminderDate" class="form-control">
                </div>

                <div class="form-group">
                    <label class="form-label">Time</label>
                    <input type="time" id="reminderTime" class="form-control">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Link to Lead optional</label>
                <select id="reminderLeadId" class="form-control">
                    <option value="">General reminder - no lead</option>
                    <?php while ($rl = $leadsForReminder->fetch_assoc()): ?>
                        <option value="<?= $rl['id'] ?>">
                            <?= htmlspecialchars($rl['title'] ?: 'Lead') ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label class="form-label">Comment *</label>
                <textarea id="reminderComment" class="form-control" rows="4" placeholder="Reminder note..."></textarea>
            </div>
        </div>

        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeModal('reminderModal')">Cancel</button>
            <button class="btn btn-primary" onclick="addCustomerReminder()">Save Reminder</button>
        </div>
    </div>
</div>

<script>
async function addCustomerReminder() {
    const customerId = document.getElementById('remCustomerId').value;
    const leadId = document.getElementById('reminderLeadId').value;
    const typeId = document.getElementById('reminderType').value;
    const date = document.getElementById('reminderDate').value;
    const time = document.getElementById('reminderTime').value;
    const comment = document.getElementById('reminderComment').value.trim();

    if (!date) {
        showToast('Please select reminder date', 'warning');
        return;
    }

    if (!comment) {
        showToast('Please enter reminder comment', 'warning');
        return;
    }

    const res = await apiCall('handlers/customers.php', {
        action: 'add_reminder',
        customer_id: customerId,
        lead_id: leadId,
        activity_type_id: typeId,
        date: date,
        time: time,
        comment: comment
    });

    if (res.success) {
        showToast('Reminder added', 'success');
        closeModal('reminderModal');
        setTimeout(() => location.reload(), 600);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

document.querySelectorAll('.tab-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        const tabId = btn.dataset.tab;

        document.querySelectorAll('.tab-btn').forEach(b => {
            b.classList.remove('active');
            b.style.borderBottom = 'none';
            b.style.color = 'var(--text)';
        });

        document.querySelectorAll('.tab-pane').forEach(p => {
            p.style.display = 'none';
        });

        btn.classList.add('active');
        btn.style.borderBottom = '2px solid var(--accent)';
        btn.style.color = 'var(--accent)';

        document.getElementById(tabId).style.display = 'block';
    });
});

async function apiCall(url, data) {
    const formData = new FormData();

    for (let key in data) {
        formData.append(key, data[key]);
    }

    const response = await fetch(url, {
        method: 'POST',
        body: formData
    });

    return await response.json();
}

function openModal(id) {
    document.getElementById(id).style.display = 'flex';
}

function closeModal(id) {
    document.getElementById(id).style.display = 'none';
}
</script>

<style>
.card {
    background: var(--bg-card);
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.form-label {
    display: block;
    margin-bottom: 4px;
    font-size: 12px;
    font-weight: 500;
    color: var(--text-muted);
}

.text-xs { font-size: 12px; }
.text-sm { font-size: 13px; }
.text-muted { color: var(--text-muted); }

.hr {
    height: 1px;
    background: var(--border);
    margin: 16px 0;
}

.tab-btn {
    padding: 8px 16px;
    background: none;
    border: none;
    cursor: pointer;
    border-bottom: 2px solid transparent;
    color: var(--text);
}

.tab-btn.active {
    color: var(--accent);
    border-bottom: 2px solid var(--accent);
}

.timeline-card {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 10px;
    padding: 14px;
    margin-bottom: 12px;
}

.badge {
    display: inline-block;
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
}

.badge-blue {
    background: #dbeafe;
    color: #1d4ed8;
}

.badge-green {
    background: #dcfce7;
    color: #166534;
}

.badge-red {
    background: #fee2e2;
    color: #991b1b;
}

.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,.5);
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal {
    max-width: 550px;
    width: 100%;
    background: var(--bg-card);
    border-radius: 12px;
    margin: 20px;
}

.modal-header,
.modal-footer {
    padding: 16px 20px;
    border-bottom: 1px solid var(--border);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-footer {
    border-bottom: 0;
    border-top: 1px solid var(--border);
    justify-content: flex-end;
    gap: 10px;
}

.modal-body {
    padding: 20px;
}

.modal-close {
    background: none;
    border: none;
    font-size: 22px;
    cursor: pointer;
}
</style>