<!-- Modal -->
<div class="modal fade" id="sendContractModal" tabindex="-1" aria-labelledby="sendContractModalLabel" aria-hidden="false">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <!-- Modal Header -->
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="sendContractModalLabel">Contract Mail Preview</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <!-- Modal Body -->
            <div class="modal-body">
                <div class="row">
                    <!-- Left Side: Mail Form -->
                    <div class="col-md-8">
                        <ul class="nav nav-tabs" id="contractTabs">
                            <li class="nav-item">
                                <a class="nav-link active" id="mail-tab" data-bs-toggle="tab" href="#mailContent">Mail</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" id="pdf-tab" data-bs-toggle="tab" href="#pdfContent">PDF</a>
                            </li>
                        </ul>

                        <div class="tab-content mt-3">
                            <div class="tab-pane fade show active" id="mailContent">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Subject</label>
                                    <input type="text" name="subject" id="emailSubject" class="form-control px-3 py-2 mt-1 border border-gray-300 rounded-md shadow-sm">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label fw-bold">Mail Body</label>
                                    <textarea id="emailBody" name="body" class="form-control shadow-sm px-3 py-2 mt-1 border border-gray-300 rounded-md"></textarea>
                                </div>
                            </div>

                            <div class="tab-pane fade" id="pdfContent">
                                <div class="mb-3">
                                    <label class="form-label fw-bold">Title</label>
                                    <input type="text" id="title" name="title" class="form-control shadow-sm px-3 py-2 mt-1 border border-gray-300 rounded-md ">
                                </div>

                                <div class="mb-3">
                                    <label class="form-label fw-bold">PDF Body</label>
                                    <textarea id="pdfBody" name="pdf" class="form-control shadow-sm px-3 py-2 mt-1 border border-gray-300 rounded-md "></textarea>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label class="form-label fw-bold">Email</label>
                                <input type="email" name="email" id="emailAddress" class="form-control shadow-sm px-3 py-2 mt-1 border border-gray-300 rounded-md">
                            </div>

                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" id="scheduleEmail">
                                <label class="form-check-label" for="scheduleEmail">Schedule Email</label>
                            </div>
                        </div>
                    </div>

                    <!-- Right Side: Sidebar Details -->
                    <div class="col-md-4">
                        <div class="p-3 bg-light rounded shadow-sm">
                            <h6 class="fw-bold border-bottom pb-2">Guide Details</h6>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.first_name + ' ' + guideData.last_name)">English Name: <strong id="name" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.japanese_name)">Japanese Name: <strong id="jap_name" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.phone)">Phone Number: <strong id="phone_no" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.email)">Email: <strong id="email" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.dob)">Birthdate: <strong id="dob" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.gender)">Gender: <strong id="gender" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.region?.eng_name)">Region: <strong id="region" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.prefecture?.eng_name)">Prefecture: <strong id="prefecture" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.city?.eng_name)">City: <strong id="city" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertDetail(guideData.starting_rate)">Start Rate: <strong id="start_rate" class="fw-bold "></strong></button>
                            <button class="btn btn-outline-primary btn-sm w-100 mt-2" onclick="insertGuideFeeTable()">Guide Fee Table</button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Modal Footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success">Send Contract</button>
            </div>
        </div>
    </div>
</div>

<!-- JavaScript -->
<script src="https://cdn.ckeditor.com/4.22.1/standard/ckeditor.js"></script>
<script>
    let emailBodyEditor;
    let pdfBodyEditor;

    document.addEventListener("DOMContentLoaded", function () {
        emailBodyEditor = CKEDITOR.replace('emailBody', {
            height: 200
        });

        document.getElementById("mail-tab").addEventListener("click", function () {
            if (!emailBodyEditor) {
                emailBodyEditor = CKEDITOR.replace('emailBody', { height: 200 });
            }
        });

        document.getElementById("pdf-tab").addEventListener("click", function () {
            if (!pdfBodyEditor) {
                pdfBodyEditor = CKEDITOR.replace('pdfBody', { height: 100 });
            }
    });
    });


    window.guideData = {};

    function populateModal(guide) {
        if (!guide) {
            console.error("Guide data is missing!");
            return;
        }
        window.guideData = guide;
        document.getElementById("name").innerText = guide.first_name + ' ' + guide.last_name || '';
        document.getElementById("jap_name").innerText = guide.japanese_name || '';
        document.getElementById("phone_no").innerText = guide.phone || '';
        document.getElementById("dob").innerText = guide.dob || '';
        document.getElementById("email").innerText = guide.email || '';
        document.getElementById("gender").innerText = guide.gender || '';
        document.getElementById("region").innerText = guide.region?.eng_name || '';
        document.getElementById("prefecture").innerText = guide.prefecture?.eng_name || '';
        document.getElementById("city").innerText = guide.city?.eng_name || '';
        document.getElementById("start_rate").innerText = guide.starting_rate|| '';
        document.getElementById("emailAddress").value = guide.email || '';
        // Email Body
        if (!emailBodyEditor) {
            emailBodyEditor = CKEDITOR.replace('emailBody', { height: 200 });
        }
        document.getElementById("emailSubject").value = '(株)ジャパン・アウェイツのご案内と業務委託契約について';
        let fees = typeof guide.guide_fee === "string" ? JSON.parse(guide.guide_fee) : guide.guide_fee;
        let categories = [
            { label: "1 - 6 people", keys: ["1", "101", "201"] },
            { label: "7 - 15 people", keys: ["301", "401", "501"] },
            { label: "16 - 27 people", keys: ["601", "701", "801"] },
            { label: "28+ people", keys: ["901", "1001", "1101"] }
        ];
        let table = document.createElement("table");
        table.style.borderCollapse = "collapse";
        table.style.width = "100%";
        table.border = "1";
        let thead = document.createElement("thead");
        thead.innerHTML = `
            <tr style="background-color: #4CAF50; color: white;">
                <th style="padding: 8px; border: 1px solid #ddd;"># of People</th>
                <th style="padding: 8px; border: 1px solid #ddd;">7 - 8+ hours</th>
                <th style="padding: 8px; border: 1px solid #ddd;">5 - 6 hours</th>
                <th style="padding: 8px; border: 1px solid #ddd;">1 - 4 hours</th>
            </tr>
        `;
        table.appendChild(thead);

        let tbody = document.createElement("tbody");

        categories.forEach(category => {
            let row = document.createElement("tr");
            row.innerHTML = `
            <td style="padding: 8px; border: 1px solid #ddd; background-color: #c8e6c9;">${category.label}</td>
            <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[0]] ?? '-'}</td>
            <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[1]] ?? '-'}</td>
            <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[2]] ?? '-'}</td>
            `;
            tbody.appendChild(row);
        });

        table.appendChild(tbody);

        let emailContent = `
            <p>${guide.japanese_name} 様</p>

            <p>株式会社ジャパンアウェイツの渋谷と申します。</p>

            <p>この度は弊社へのご登録ありがとうございます。</p>

            <p>今後のご案内として、以下のお手続きをお願いいたします。</p>

            <h3>I. 業務委託契約の取り交わし</h3>

            <p>相互理解と円滑な業務遂行のため、業務委託契約書をお読みいただき、ご署名をお願いいたします。</p>
            <p>契約書はこちらでご確認いただけます： <a href="#">契約書へのリンク</a></p>
            <p>契約内容をご確認いただき、ご同意いただけましたら、以下のお手続きをお願いいたします。</p>

            <ol>
                <li>1.個人情報欄のご入力。</li>
                <li>2.マウスまたはタッチスクリーンを使って「Sign here」ボックス内にご署名。</li>
                <li>3.Submitをクリックします。</li>
            </ol>

           <p style="color: red;"><strong>※ご署名の前にご不明な点がございましたら、お気軽に直接メールにてお問い合わせください。</strong></p>

             <h3>II. 銀行口座情報</h3>
            <p>今後のお支払いを進めるため、以下の情報をご提供ください。</p>
            <ul>
                <li>銀行名（国内のみ）</li>
                <li>支店名</li>
                <li>口座の種類</li>
                <li>口座番号</li>
                <li>口座名義</li>
            </ul>
            <h3>III. 次の手順</h3>
                <p>ご署名いただいた契約書を受領後、契約記録用に印刷した控えと、ゲストとの交流に必要な資材</p>
                <p>サインボード、レビューカード、トートバッグ、小旗を含むスターターパックを郵送いたします。</p>
                <p>契約終了の際には、これらの資料をご返却ください。</p>
                <p>契約締結後、担当のブッキングマネージャーよりツアー依頼の送信や顧客情報の提供をさせていただきます。</p>

            <h3>IV.通訳案内士業務のためのガイドライン</h3>
            <p>以下の点にご注意ください。</p>
            <ul>
                <li>守秘義務： 当社製品に関する情報を他社と共有したり、個人的に使用することはご遠慮ください。</li>
                <li>ゲストとのやりとり： ジャパン・アウェイツの代表としてゲストと接してください。</li>
                <li>レビュー投稿のお願い：各ツアーの終了時、ゲストにレビューカードを配布しレビューを書くようお勧めしてください。※1グループにつきカード1枚</li>
                <li>レビューカードやその他の資料については、リクエストフォームにて追加のご請求が可能です。</li>
            </ul>
            <h3>V. キャンセル規定</h3>
            <p>お客様のご都合によるキャンセルの場合、ガイド料金は以下の通りお支払いいたします。</p>
            <ul>
                <li><strong>1日前：</strong> 100％のガイド料</li>
                <li><strong>2日前：</strong> 50％のガイド料</li>
                <li><strong>3日前：</strong> 25％のガイド料</li>
                <li><strong>4日以上前：</strong> ガイド料支払いなし</li>
            </ul>
            <p>※不可抗力の場合は例外となります。</p>
            <h3>VI. 支払い方法とガイド料</h3>
            <p>ガイド料は月2回お支払いいたします。</p>
            <li>毎月1日から15日のツアーの場合： 月末までにお支払いいたします。</li>
            <li>16日から月末までのツアー：月末締め翌月15日までにお支払いいたします。</li>
            <p>FITツアーのガイド料はブッキングマネージャーよりご提供する場所、ツアー時間、人数に基づいて設定されます。FITツアーのスタート料金は、下記の表をご参照ください。</p>

        `;

        emailContent += table.outerHTML;

        emailContent += `
            <p>固定ツアーの場合、ガイド料は固定となります。</p>

            <h3>VII. 経費報告</h3>
            <p>ツアー終了後72時間以内にツアーレポートにて経費を申請してください。</p>

            <h4>公共交通機関の場合</h4>
            <ul>
                <li>交通費の明細として、ナビゲーションシステム <a href="https://transit.yahoo.co.jp/promo/app">（GoogleマップやYahoo！乗換案内など）</a>のスクリーンショットを提出してください。</li>
                <li>ご自宅から目的地までの交通費は当社が負担いたします（ツアー説明書に記載の上限額まで）。</li>
                <li>交通費が上限額を超える場合は、事前に予約担当者にご相談の上、承認を得てください。（<a href="mailto:booking@japanawaits.com">booking@japanawaits.com</a>までご連絡ください）</li>
            </ul>

            <h4>自家用車利用の場合</h4>
            <ul>
                <li>Yahoo！カーナビアプリでガソリン代と通行料を計算</li>
                <li>ルート検索画面でガソリン代と通行料金を計算したスクリーンショットを提出</li>
                <li>駐車料金の領収書をツアーレポートにて提出</li>
                <li>交通費の精算額は、ツアー説明書に記載された上限額まで</li>
            </ul>

            <h3>VIII. 領収書の郵送先</h3>
            <p>経費（自宅からの交通費を除く）の領収書原本は、下記の期日までにご郵送ください。</p>

            <ul>
                <li>前年12月1日～本年5月31日までのツアー：5月31日まで</li>
                <li>6月1日～11月30日までのツアー：11月30日まで</li>
            </ul>

            <p><strong>領収書の郵送先：</strong></p>
            <address>
                〒220-0051<br>
                神奈川県横浜市西区中央1-28-13-707<br>
                (株)ジャパン・アウェイツ
            </address>

            <p>最後までお読みいただき、感謝申し上げます。</p>
            <p>ご不明な点がございましたら、ご遠慮なくお問い合わせください。</p>

            <p>どうぞ引き続きよろしくお願いします。</p>

            <p>株式会社ジャパン・アウェイツ</p>
            <p>渋谷かおり</p>
        `;

        emailBodyEditor.setData(emailContent);

        // PDF Body
        if (!pdfBodyEditor) {
            pdfBodyEditor = CKEDITOR.replace('pdfBody', { height: 100 });
        }
        document.getElementById("title").value = 'Agreement and Next Steps – Japan Awaits';
        let PdfContent = `
            <p>Dear ${guide.first_name} ${guide.last_name},</p>

            <p>Thank you for your interest in joining Japan Awaits. I'm Kaori Shibuya from Japan Awaits Co., Ltd., and we're excited to welcome you to our team. To move forward, we just need you to complete a few simple steps.</p>

            <h3>I. Service Contract Agreement</h3>
            <p>To ensure mutual understanding and smooth operations, we kindly ask you to read and sign our service agreement.</p>
            <p>You can review the agreement here: <a href="#">契約書へのリンク</a></p>
            <p>Once you’ve reviewed and agreed to the terms, please follow these steps:</p>

            <ul>
                <li>Complete the personal information section.</li>
                <li>Sign using your mouse or touchscreen in the "Sign here" box.</li>
                <li>Click "Submit." If you have any questions prior to signing, please feel free to email me directly.</li>
            </ul>

            <h3>II. Bank Details</h3>
            <p>To process future payments, please provide the following information:</p>

            <ul>
                <li>Bank Name (domestic only)</li>
                <li>Branch Name</li>
                <li>Account Type</li>
                <li>Account Number</li>
                <li>Account Holder’s Name</li>
            </ul>

            <h3>III. Next Steps</h3>
            <p>After we receive your signed contract, we will send you a printed copy by mail for your records, along with a starter pack containing materials for guest interactions (e.g., signboards, review cards, tote bag, and small flag). In the event of contract termination, we kindly ask that these items be returned.</p>
            <p>Once the agreement is signed, the Booking Manager will be able to send tour requests and provide customer details.</p>

            <h3>IV. Guidelines for Guiding Services</h3>
            <ul>
                <li><strong>Confidentiality:</strong> Refrain from sharing information about our products with other companies or using it personally.</li>
                <li><strong>Guest Interaction:</strong> Kindly interact with guests as a representative of Japan Awaits.</li>
                <li><strong>Review Submissions:</strong> At the end of each tour, provide review cards to guests (one review card per group) and encourage them to write a review. Additional review cards or other materials can be requested in our Request Form.</li>
            </ul>

            <h3>V. Cancellation Policy</h3>
            <p>In case of cancellation from the guests, the guide fee will be paid as follows:</p>

            <ul>
                <li>1 day notice: 100% guide fee</li>
                <li>2 days notice: 50% guide fee</li>
                <li>3 days notice: 25% guide fee</li>
                <li>4 days or more notice: No guide fee</li>
            </ul>

            <p>Exceptions may apply in cases of force majeure.</p>

            <h3>VI. Payment Schedule and Guide Fees</h3>
            <p>Guide fees are paid twice a month:</p>

            <ul>
                <li>For tours from the 1st to 15th of the month: Payment at the end of the month</li>
                <li>For tours from the 16th to end of the month: Payment by the 15th of the following month</li>
            </ul>

            <p>Starting rates for FIT tours are included in the original email, with rates based on location, duration, number of guests as provided by the Booking Manager. For fixed tours, the guide fee is fixed.</p>

            <h3>VII. Expense Reporting</h3>
            <p>Please submit your tour expenses in the Tour Report within 72 hours after the completion of the tour. Please see below on how to report transportation expenses based on the method used:</p>

            <h4>For Public Transportation:</h4>
            <ul>
                <li>Provide a screenshot of the navigation system (such as <a href="https://transit.yahoo.co.jp/promo/app">Google Maps or Yahoo!乗換案内</a>) as proof of transportation expense.</li>
                <li>We will cover the cost of transport from your home to the destination (up to the maximum amount stated in the Tour Instructions). If the transportation expense should exceed the maximum amount, please consult the Booking Manager for approval in advance (<a href="mailto:booking@japanawaits.com">booking@japanawaits.com</a>).</li>
                <li>Include details of the departure and arrival destinations and the total expense amount on the Tour Report.</li>
            </ul>

            <h4>For Private Car Usage:</h4>
            <ul>
                <li>Use the Yahoo! Carnavi app to calculate petrol and toll charges (you must indicate your car type on the app prior to usage).</li>
                <li>Provide a screenshot of the petrol and toll calculation on the navigation system.</li>
                <li>Submit receipts in the Tour Report for parking fees.</li>
                <li>Please note that we do not provide car insurance or cover any accidents.</li>
                <li>The reimbursement amount is up to the maximum stated in the Tour Instructions. If the transportation expense should exceed the maximum amount, please consult the Booking Manager for approval in advance (<a href="mailto:booking@japanawaits.com">booking@japanawaits.com</a>).</li>
            </ul>

            <p>After verifying your Tour Report, we will send a payment slip by your next payment cycle via email. If no response is received within two weeks, we will process payment based on the slip without the right to refusal.</p>

            <h3>VIII. Mailing Address for Receipts</h3>
            <p>Please send original receipts for expenses (except for transportation expenses) by the following dates:</p>

            <ul>
                <li>May 31st for tours that took place from December 1st of the previous year to May 31st of this year</li>
                <li>November 30th for tours that took place from June 1st to November 30th of this year</li>
            </ul>

            <p><strong>Mail receipts to:</strong></p>

            <h4>In English:</h4>
            <address>
                Japan Awaits Co., Ltd.<br>
                1-28-13-707 Chuo, Nishi-ku, Yokohama-shi, Kanagawa 〒220-0051
            </address>

            <h4>In Japanese:</h4>
            <address>
                〒220-0051<br>
                神奈川県横浜市西区中央1-28-13-707<br>
                (株)ジャパン・アウェイツ
            </address>

            <p>If you have any questions, please don’t hesitate to contact us.</p>
            <p>Thank you for your consideration, and we look forward to working with you!</p>

            <p>Best regards,</p>
            <p>Kaori Shibuya</p>
            <p>Japan Awaits Co., Ltd.</p>

        `;
        pdfBodyEditor.setData(PdfContent);
    }

    function insertDetail(value) {
        let activeTab = document.querySelector(".nav-link.active").id;
        if (activeTab === "mail-tab" && emailBodyEditor) {
            emailBodyEditor.insertText(value + " ");
        } else if (activeTab === "pdf-tab" && pdfBodyEditor) {
            pdfBodyEditor.insertText(value + " ");
        }
    }

    function insertGuideFeeTable() {
        if (!guideData || !guideData.guide_fee) {
            console.error("Guide fee data is missing!");
            return;
        }
        if (!emailBodyEditor) {
            console.error("Email editor is not initialized yet!");
            return;
        }

        let fees = typeof guideData.guide_fee === "string" ? JSON.parse(guideData.guide_fee) : guideData.guide_fee;

        let categories = [
            { label: "1 - 6 people", keys: ["1", "101", "201"] },
            { label: "7 - 15 people", keys: ["301", "401", "501"] },
            { label: "16 - 27 people", keys: ["601", "701", "801"] },
            { label: "28+ people", keys: ["901", "1001", "1101"] }
        ];

        let table = document.createElement("table");
        table.style.borderCollapse = "collapse";
        table.style.width = "100%";
        table.border = "1";

        let thead = document.createElement("thead");
        thead.innerHTML = `
            <tr style="background-color: #4CAF50; color: white;">
                <th style="padding: 8px; border: 1px solid #ddd;"># of People</th>
                <th style="padding: 8px; border: 1px solid #ddd;">7 - 8+ hours</th>
                <th style="padding: 8px; border: 1px solid #ddd;">5 - 6 hours</th>
                <th style="padding: 8px; border: 1px solid #ddd;">1 - 4 hours</th>
            </tr>
        `;
        table.appendChild(thead);

        let tbody = document.createElement("tbody");

        categories.forEach(category => {
            let row = document.createElement("tr");
            row.innerHTML = `
                <td style="padding: 8px; border: 1px solid #ddd; background-color: #c8e6c9;">${category.label}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[0]] ?? '-'}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[1]] ?? '-'}</td>
                <td style="padding: 8px; border: 1px solid #ddd;">${fees[category.keys[2]] ?? '-'}</td>
            `;
            tbody.appendChild(row);
        });

        table.appendChild(tbody);

        let activeTab = document.querySelector(".nav-link.active").id;
        if (activeTab === "mail-tab" && emailBodyEditor) {
            emailBodyEditor.insertHtml(table.outerHTML);
        } else if (activeTab === "pdf-tab" && pdfBodyEditor) {
            pdfBodyEditor.insertHtml(table.outerHTML);
        } else {
            console.error("No active editor found!");
        }
    }

    $(document).ready(function () {
        $(".btn-success").click(function () {
            let email = $("#emailAddress").val();
            let subject = $("#emailSubject").val();
            let body = emailBodyEditor.getData();
            let title = $("#title").val();
            let pdfBody = pdfBodyEditor.getData();
            let scheduleEmail = $("#scheduleEmail").is(":checked") ? 1 : 0;
            let formData = new FormData();
            formData.append("email", email);
            formData.append("subject", subject);
            formData.append("body", body);
            formData.append("title", title);
            formData.append("pdf", pdfBody);
            formData.append("isScheduled", scheduleEmail);
            formData.append("_token", $('meta[name="csrf-token"]').attr("content"));
            $.ajax({
                url: "/admin/tour-guides/send-contract-mail",
                type: "POST",
                data: formData,
            processData: false,
            contentType: false,
                beforeSend: function () {
                    $(".btn-success").text("Sending...").attr("disabled", true);
                },
                success: function (response) {
                    alert("Contract sent successfully!");
                    $("#sendContractModal").modal("hide");
                },
                error: function (xhr, status, error) {
                    console.error(xhr.responseText);
                    alert("Something went wrong. Please try again.");
                },
                complete: function () {
                    $(".btn-success").text("Send Contract").attr("disabled", false);
                }
            });
        });
    });


</script>
<?php /**PATH C:\xampp8.2\htdocs\Portal\resources\views/admin/tour_guide/send_contract.blade.php ENDPATH**/ ?>