<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <!-- ============================================================ -->
    <!-- Page 11 Public Signing Form                                   -->
    <!-- ============================================================ -->
    <template id="portal_page11_public_sign" name="Page 11 - Sign">
        <t t-call="portal.frontend_layout">
            <div class="container py-4" style="max-width:720px;">
                <div class="text-center mb-4">
                    <t t-if="company.logo">
                        <img t-att-src="'/web/image/res.company/%s/logo/200x60' % company.id"
                             alt="Company Logo" style="max-height:60px;" class="mb-2"/>
                    </t>
                    <h3 class="mb-1">ADP Consent and Declaration</h3>
                    <p class="text-muted">Page 11 - Assistive Devices Program</p>
                </div>

                <t t-if="request.params.get('error') == 'no_signature'">
                    <div class="alert alert-danger">Please draw your signature before submitting.</div>
                </t>
                <t t-if="request.params.get('error') == 'no_consent'">
                    <div class="alert alert-danger">You must accept the consent declaration before signing.</div>
                </t>

                <!-- Consent Declaration -->
                <form method="POST" t-att-action="'/page11/sign/%s/submit' % token" id="page11Form">
                    <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/>

                    <!-- Applicant Information -->
                    <div class="card mb-3">
                        <div class="card-header"><strong>Applicant Information</strong></div>
                        <div class="card-body">
                            <div class="row mb-2">
                                <div class="col-sm-4">
                                    <label class="form-label">Last Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="client_last_name"
                                           t-att-value="client_last_name or ''" required="required"/>
                                </div>
                                <div class="col-sm-4">
                                    <label class="form-label">First Name <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="client_first_name"
                                           t-att-value="client_first_name or ''" required="required"/>
                                </div>
                                <div class="col-sm-4">
                                    <label class="form-label">Middle Name</label>
                                    <input type="text" class="form-control" name="client_middle_name"
                                           t-att-value="client_middle_name or ''"/>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-sm-6">
                                    <label class="form-label">Health Card Number (10 digits) <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="client_health_card"
                                           t-att-value="client_health_card or ''" required="required"
                                           maxlength="10" pattern="[0-9]{10}" title="10-digit health card number"
                                           placeholder="e.g. 1234567890"/>
                                </div>
                                <div class="col-sm-3">
                                    <label class="form-label">Version <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" name="client_health_card_version"
                                           t-att-value="client_health_card_version or ''" required="required"
                                           maxlength="2" placeholder="e.g. AB"/>
                                </div>
                                <div class="col-sm-3">
                                    <label class="form-label">Case Ref</label>
                                    <input type="text" class="form-control" readonly="readonly"
                                           t-att-value="order.name"/>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card mb-3">
                        <div class="card-header"><strong>Consent and Declaration</strong></div>
                        <div class="card-body">
                            <p class="small">
                                I consent to information being collected and used by the Ministry of Health and Long-Term Care,
                                and agents authorized by the Ministry, for the administration and enforcement of the
                                Assistive Devices Program. I understand this consent is voluntary and I may withdraw it
                                at any time. I declare that the information in this application is true and complete.
                            </p>
                            <div class="form-check mb-3">
                                <input type="checkbox" class="form-check-input" id="consent_declaration"
                                       name="consent_declaration" required="required"/>
                                <label class="form-check-label" for="consent_declaration">
                                    <strong>I have read and accept the above declaration.</strong>
                                </label>
                            </div>

                            <div class="mb-3">
                                <label for="signer_type" class="form-label"><strong>I am signing as:</strong></label>
                                <select class="form-select" id="signer_type" name="signer_type" required="required"
                                        onchange="toggleAgentFields()">
                                    <option value="client" t-att-selected="signer_type == 'client' and 'selected'">Applicant (Client - Self)</option>
                                    <option value="spouse" t-att-selected="signer_type == 'spouse' and 'selected'">Spouse</option>
                                    <option value="parent" t-att-selected="signer_type == 'parent' and 'selected'">Parent</option>
                                    <option value="legal_guardian" t-att-selected="signer_type == 'legal_guardian' and 'selected'">Legal Guardian</option>
                                    <option value="poa" t-att-selected="signer_type == 'poa' and 'selected'">Power of Attorney</option>
                                    <option value="public_trustee" t-att-selected="signer_type == 'public_trustee' and 'selected'">Public Trustee</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label for="signer_name" class="form-label">Full Name</label>
                                <input type="text" class="form-control" id="signer_name" name="signer_name"
                                       t-att-value="sign_request.signer_name or ''" required="required"/>
                            </div>
                        </div>
                    </div>

                    <!-- Agent Details (shown/hidden via JS based on signer type selection) -->
                    <div class="card mb-3" id="agent_details_card" t-att-style="'' if is_agent else 'display:none;'">
                        <div class="card-header"><strong>Agent Details</strong></div>
                        <div class="card-body">
                            <div class="row mb-2">
                                <div class="col-sm-5">
                                    <label class="form-label">Last Name</label>
                                    <input type="text" class="form-control agent-field" name="agent_last_name"/>
                                </div>
                                <div class="col-sm-5">
                                    <label class="form-label">First Name</label>
                                    <input type="text" class="form-control agent-field" name="agent_first_name"/>
                                </div>
                                <div class="col-sm-2">
                                    <label class="form-label">M.I.</label>
                                    <input type="text" class="form-control" name="agent_middle_initial"
                                           maxlength="2" placeholder="M"/>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-sm-6">
                                    <label class="form-label">Home Phone</label>
                                    <input type="tel" class="form-control" name="agent_phone"/>
                                </div>
                                <div class="col-sm-6">
                                    <label class="form-label">Business Phone</label>
                                    <input type="tel" class="form-control" name="agent_business_phone"/>
                                </div>
                            </div>
                            <div class="mb-2">
                                <label class="form-label">Search Address</label>
                                <input type="text" class="form-control" id="agent_street_search"
                                       placeholder="Start typing an address..." autocomplete="off"/>
                            </div>
                            <div class="row mb-2">
                                <div class="col-sm-3">
                                    <label class="form-label">Unit #</label>
                                    <input type="text" class="form-control" name="agent_unit" id="agent_unit"/>
                                </div>
                                <div class="col-sm-3">
                                    <label class="form-label">Street #</label>
                                    <input type="text" class="form-control" name="agent_street_number" id="agent_street_number"/>
                                </div>
                                <div class="col-sm-6">
                                    <label class="form-label">Street Name</label>
                                    <input type="text" class="form-control" name="agent_street" id="agent_street"/>
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-sm-5">
                                    <label class="form-label">City/Town</label>
                                    <input type="text" class="form-control" name="agent_city" id="agent_city"/>
                                </div>
                                <div class="col-sm-4">
                                    <label class="form-label">Province</label>
                                    <input type="text" class="form-control" name="agent_province" id="agent_province" value="Ontario"/>
                                </div>
                                <div class="col-sm-3">
                                    <label class="form-label">Postal Code</label>
                                    <input type="text" class="form-control" name="agent_postal_code" id="agent_postal_code"/>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Signature Pad -->
                    <div class="card mb-3">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <strong>Signature</strong>
                            <button type="button" class="btn btn-sm btn-outline-secondary" onclick="clearSignature()">Clear</button>
                        </div>
                        <div class="card-body p-2">
                            <canvas id="signature-canvas" width="660" height="200"
                                    style="border:1px dashed rgba(128,128,128,0.35);border-radius:6px;width:100%;touch-action:none;cursor:crosshair;">
                            </canvas>
                            <input type="hidden" name="signature_data" id="signature_data"/>
                        </div>
                    </div>

                    <div class="text-center mb-4">
                        <button type="submit" class="btn btn-primary btn-lg px-5" onclick="return prepareSubmit()">
                            Submit Signature
                        </button>
                    </div>
                </form>

                <p class="text-center text-muted small">
                    <t t-out="company.name"/> &amp;middot;
                    <t t-if="company.phone"><t t-out="company.phone"/> &amp;middot; </t>
                    <t t-if="company.email"><t t-out="company.email"/></t>
                </p>
            </div>

            <script type="text/javascript">
                function toggleAgentFields() {
                    var sel = document.getElementById('signer_type');
                    var card = document.getElementById('agent_details_card');
                    var agentFields = card ? card.querySelectorAll('.agent-field') : [];
                    var isAgent = sel.value !== 'client';
                    if (card) card.style.display = isAgent ? '' : 'none';
                    agentFields.forEach(function(f) {
                        if (isAgent) { f.setAttribute('required', 'required'); }
                        else { f.removeAttribute('required'); f.value = ''; }
                    });
                }
                document.addEventListener('DOMContentLoaded', toggleAgentFields);
            </script>
            <script type="text/javascript">
                (function() {
                    var canvas = document.getElementById('signature-canvas');
                    if (!canvas) return;
                    var ctx = canvas.getContext('2d');
                    var drawing = false;
                    var lastX = 0, lastY = 0;
                    var hasDrawn = false;

                    function resizeCanvas() {
                        var rect = canvas.getBoundingClientRect();
                        var dpr = window.devicePixelRatio || 1;
                        canvas.width = rect.width * dpr;
                        canvas.height = rect.height * dpr;
                        ctx.scale(dpr, dpr);
                        ctx.strokeStyle = '#000';
                        ctx.lineWidth = 2;
                        ctx.lineCap = 'round';
                        ctx.lineJoin = 'round';
                    }

                    resizeCanvas();

                    function getPos(e) {
                        var rect = canvas.getBoundingClientRect();
                        var touch = e.touches ? e.touches[0] : e;
                        return {
                            x: touch.clientX - rect.left,
                            y: touch.clientY - rect.top
                        };
                    }

                    function startDraw(e) {
                        e.preventDefault();
                        drawing = true;
                        var pos = getPos(e);
                        lastX = pos.x;
                        lastY = pos.y;
                    }

                    function draw(e) {
                        if (!drawing) return;
                        e.preventDefault();
                        var pos = getPos(e);
                        ctx.beginPath();
                        ctx.moveTo(lastX, lastY);
                        ctx.lineTo(pos.x, pos.y);
                        ctx.stroke();
                        lastX = pos.x;
                        lastY = pos.y;
                        hasDrawn = true;
                    }

                    function stopDraw(e) {
                        if (e) e.preventDefault();
                        drawing = false;
                    }

                    canvas.addEventListener('mousedown', startDraw);
                    canvas.addEventListener('mousemove', draw);
                    canvas.addEventListener('mouseup', stopDraw);
                    canvas.addEventListener('mouseleave', stopDraw);
                    canvas.addEventListener('touchstart', startDraw, {passive: false});
                    canvas.addEventListener('touchmove', draw, {passive: false});
                    canvas.addEventListener('touchend', stopDraw, {passive: false});

                    window.clearSignature = function() {
                        var dpr = window.devicePixelRatio || 1;
                        ctx.clearRect(0, 0, canvas.width / dpr, canvas.height / dpr);
                        hasDrawn = false;
                        document.getElementById('signature_data').value = '';
                    };

                    window.prepareSubmit = function() {
                        if (!hasDrawn) {
                            alert('Please draw your signature before submitting.');
                            return false;
                        }
                        var dataUrl = canvas.toDataURL('image/png');
                        document.getElementById('signature_data').value = dataUrl;
                        return true;
                    };
                })();
            </script>
            <t t-if="google_maps_api_key">
                <script t-attf-src="https://maps.googleapis.com/maps/api/js?key=#{google_maps_api_key}&amp;libraries=places&amp;callback=initPage11AddressAutocomplete" async="async" defer="defer"></script>
                <script type="text/javascript">
                    function initPage11AddressAutocomplete() {
                        var searchInput = document.getElementById('agent_street_search');
                        if (!searchInput) return;
                        var autocomplete = new google.maps.places.Autocomplete(searchInput, {
                            types: ['address'],
                            componentRestrictions: { country: 'ca' }
                        });
                        autocomplete.setFields(['address_components', 'formatted_address']);
                        autocomplete.addListener('place_changed', function() {
                            var place = autocomplete.getPlace();
                            if (!place || !place.address_components) return;
                            var street_number = '', route = '', city = '', province = '', postal = '', unit = '';
                            place.address_components.forEach(function(c) {
                                var t = c.types;
                                if (t.indexOf('street_number') >= 0) street_number = c.long_name;
                                else if (t.indexOf('route') >= 0) route = c.long_name;
                                else if (t.indexOf('locality') >= 0) city = c.long_name;
                                else if (t.indexOf('sublocality') >= 0 &amp;&amp; !city) city = c.long_name;
                                else if (t.indexOf('administrative_area_level_1') >= 0) province = c.long_name;
                                else if (t.indexOf('postal_code') >= 0) postal = c.long_name;
                                else if (t.indexOf('subpremise') >= 0) unit = c.long_name;
                            });
                            document.getElementById('agent_street_number').value = street_number;
                            document.getElementById('agent_street').value = route;
                            document.getElementById('agent_city').value = city;
                            document.getElementById('agent_province').value = province;
                            document.getElementById('agent_postal_code').value = postal;
                            if (unit) document.getElementById('agent_unit').value = unit;
                        });
                    }
                </script>
            </t>
        </t>
    </template>

    <!-- ============================================================ -->
    <!-- Success Page                                                  -->
    <!-- ============================================================ -->
    <template id="portal_page11_sign_success" name="Page 11 - Signed Successfully">
        <t t-call="portal.frontend_layout">
            <div class="container py-5" style="max-width:600px;">
                <div class="text-center">
                    <div class="mb-4">
                        <i class="fa fa-check-circle text-success" style="font-size:64px;"/>
                    </div>
                    <h3>Signature Submitted Successfully</h3>
                    <p class="text-muted mt-3">
                        Thank you for signing the ADP Consent and Declaration form.
                        Your signature has been recorded and the document has been updated.
                    </p>
                    <t t-if="sign_request and sign_request.sale_order_id">
                        <p class="text-muted">
                            Case Reference: <strong><t t-out="sign_request.sale_order_id.name"/></strong>
                        </p>
                    </t>
                    <t t-if="sign_request and sign_request.signed_pdf and token">
                        <a t-attf-href="/page11/sign/#{token}/download"
                           class="btn btn-outline-primary mt-3">
                            <i class="fa fa-download"/> Download Signed PDF
                        </a>
                    </t>
                    <p class="text-muted mt-4 small">You may close this window.</p>
                </div>
            </div>
        </t>
    </template>

    <!-- ============================================================ -->
    <!-- Expired / Cancelled Page                                      -->
    <!-- ============================================================ -->
    <template id="portal_page11_sign_expired" name="Page 11 - Link Expired">
        <t t-call="portal.frontend_layout">
            <div class="container py-5" style="max-width:600px;">
                <div class="text-center">
                    <div class="mb-4">
                        <i class="fa fa-clock-o text-warning" style="font-size:64px;"/>
                    </div>
                    <h3>Signing Link Expired</h3>
                    <p class="text-muted mt-3">
                        This signing link is no longer valid. It may have expired or been cancelled.
                    </p>
                    <p class="text-muted">
                        Please contact the office to request a new signing link.
                    </p>
                </div>
            </div>
        </t>
    </template>

    <!-- ============================================================ -->
    <!-- Invalid / Not Found Page                                      -->
    <!-- ============================================================ -->
    <template id="portal_page11_sign_invalid" name="Page 11 - Invalid Link">
        <t t-call="portal.frontend_layout">
            <div class="container py-5" style="max-width:600px;">
                <div class="text-center">
                    <div class="mb-4">
                        <i class="fa fa-exclamation-triangle text-danger" style="font-size:64px;"/>
                    </div>
                    <h3>Invalid Link</h3>
                    <p class="text-muted mt-3">
                        This signing link is not valid. Please check that you are using the correct link
                        from the email you received.
                    </p>
                </div>
            </div>
        </t>
    </template>
</odoo>
