<?php
/**
 * Clients Management Page
 * SSCI Office Platform
 */

// Bootstrap is already loaded from public/index.php

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('clients') . ' - ' . config('app.name');

$action = $_GET['action'] ?? 'list';

require_once __DIR__ . '/../../layouts/header.php';

if ($action === 'list'): ?>

    <div class="animate__animated animate__fadeIn">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-800"><?php echo trans('manage_clients') ?? 'Manage Clients'; ?></h1>
            <a href="?page=clients&action=create" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
                <i class="fas fa-plus"></i> <?php echo trans('add_client') ?? 'Add Client'; ?>
            </a>
        </div>

        <!-- Desktop Table View -->
        <div class="hidden md:block bg-white rounded-lg shadow overflow-hidden">
            <div class="overflow-x-auto">
                <table class="min-w-full">
                    <thead>
                        <tr class="border-b-2 border-gray-200">
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('client_name') ?? 'Client Name'; ?></th>
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('client_email') ?? 'Email'; ?></th>
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('client_phone') ?? 'Phone'; ?></th>
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('company_type') ?? 'Company Type'; ?></th>
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('status') ?? 'Status'; ?></th>
                            <th class="text-left px-6 py-3 text-xs font-semibold text-gray-700 uppercase"><?php echo trans('actions') ?? 'Actions'; ?></th>
                        </tr>
                    </thead>
                <tbody>
                    <?php
                    $clients = $db->fetchAll("SELECT c.*, u.name as created_by_name FROM clients c LEFT JOIN users u ON c.created_by = u.id WHERE c.active = 1 LIMIT 20");
                    foreach ($clients as $client):
                    ?>
                    <tr class="border-b border-gray-200 hover:bg-gray-50">
                        <td class="px-6 py-4 text-sm text-gray-900"><?php echo htmlspecialchars($client['name']); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?php echo htmlspecialchars($client['email'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?php echo htmlspecialchars($client['phone'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm text-gray-600"><?php echo htmlspecialchars($client['company_type'] ?? '-'); ?></td>
                        <td class="px-6 py-4 text-sm">
                            <span class="px-3 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold"><?php echo trans('active') ?? 'Active'; ?></span>
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <a href="?page=clients&action=edit&id=<?php echo $client['id']; ?>" class="text-blue-600 hover:text-blue-800 mr-3">
                                <i class="fas fa-edit"></i> <?php echo trans('edit') ?? 'Edit'; ?>
                            </a>
                            <button onclick="deleteClient(<?php echo $client['id']; ?>)" class="text-red-600 hover:text-red-800">
                                <i class="fas fa-trash"></i> <?php echo trans('delete') ?? 'Delete'; ?>
                            </button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile Card View -->
        <div class="md:hidden space-y-4 pb-20">
            <?php
            $clients = $db->fetchAll("SELECT c.*, u.name as created_by_name FROM clients c LEFT JOIN users u ON c.created_by = u.id WHERE c.active = 1 LIMIT 20");
            foreach ($clients as $client):
            ?>
            <div class="bg-white rounded-lg shadow p-4 border-l-4 border-blue-600">
                <div class="flex justify-between items-start mb-3">
                    <h3 class="text-lg font-bold text-gray-900"><?php echo htmlspecialchars($client['name']); ?></h3>
                    <span class="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs font-semibold"><?php echo trans('active') ?? 'Active'; ?></span>
                </div>
                <div class="space-y-2 text-sm text-gray-600 mb-4">
                    <div><span class="font-semibold text-gray-700">Email:</span> <?php echo htmlspecialchars($client['email'] ?? '-'); ?></div>
                    <div><span class="font-semibold text-gray-700">Phone:</span> <?php echo htmlspecialchars($client['phone'] ?? '-'); ?></div>
                    <div><span class="font-semibold text-gray-700">Type:</span> <?php echo htmlspecialchars($client['company_type'] ?? '-'); ?></div>
                </div>
                <div class="flex gap-2">
                    <a href="?page=clients&action=edit&id=<?php echo $client['id']; ?>" class="flex-1 text-center bg-blue-600 text-white px-3 py-2 rounded-lg hover:bg-blue-700 transition text-sm font-semibold">
                        <i class="fas fa-edit"></i> Edit
                    </a>
                    <button onclick="deleteClient(<?php echo $client['id']; ?>)" class="flex-1 text-center bg-red-600 text-white px-3 py-2 rounded-lg hover:bg-red-700 transition text-sm font-semibold">
                        <i class="fas fa-trash"></i> Delete
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

<?php elseif ($action === 'create' || $action === 'edit'): 
    $client = null;
    if ($action === 'edit' && isset($_GET['id'])) {
        $client = $db->fetch("SELECT * FROM clients WHERE id = ?", [$_GET['id']]);
    }
    
    // Get all user accounts with role = 'client'
    $accounts = $db->fetchAll("SELECT id, name, email, phone, address FROM users WHERE role = 'client' AND active = 1 ORDER BY name");
?>

    <div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl">
        <div class="mb-6">
            <a href="?page=clients" class="text-blue-600 hover:text-blue-800"><i class="fas fa-arrow-left mr-2"></i><?php echo trans('back') ?? 'Back'; ?></a>
            <h1 class="text-2xl sm:text-3xl font-bold text-gray-800 mt-2"><?php echo $action === 'create' ? (trans('add_client') ?? 'Add Client') : (trans('edit_client') ?? 'Edit Client'); ?></h1>
        </div>

        <div class="bg-white rounded-lg shadow">
            <div class="p-8">
                <form id="clientForm" data-draft="clientForm" data-autosave-interval="30000" onsubmit="handleClientSubmit(event, <?php echo $action === 'edit' ? $client['id'] : 'null'; ?>)" class="space-y-8">
                    
                    <!-- Account Selection Section -->
                    <div class="border-b pb-8">
                        <h2 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
                            <i class="fas fa-user-circle text-blue-600 mr-3"></i> <?php echo trans('account_information') ?? 'Account Information'; ?>
                        </h2>
                        
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <!-- Account Dropdown -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-user mr-2 text-blue-600"></i><?php echo trans('select_account') ?? 'Select Account'; ?>
                                </label>
                                <select id="accountSelect" name="account_id" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" onchange="autofillFromAccount(this.value)">
                                    <option value=""><?php echo trans('choose_account') ?? 'Choose an account...'; ?></option>
                                    <?php foreach ($accounts as $account): ?>
                                        <option value="<?php echo $account['id']; ?>" data-email="<?php echo htmlspecialchars($account['email']); ?>" data-phone="<?php echo htmlspecialchars($account['phone']); ?>" data-address="<?php echo htmlspecialchars($account['address']); ?>" data-name="<?php echo htmlspecialchars($account['name']); ?>"><?php echo htmlspecialchars($account['name']); ?> (<?php echo htmlspecialchars($account['email']); ?>)</option>
                                    <?php endforeach; ?>
                                </select>
                                <p class="text-xs text-gray-500 mt-2"><i class="fas fa-info-circle"></i> Selecting an account will auto-fill contact details</p>
                            </div>
                            
                            <!-- Client Name -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-building mr-2 text-blue-600"></i><?php echo trans('client_name') ?? 'Client Name'; ?> *
                                </label>
                                <input type="text" name="name" id="clientName" required class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                       value="<?php echo htmlspecialchars($client['name'] ?? ''); ?>" placeholder="Client company name">
                            </div>

                            <!-- Email -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-envelope mr-2 text-blue-600"></i><?php echo trans('client_email') ?? 'Email'; ?>
                                </label>
                                <input type="email" name="email" id="clientEmail" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                       value="<?php echo htmlspecialchars($client['email'] ?? ''); ?>" placeholder="email@example.com">
                            </div>

                            <!-- Phone -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-phone mr-2 text-blue-600"></i><?php echo trans('client_phone') ?? 'Phone'; ?>
                                </label>
                                <input type="tel" name="phone" id="clientPhone" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                       value="<?php echo htmlspecialchars($client['phone'] ?? ''); ?>" placeholder="+1 (555) 000-0000">
                            </div>

                            <!-- Company Type -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-tag mr-2 text-blue-600"></i><?php echo trans('company_type') ?? 'Company Type'; ?>
                                </label>
                                <select name="company_type" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition">
                                    <option value=""><?php echo trans('select_company_type') ?? 'Select a company type...'; ?></option>
                                    <option value="Bank" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Bank') ? 'selected' : ''; ?>>Bank</option>
                                    <option value="Hospital" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Hospital') ? 'selected' : ''; ?>>Hospital</option>
                                    <option value="School" <?php echo (isset($client['company_type']) && $client['company_type'] === 'School') ? 'selected' : ''; ?>>School</option>
                                    <option value="Government" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Government') ? 'selected' : ''; ?>>Government</option>
                                    <option value="Retail" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Retail') ? 'selected' : ''; ?>>Retail</option>
                                    <option value="Warehouse" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Warehouse') ? 'selected' : ''; ?>>Warehouse</option>
                                    <option value="Manufacturing" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Manufacturing') ? 'selected' : ''; ?>>Manufacturing</option>
                                    <option value="Hotel" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Hotel') ? 'selected' : ''; ?>>Hotel</option>
                                    <option value="Airport" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Airport') ? 'selected' : ''; ?>>Airport</option>
                                    <option value="Port" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Port') ? 'selected' : ''; ?>>Port</option>
                                    <option value="Residential Complex" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Residential Complex') ? 'selected' : ''; ?>>Residential Complex</option>
                                    <option value="Shopping Mall" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Shopping Mall') ? 'selected' : ''; ?>>Shopping Mall</option>
                                    <option value="Office Building" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Office Building') ? 'selected' : ''; ?>>Office Building</option>
                                    <option value="Data Center" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Data Center') ? 'selected' : ''; ?>>Data Center</option>
                                    <option value="Other" <?php echo (isset($client['company_type']) && $client['company_type'] === 'Other') ? 'selected' : ''; ?>>Other</option>
                                </select>
                            </div>

                            <!-- Address -->
                            <div class="md:col-span-2">
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-map-marker-alt mr-2 text-blue-600"></i><?php echo trans('client_address') ?? 'Address'; ?>
                                </label>
                                <textarea name="address" id="clientAddress" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" rows="3" placeholder="Street address, city, state, postal code"><?php echo htmlspecialchars($client['address'] ?? ''); ?></textarea>
                            </div>

                            <!-- Contact Person -->
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">
                                    <i class="fas fa-id-card mr-2 text-blue-600"></i><?php echo trans('contact_person') ?? 'Contact Person'; ?>
                                </label>
                                <input type="text" name="contact_person" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200 transition" 
                                       value="<?php echo htmlspecialchars($client['contact_person'] ?? ''); ?>" placeholder="Primary contact name">
                            </div>
                        </div>
                    </div>

                    <!-- Form Actions -->
                    <div class="flex gap-4 pt-6">
                        <button type="submit" class="bg-gradient-to-r from-blue-600 to-blue-700 text-white px-8 py-3 rounded-lg hover:from-blue-700 hover:to-blue-800 transition font-semibold flex items-center">
                            <i class="fas fa-save mr-2"></i> <?php echo trans('save_client') ?? trans('save') ?? 'Save'; ?>
                        </button>
                        <a href="?page=clients" class="bg-gray-500 text-white px-8 py-3 rounded-lg hover:bg-gray-600 transition font-semibold flex items-center">
                            <i class="fas fa-times mr-2"></i> <?php echo trans('cancel') ?? 'Cancel'; ?>
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

<?php endif;

require_once __DIR__ . '/../../layouts/footer.php'; ?>

<script>
/**
 * Show toast notification using SweetAlert2
 */
function showToast(type, message) {
    const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
    });

    Toast.fire({
        icon: type,
        title: message
    });
}

/**
 * Autofill form fields from selected account
 */
function autofillFromAccount(accountId) {
    if (!accountId) {
        document.getElementById('clientName').value = '';
        document.getElementById('clientEmail').value = '';
        document.getElementById('clientPhone').value = '';
        document.getElementById('clientAddress').value = '';
        return;
    }
    
    const select = document.getElementById('accountSelect');
    const option = select.options[select.selectedIndex];
    
    document.getElementById('clientName').value = option.dataset.name || '';
    document.getElementById('clientEmail').value = option.dataset.email || '';
    document.getElementById('clientPhone').value = option.dataset.phone || '';
    document.getElementById('clientAddress').value = option.dataset.address || '';
    
    console.log('✓ Account details auto-filled');
}

/**
 * Handle client form submission
 */
function handleClientSubmit(event, clientId) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData);
    
    if (!data.name || !data.name.trim()) {
        showToast('error', 'Client name is required');
        return;
    }
    
    const url = clientId ? `api.php?endpoint=clients/update&id=${clientId}` : 'api.php?endpoint=clients/create';
    
    fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(res => {
        // Check if response is actually JSON
        const contentType = res.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            throw new Error('Server returned non-JSON response. Check API endpoint.');
        }
        return res.json();
    })
    .then(result => {
        if (result.success) {
            showToast('success', 'Client saved successfully');
            setTimeout(() => window.location.href = '?page=clients', 1500);
        } else {
            showToast('error', result.error || 'An error occurred');
        }
    })
    .catch(err => {
        console.error('Fetch error:', err);
        showToast('error', 'Error: ' + err.message);
    });
}

/**
 * Delete client with confirmation
 */
function deleteClient(id) {
    if (confirm('Are you sure you want to delete this client?')) {
        fetch(`api.php?endpoint=clients/delete&id=${id}`, { method: 'POST' })
            .then(res => {
                const contentType = res.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    throw new Error('Server returned non-JSON response');
                }
                return res.json();
            })
            .then(data => {
                if (data.success) {
                    showToast('success', 'Client deleted successfully');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast('error', data.error || 'Delete failed');
                }
            })
            .catch(err => {
                console.error('Error:', err);
                showToast('error', 'Error: ' + err.message);
            });
    }
}
</script>
