<?php
session_start();
require_once 'includes/auth.php';
requireLogin();
require_once 'config/database.php';
require_once 'includes/functions.php';

$userId = $_SESSION['user_id'];

// Get user's company
$stmt = $pdo->prepare("SELECT * FROM companies WHERE user_id = ? LIMIT 1");
$stmt->execute([$userId]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: settings.php');
    exit;
}

$companyId = $company['id'];

// Handle delete if requested
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $deleteId = $_GET['delete'];
    $stmt = $pdo->prepare("DELETE FROM clients WHERE id = ? AND company_id = ?");
    $stmt->execute([$deleteId, $companyId]);
    header('Location: clients.php?msg=deleted');
    exit;
}

// Fetch all clients
$stmt = $pdo->prepare("SELECT * FROM clients WHERE company_id = ? ORDER BY created_at DESC");
$stmt->execute([$companyId]);
$clients = $stmt->fetchAll();

include 'includes/header.php';
?>

<!-- Success/Error messages -->
<?php if (isset($_GET['msg'])): ?>
    <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded-lg mb-4">
        <?php 
        if ($_GET['msg'] == 'added') echo 'Client added successfully!';
        if ($_GET['msg'] == 'updated') echo 'Client updated successfully!';
        if ($_GET['msg'] == 'deleted') echo 'Client deleted successfully!';
        ?>
    </div>
<?php endif; ?>

<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm overflow-hidden">
    <div class="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex justify-between items-center">
        <h3 class="text-lg font-semibold text-gray-800 dark:text-white">All Clients</h3>
        <button onclick="openClientModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
            <i class="fas fa-plus mr-2"></i>Add Client
        </button>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full">
            <thead class="bg-gray-50 dark:bg-gray-700/50">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Name</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Email</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Phone</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Location</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                <?php if (empty($clients)): ?>
                    <tr>
                        <td colspan="5" class="px-6 py-12 text-center text-gray-500 dark:text-gray-400">No clients yet. Click "Add Client" to get started.</td>
                    </tr>
                <?php else: foreach ($clients as $client): ?>
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/50">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white"><?php echo htmlspecialchars($client['name']); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($client['email'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400"><?php echo htmlspecialchars($client['phone'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-500 dark:text-gray-400">
                            <?php
                            $location = [];
                            if ($client['city']) $location[] = $client['city'];
                            if ($client['country']) $location[] = $client['country'];
                            echo htmlspecialchars(implode(', ', $location) ?: '-');
                            ?>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <button onclick="editClient(<?php echo htmlspecialchars(json_encode($client)); ?>)" class="text-blue-600 hover:text-blue-800 mr-3"><i class="fas fa-edit"></i></button>
                            <a href="?delete=<?php echo $client['id']; ?>" onclick="return confirm('Are you sure? This will also delete all associated invoices.')" class="text-red-600 hover:text-red-800"><i class="fas fa-trash"></i></a>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Client Modal -->
<div id="clientModal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-full max-w-md shadow-lg rounded-lg bg-white dark:bg-gray-800">
        <div class="flex justify-between items-center mb-4">
            <h3 id="modalTitle" class="text-lg font-semibold text-gray-800 dark:text-white">Add Client</h3>
            <button onclick="closeClientModal()" class="text-gray-400 hover:text-gray-600">&times;</button>
        </div>
        <form id="clientForm" method="POST" action="client-save.php">
            <input type="hidden" name="id" id="clientId">
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Name *</label>
                <input type="text" name="name" id="clientName" required class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Email</label>
                <input type="email" name="email" id="clientEmail" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Phone</label>
                <input type="text" name="phone" id="clientPhone" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white">
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Address</label>
                <textarea name="address" id="clientAddress" rows="2" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
            </div>
            <div class="grid grid-cols-2 gap-3 mb-3">
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">City</label><input type="text" name="city" id="clientCity" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">State</label><input type="text" name="state" id="clientState" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
            </div>
            <div class="grid grid-cols-2 gap-3 mb-3">
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Postal Code</label><input type="text" name="postal_code" id="clientPostal" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
                <div><label class="block text-gray-700 dark:text-gray-300 mb-1">Country</label><input type="text" name="country" id="clientCountry" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></div>
            </div>
            <div class="mb-3">
                <label class="block text-gray-700 dark:text-gray-300 mb-1">Notes</label>
                <textarea name="notes" id="clientNotes" rows="2" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
            </div>
            <div class="flex justify-end space-x-3 mt-4">
                <button type="button" onclick="closeClientModal()" class="px-4 py-2 border rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">Cancel</button>
                <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Save</button>
            </div>
        </form>
    </div>
</div>

<script>
function openClientModal() {
    document.getElementById('modalTitle').innerText = 'Add Client';
    document.getElementById('clientForm').reset();
    document.getElementById('clientId').value = '';
    document.getElementById('clientModal').classList.remove('hidden');
}
function closeClientModal() {
    document.getElementById('clientModal').classList.add('hidden');
}
function editClient(client) {
    document.getElementById('modalTitle').innerText = 'Edit Client';
    document.getElementById('clientId').value = client.id;
    document.getElementById('clientName').value = client.name;
    document.getElementById('clientEmail').value = client.email || '';
    document.getElementById('clientPhone').value = client.phone || '';
    document.getElementById('clientAddress').value = client.address || '';
    document.getElementById('clientCity').value = client.city || '';
    document.getElementById('clientState').value = client.state || '';
    document.getElementById('clientPostal').value = client.postal_code || '';
    document.getElementById('clientCountry').value = client.country || '';
    document.getElementById('clientNotes').value = client.notes || '';
    document.getElementById('clientModal').classList.remove('hidden');
}
</script>

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