<?php
require_once 'config/config.php';
require_once 'header.php';

$lang_code = $_SESSION['language'] ?? 'english';
require_once "languages/$lang_code.php";

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}
$user_id = $_SESSION['user_id'];

$whereClause = in_array($user_id, [1, 2]) ? "" : "WHERE c.created_by = $user_id";

$result = $conn->query("
    SELECT c.*, u.name AS created_by
    FROM customers_followup c
    LEFT JOIN users u ON c.created_by = u.id
    $whereClause
    ORDER BY c.id DESC
");
// جلب جميع المستخدمين لفلتر "created_by"
$usersResult = $conn->query("SELECT id, name FROM users ORDER BY name");

?>

<div class="main-content p-4" style="flex:1;">
   
<?php include 'upcoming_followups.php'; ?>

    <div class="card">
        <div class="card-header">
            <h4><?= $lang['all_customers'] ?></h4>
        </div>
        <div class="card-body table-responsive">
           <!-- فلاتر البحث -->
<div class="row mb-3 align-items-end">
    <div class="col-md-3">
        <input type="text" id="searchInput" class="form-control" placeholder="<?= $lang['search_by_name_or_mobile'] ?>">
    </div>

    <div class="col-md-2">
        <select id="followupFilter" class="form-select">
            <option value="all"><?= $lang['all_statuses'] ?></option>
            <option value="done"><?= $lang['followed_up'] ?></option>
            <option value="pending"><?= $lang['not_followed_up'] ?></option>
        </select>
    </div>

    <div class="col-md-2">
        <input type="date" id="followupDateFilter" class="form-control" placeholder="<?= $lang['filter_by_followup_date'] ?>">
    </div>

    <?php if (in_array($_SESSION['user_id'], [1, 2])): ?>
    <div class="col-md-2">
        <select id="userFilter" class="form-select">
            <option value="all"><?= $lang['all_users'] ?></option>
            <?php while ($user = $usersResult->fetch_assoc()): ?>
                <option value="<?= $user['name'] ?>"><?= htmlspecialchars($user['name']) ?></option>
            <?php endwhile; ?>
        </select>
    </div>
    <?php endif; ?>

    <div class="col-md-3">
        <button class="btn btn-secondary w-100" onclick="resetFilters()"><?= $lang['reset'] ?></button>
    </div>
</div>



<table id="customersTable" class="table table-bordered table-striped">
                <thead>
                    <tr>
                        <th><?= $lang['customer_name'] ?></th>
                        <th><?= $lang['mobile_number'] ?></th>
                        <th><?= $lang['number_of_people'] ?></th>
                        <th><?= $lang['number_of_days'] ?></th>
                        <th><?= $lang['trip_type'] ?></th>
                        <th><?= $lang['status'] ?></th>
                        <th><?= $lang['first_contact_date'] ?></th>
                        <th><?= $lang['followup_date'] ?></th>
                        <th><?= $lang['closed_date'] ?></th>
                        <th><?= $lang['created_by'] ?></th>
                        <th><?= $lang['actions'] ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php while ($row = $result->fetch_assoc()):
                        $row_class = '';
                        $today = date('Y-m-d');
                        $diff_days = (strtotime($row['followup_date']) - strtotime($today)) / 86400;

                        if ($row['followed_up']) {
                            $row_class = 'table-success';
                        } elseif ($diff_days >= 0 && $diff_days <= 3) {
                            $row_class = 'table-danger';
                        }
                    ?>
                        <tr class="<?= $row_class ?>" id="row-<?= $row['id'] ?>">
                            <td><?= htmlspecialchars($row['customer_name']) ?></td>
                            <td><?= htmlspecialchars($row['mobile_number']) ?></td>
                            <td><?= htmlspecialchars($row['number_of_people']) ?></td>
                            <td><?= htmlspecialchars($row['number_of_days']) ?></td>
                            <td>
                                <?php
                                    switch ($row['trip_type']) {
                                        case 'package': echo $lang['trip_package']; break;
                                        case 'hajj': echo $lang['trip_hajj']; break;
                                        case 'umrah': echo $lang['trip_umrah']; break;
                                        default: echo '-';
                                    }
                                ?>
                            </td>
                            <td class="status-cell"><?= $lang['status_' . strtolower(str_replace(' ', '_', $row['status']))] ?></td>
                            <td><?= htmlspecialchars($row['first_contact_date']) ?></td>
                            <td><?= htmlspecialchars($row['followup_date']) ?></td>
                            <td class="closed-date-cell"><?= $row['closed_date'] ? htmlspecialchars($row['closed_date']) : '-' ?></td>
                            <td><?= htmlspecialchars($row['created_by']) ?></td>

<td>
    <?php
        // تحويل رقم الهاتف إلى 962 format
        $raw_mobile = preg_replace('/\D/', '', $row['mobile_number']);
        if (strpos($raw_mobile, '962') === 0) {
            $formatted_mobile = $raw_mobile;
        } elseif (strpos($raw_mobile, '0') === 0) {
            $formatted_mobile = '962' . substr($raw_mobile, 1);
        } elseif (strlen($raw_mobile) === 9) {
            $formatted_mobile = '962' . $raw_mobile;
        } else {
            $formatted_mobile = $raw_mobile;
        }
    ?>

    <!-- زر واتساب -->
    <a href="https://api.whatsapp.com/send?phone=<?= $formatted_mobile ?>" target="_blank" class="btn btn-sm btn-success" title="WhatsApp">
        <i class="bi bi-whatsapp"></i>
    </a>

    <!-- زر المتابعة -->
    <?php if (!$row['followed_up']): ?>
        <button class="btn btn-sm btn-primary followup-btn"
            data-id="<?= $row['id'] ?>"
            data-name="<?= htmlspecialchars($row['customer_name']) ?>"
            data-mobile="<?= htmlspecialchars($row['mobile_number']) ?>"
            data-people="<?= htmlspecialchars($row['number_of_people']) ?>"
            data-days="<?= htmlspecialchars($row['number_of_days']) ?>"
            data-trip="<?= htmlspecialchars($row['trip_type']) ?>"
            data-request="<?= htmlspecialchars($row['request_details']) ?>"
            data-status="<?= htmlspecialchars($row['status']) ?>"
            data-first="<?= htmlspecialchars($row['first_contact_date']) ?>"
            data-next="<?= htmlspecialchars($row['followup_date']) ?>">
            <?= $lang['followed_up'] ?>
        </button>
    <?php else: ?>
        <span class="badge bg-success"><?= $lang['followed_up'] ?></span>
    <?php endif; ?>
    
    <?php if (in_array($_SESSION['user_id'], [1, 2])): ?>
    <button class="btn btn-sm btn-warning reopen-btn"
        data-id="<?= $row['id'] ?>"
        data-next="<?= $row['followup_date'] ?>">
<?= $lang['reopen_followup'] ?>
    </button>
<?php endif; ?>

</td>
                        </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal 1 -->
<div class="modal fade" id="followupModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><?= $lang['followed_up'] ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p><strong><?= $lang['customer_name'] ?>:</strong> <span id="modalCustomerName"></span></p>
        <p><strong><?= $lang['mobile_number'] ?>:</strong> <span id="modalCustomerMobile"></span></p>
        <p><strong><?= $lang['number_of_people'] ?>:</strong> <span id="modalPeople"></span></p>
        <p><strong><?= $lang['number_of_days'] ?>:</strong> <span id="modalDays"></span></p>
        <p><strong><?= $lang['trip_type'] ?>:</strong> <span id="modalTrip"></span></p>
        <p><strong><?= $lang['request_details'] ?>:</strong> <span id="modalRequest"></span></p>
        <p><strong><?= $lang['status'] ?>:</strong> <span id="modalStatus"></span></p>
        <p><strong><?= $lang['first_contact_date'] ?>:</strong> <span id="modalFirst"></span></p>
        <p><strong><?= $lang['followup_date'] ?>:</strong> <span id="modalNext"></span></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= $lang['cancel'] ?></button>
        <button type="button" class="btn btn-success" id="confirmFollowBtn"><?= $lang['confirm'] ?></button>
      </div>
    </div>
  </div>
</div>

<!-- Modal 2 -->
<div class="modal fade" id="closeDateModal" tabindex="-1">
  <div class="modal-dialog">
    <form id="closeDateForm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><?= $lang['enter_close_date'] ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label"><?= $lang['status'] ?></label>
                    <select name="status_update" id="status_update" class="form-select" required>
                        <option value="Waiting"><?= $lang['status_waiting'] ?></option>
                        <option value="Interested"><?= $lang['status_interested'] ?></option>
                        <option value="Not Interested"><?= $lang['status_not_interested'] ?></option>
                        <option value="Purchased"><?= $lang['status_purchased'] ?></option>
                    </select>
                </div>
                <p class="mb-0"><?= $lang['closed_date'] ?>: <strong><?= date('Y-m-d') ?></strong></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= $lang['cancel'] ?></button>
<button type="submit" class="btn btn-primary"><?= $lang['confirm'] ?></button>
            </div>
        </div>
        
        
    </form>
  </div>
</div>
<!-- Modal فتح المتابعة -->
<div class="modal fade" id="reopenModal" tabindex="-1">
  <div class="modal-dialog">
    <form id="reopenForm">
        <div class="modal-content">
            <div class="modal-header">
<h5 class="modal-title"><?= $lang['reopen_followup'] ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="reopenId" name="id">
                <div class="mb-3">
                    <label class="form-label"><?= $lang['followup_date'] ?></label>
                    <input type="date" name="followup_date" id="newFollowupDate" class="form-control" required>
                </div>
            </div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary"><?= $lang['confirm'] ?></button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= $lang['cancel'] ?></button>
            </div>
        </div>
    </form>
  </div>
</div>

<script>
    let selectedId = null;

    document.querySelectorAll('.followup-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            selectedId = this.dataset.id;
            document.getElementById('modalCustomerName').textContent = this.dataset.name;
            document.getElementById('modalCustomerMobile').textContent = this.dataset.mobile;
            document.getElementById('modalPeople').textContent = this.dataset.people;
            document.getElementById('modalDays').textContent = this.dataset.days;
            document.getElementById('modalTrip').textContent = this.dataset.trip;
            document.getElementById('modalRequest').textContent = this.dataset.request;
            document.getElementById('modalStatus').textContent = this.dataset.status;
            document.getElementById('modalFirst').textContent = this.dataset.first;
            document.getElementById('modalNext').textContent = this.dataset.next;
            new bootstrap.Modal(document.getElementById('followupModal')).show();
        });
    });

    document.getElementById('confirmFollowBtn').addEventListener('click', function () {
        bootstrap.Modal.getInstance(document.getElementById('followupModal')).hide();
        new bootstrap.Modal(document.getElementById('closeDateModal')).show();
    });

    document.getElementById('closeDateForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const closedDate = new Date().toISOString().split('T')[0];
        const status = document.getElementById('status_update').value;

        fetch('mark_followup_ajax.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `id=${selectedId}&closed_date=${closedDate}&status=${encodeURIComponent(status)}`
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                const row = document.getElementById('row-' + selectedId);
                row.classList.remove('table-danger');
                row.classList.add('table-success');
                row.querySelector('.followup-btn')?.remove();
                const badge = document.createElement('span');
                badge.className = 'badge bg-success';
                badge.textContent = '<?= $lang['followed_up'] ?>';
                row.querySelector('td:last-child').appendChild(badge);
                row.querySelector('.closed-date-cell').textContent = closedDate;
                row.querySelector('.status-cell').textContent = status;
                bootstrap.Modal.getInstance(document.getElementById('closeDateModal')).hide();
            }
        });
    });
    
    
    
</script>

<script>
    window.addEventListener('DOMContentLoaded', function () {
const rows = document.querySelectorAll("#customersTable tbody tr");

        document.getElementById('searchInput').addEventListener('input', filterRows);
        document.getElementById('followupFilter').addEventListener('change', filterRows);
        document.getElementById('followupDateFilter').addEventListener('change', filterRows);
        document.getElementById('userFilter')?.addEventListener('change', filterRows); // ← هذا السطر الجديد


function filterRows() {
    const search = document.getElementById('searchInput').value.toLowerCase();
    const status = document.getElementById('followupFilter').value;
    const date = document.getElementById('followupDateFilter').value;
    const user = document.getElementById('userFilter')?.value?.toLowerCase() ?? 'all';

    rows.forEach(row => {
        const name = row.cells[0].textContent.toLowerCase();
        const mobile = row.cells[1].textContent.toLowerCase();
        const statusCell = row.querySelector('.status-cell')?.textContent.toLowerCase();
        const followupDate = row.cells[7].textContent;
        const createdBy = row.cells[9].textContent.toLowerCase();

        let show = true;

        if (search && !name.includes(search) && !mobile.includes(search)) show = false;
        if (status === 'done' && !row.classList.contains('table-success')) show = false;
        if (status === 'pending' && row.classList.contains('table-success')) show = false;
        if (date && followupDate !== date) show = false;
        if (user !== 'all' && createdBy !== user) show = false;

        row.style.display = show ? '' : 'none';
    });
}

        window.resetFilters = function () {
            document.getElementById('searchInput').value = '';
            document.getElementById('followupFilter').value = 'all';
            document.getElementById('followupDateFilter').value = '';
            filterRows();
        }
    });
</script>

<script>
document.querySelectorAll('.reopen-btn').forEach(button => {
    button.addEventListener('click', function () {
        document.getElementById('reopenId').value = this.dataset.id;
        document.getElementById('newFollowupDate').value = this.dataset.next;
        new bootstrap.Modal(document.getElementById('reopenModal')).show();
    });
});

document.getElementById('reopenForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const id = document.getElementById('reopenId').value;
    const newDate = document.getElementById('newFollowupDate').value;

    fetch('reopen_followup_ajax.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `id=${id}&followup_date=${newDate}`
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            location.reload(); // يمكنك تحسينه لتحديث السطر فقط بدون ريفريش
        }
    });
});
</script>

<?php require_once 'includes/footer.php'; ?>
