<?php
/**
 * components/clientDetailsForm.php
 *
 * Client selection dropdown with auto-fill functionality.
 * Replaces modX [[!clientDetailsFORM]] snippet.
 */

// TODO: Replace with proper session-based user authentication
$userId = $_SESSION['user_id'] ?? 1; // Temporary fallback

try {
    // Database connection - TODO: Move to centralized config
    $pdo = new PDO(
        'mysql:host=localhost;dbname=cropmonitor;charset=utf8',
        'cropmonitor',
        'brvnCcaEYxlPCS3',
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    // Prepare and execute query with parameterized statement
    $stmt = $pdo->prepare("SELECT id, client, company, email, address FROM client_records WHERE modx_user_id = ? ORDER BY client ASC");
    $stmt->execute([$userId]);
    $clients = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    // TODO: Proper error logging and user-friendly error display
    error_log("Database error in clientDetailsForm: " . $e->getMessage());
    $clients = [];
}
?>

<div class="form-group">
    <label for="selectUsers" class="form-label">Select Client</label>
    <select id="selectUsers" name="client_id" class="form-control form-control-sm">
        <option value="">Select current client or add new client below...</option>
        <?php foreach ($clients as $client): ?>
            <option value="<?= htmlspecialchars($client['id'], ENT_QUOTES, 'UTF-8') ?>"
                    data-client="<?= htmlspecialchars($client['client'], ENT_QUOTES, 'UTF-8') ?>"
                    data-company="<?= htmlspecialchars($client['company'], ENT_QUOTES, 'UTF-8') ?>"
                    data-email="<?= htmlspecialchars($client['email'], ENT_QUOTES, 'UTF-8') ?>"
                    data-address="<?= htmlspecialchars($client['address'], ENT_QUOTES, 'UTF-8') ?>">
                <?= htmlspecialchars($client['id'] . " - " . $client['client'] . " - " . $client['company'], ENT_QUOTES, 'UTF-8') ?>
            </option>
        <?php endforeach; ?>
        <option value="new" class="text-primary fw-bold">➕ Add New Client...</option>
    </select>
    <div class="form-text">Choose an existing client to auto-fill the form below.</div>
</div>

<script type="text/javascript">
document.getElementById('selectUsers').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    if (!selectedOption.value) {
        // Clear fields if "Select..." is chosen
        clearClientFields();
        return;
    }

    if (selectedOption.value === 'new') {
        // This will be handled by the modal's change event listener
        return;
    }

    const client = selectedOption.getAttribute('data-client') || '';
    const company = selectedOption.getAttribute('data-company') || '';
    const email = selectedOption.getAttribute('data-email') || '';
    const fullAddress = selectedOption.getAttribute('data-address') || '';

    // Parse address components (assuming format: "street, town, state, postcode")
    const addressParts = fullAddress.split(', ');
    const siteAddress = addressParts[0] || '';
    const town = addressParts.slice(1, -2).join(', ') || '';
    const state = addressParts[addressParts.length - 2] || '';
    const postcode = addressParts[addressParts.length - 1] || '';

    // Fill form fields
    const nameField = document.getElementById('name');
    const companyField = document.getElementById('company');
    const emailField = document.getElementById('email');
    const siteAddressField = document.getElementById('site_address');
    const postalAddressField = document.getElementById('postal_address');

    if (nameField) nameField.value = client;
    if (companyField) companyField.value = company;
    if (emailField) emailField.value = email;
    if (siteAddressField) siteAddressField.value = siteAddress;
    if (postalAddressField) postalAddressField.value = town + (town && (state || postcode) ? ', ' : '') + state + (state && postcode ? ', ' : '') + postcode;
});

// Function to add new client to dropdown
function addClientToDropdown(clientData) {
    const select = document.getElementById('selectUsers');
    const option = document.createElement('option');
    option.value = clientData.id;
    option.setAttribute('data-client', clientData.name);
    option.setAttribute('data-company', clientData.company);
    option.setAttribute('data-email', clientData.email);
    option.setAttribute('data-address', clientData.address);
    option.textContent = clientData.id + ' - ' + clientData.name + ' - ' + clientData.company;

    // Insert before the "Add New Client" option
    const addNewOption = select.querySelector('option[value="new"]');
    select.insertBefore(option, addNewOption);

    // Select the new client
    select.value = clientData.id;
    select.dispatchEvent(new Event('change'));
}

// Make function globally available for the modal
window.addClientToDropdown = addClientToDropdown;

function clearClientFields() {
    const fields = ['name', 'company', 'email', 'site_address', 'postal_address'];
    fields.forEach(fieldId => {
        const field = document.getElementById(fieldId);
        if (field) field.value = '';
    });
}
</script>