<?php
// init.php ko shaamil karein
require_once 'init.php';

// Suraksha jaanch
if (!userHasRole(['Admin', 'Manager', 'Sales'])) {
    header("Location: dashboard.php");
    exit();
}

// --- फिल्टर्स aur Pagination ---
$limit = 20; // Ek page par 20 clients dikhayein
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;
$search_term = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? 'all';

// --- DATA FETCHING ---
$params = [];
$param_types = '';

$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM clients WHERE 1=1";

if (!empty($search_term)) {
    $sql .= " AND (name LIKE ? OR contact_person LIKE ?)";
    $search_like = "%" . $search_term . "%";
    $params = [$search_like, $search_like];
    $param_types = 'ss';
}
if ($status_filter !== 'all') {
    $sql .= " AND is_active = ?";
    $params[] = $status_filter;
    $param_types .= 'i';
}

$sql .= " ORDER BY name ASC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$param_types .= 'ii';

$stmt = $conn->prepare($sql);
if (!empty($params)) {
    $stmt->bind_param($param_types, ...$params);
}
$stmt->execute();
$clients_result = $stmt->get_result();
$clients = $clients_result->fetch_all(MYSQLI_ASSOC);
$stmt->close();

$total_clients = $conn->query("SELECT FOUND_ROWS()")->fetch_row()[0];
$total_pages = ceil($total_clients / $limit);

// --- Stats Cards ke liye Data ---
$active_clients_count = $conn->query("SELECT COUNT(id) as count FROM clients WHERE is_active = TRUE")->fetch_assoc()['count'];
$inactive_clients_count = $conn->query("SELECT COUNT(id) as count FROM clients WHERE is_active = FALSE")->fetch_assoc()['count'];

$conn->close();
require_once 'header.php';
?>

<title>Manage Clients - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Manage Clients</h2>

<div x-data="clientsPage()">

    <main class="p-6 md:p-10">
        <div class="bg-white p-4 rounded-lg shadow-md mb-8 sticky top-0 z-10">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
                <div class="bg-green-100 border-l-4 border-green-500 p-4 rounded-lg flex items-center gap-4">
                    <div class="text-green-600"><svg class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a3.002 3.002 0 013.292 0l3.5 3.5m-3.5-3.5V5a3 3 0 116 0v6.143"/></svg></div>
                    <div><p class="text-sm font-medium text-gray-500">Total Active Clients</p><p class="text-2xl font-bold text-gray-800"><?php echo $active_clients_count; ?></p></div>
                </div>
                <div class="bg-red-100 border-l-4 border-red-500 p-4 rounded-lg flex items-center gap-4">
                    <div class="text-red-600"><svg class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" /></svg></div>
                    <div><p class="text-sm font-medium text-gray-500">Inactive Clients</p><p class="text-2xl font-bold text-red-600"><?php echo $inactive_clients_count; ?></p></div>
                </div>
            </div>
            <div class="flex flex-col md:flex-row justify-between items-center gap-4 pt-4 border-t">
                <form method="GET" action="clients.php" class="flex-grow flex flex-col md:flex-row gap-4">
                    <input type="text" name="search" value="<?php echo htmlspecialchars($search_term); ?>" placeholder="Search by name or person..." class="w-full md:w-1/2 px-4 py-2 border rounded-lg">
                    <select name="status" class="w-full md:w-auto border-gray-300 rounded-md shadow-sm" onchange="this.form.submit()">
                        <option value="all" <?php if($status_filter == 'all') echo 'selected'; ?>>All Statuses</option>
                        <option value="1" <?php if($status_filter == '1') echo 'selected'; ?>>Active</option>
                        <option value="0" <?php if($status_filter == '0') echo 'selected'; ?>>Inactive</option>
                    </select>
                </form>
                <div class="flex items-center gap-4 mt-4 md:mt-0">
                    <a href="import-clients.php" class="bg-green-500 hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg shadow-sm">Import</a>
                    <a href="onboarding.php" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg shadow-sm">+ Add Client</a>
                </div>
            </div>
        </div>
        
        <div class="bg-white rounded-lg shadow-lg overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase">Client Name</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase">Contact Person</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase">Status</th>
                            <th class="px-6 py-4 text-left text-xs font-semibold text-gray-600 uppercase">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        <?php if (empty($clients)): ?>
                            <tr><td colspan="4" class="px-6 py-10 text-center text-gray-500">No clients found.</td></tr>
                        <?php else: ?>
                            <?php foreach ($clients as $client): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900"><?php echo htmlspecialchars($client['name']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-600"><?php echo htmlspecialchars($client['contact_person']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $client['is_active'] ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                            <?php echo $client['is_active'] ? 'Active' : 'Inactive'; ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium flex items-center gap-4">
                                        <a href="client-profile.php?id=<?php echo $client['id']; ?>" class="text-blue-600 hover:text-blue-900">View Profile</a>
                                        <button @click="openChecklistModal(<?php echo htmlspecialchars(json_encode($client)); ?>)" class="text-green-600 hover:text-green-900">Optimize Status</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if ($total_pages > 1): ?>
            <div class="p-4 flex justify-between items-center">
                <div class="text-sm text-gray-600">
                    Page <?php echo $page; ?> of <?php echo $total_pages; ?>
                </div>
                <div>
                    <?php if ($page > 1): ?>
                        <a href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search_term); ?>&status=<?php echo $status_filter; ?>" class="px-4 py-2 bg-white border rounded-md text-sm hover:bg-gray-50">Previous</a>
                    <?php endif; ?>
                    <?php if ($page < $total_pages): ?>
                        <a href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search_term); ?>&status=<?php echo $status_filter; ?>" class="ml-2 px-4 py-2 bg-white border rounded-md text-sm hover:bg-gray-50">Next</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </main>

    <div x-show="isModalOpen" x-transition class="fixed inset-0 bg-gray-900 bg-opacity-75 flex items-center justify-center z-50" style="display: none;">
        <div class="bg-white rounded-lg shadow-xl p-8 w-full max-w-2xl" @click.away="isModalOpen = false">
            <h3 class="text-xl font-bold mb-4">Onboarding Checklist for <span x-text="currentClient.name"></span></h3>
            <div x-show="checklistLoading" class="text-center p-8">Loading...</div>
            <div x-show="!checklistLoading" class="grid grid-cols-2 md:grid-cols-3 gap-4">
                <template x-for="item in checklistItems" :key="item.key">
                    <label class="flex items-center p-3 border rounded-lg cursor-pointer" :class="{ 'bg-green-50 border-green-400': item.checked }">
                        <input type="checkbox" class="h-5 w-5 rounded" :checked="item.checked" @change="updateChecklistItem(item)">
                        <span class="ml-3 text-sm font-medium" x-text="item.label"></span>
                    </label>
                </template>
            </div>
            <div class="flex justify-end mt-8"><button @click="isModalOpen = false" class="px-6 py-2 bg-gray-200 rounded-md">Close</button></div>
        </div>
    </div>

</div> <script>
function clientsPage() {
    return {
        isModalOpen: false,
        checklistLoading: false,
        currentClient: {},
        checklistItems: [],
        
        openChecklistModal(client) {
            this.currentClient = client;
            this.isModalOpen = true;
            this.checklistLoading = true;
            fetch(`get_checklist.php?client_id=${client.id}`)
                .then(res => res.json())
                .then(data => {
                    if(data.status === 'success') { this.populateChecklist(data.checklist); } 
                    else { alert('Error: Could not load checklist data.'); }
                    this.checklistLoading = false;
                })
                .catch(error => {
                    console.error('Error fetching checklist:', error);
                    alert('Error: Could not load checklist data.');
                    this.checklistLoading = false;
                });
        },
        populateChecklist(checklistData) {
            const labels = {
                seo_keywords: 'SEO Keywords', seo_link: 'SEO Link', google_photos: 'Google Photos',
                google_no: 'Google No.', insta_highlights: 'Insta Highlights', insta_bio: 'Insta Bio',
                insta_grid: 'Insta Grid', whatsapp_logo: 'Whatsapp Logo', qr_code: 'QR Code'
            };
            this.checklistItems = [];
            for (const key in labels) {
                this.checklistItems.push({
                    key: key, label: labels[key], checked: checklistData && checklistData[key] == 1
                });
            }
        },
        updateChecklistItem(item) {
            // Optimistically update the UI
            const originalCheckedState = item.checked;
            item.checked = !originalCheckedState;

            fetch('update_checklist_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    client_id: this.currentClient.id, item_key: item.key, status: item.checked
                })
            })
            .then(res => res.json())
            .then(data => {
                if(data.status !== 'success') {
                    // Revert on failure
                    item.checked = originalCheckedState; 
                    alert('Error: Could not save the change.');
                }
            })
            .catch(error => {
                console.error('Error updating checklist:', error);
                item.checked = originalCheckedState; // Revert on failure
                alert('Error: Could not save the change.');
            });
        }
    }
}
</script>

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