<?php include('header.php')?>
<style>
  .tab-content.hidden {
      display: none;
  }
  .tab-content {
      display: block;
  }
  .mbutton {
      background: #ffffff;
      color: black;
  }
  .mbutton:hover {
      background: #ffffff;
  }
  .mbutton.active {
      background: #012b4b;
      color: white;
  }
  .down-icon {
      height: 40px;
      width: 40px;
      line-height: 40px;
      background: #fe2c2d;
      border-radius: 50%;
  }
  .img-box2 .slider-area {
      padding-left: 105px;
  }
  .main-container {
      display: flex;
      justify-content: center;
      align-items: center;
      gap: 25px;
      margin-bottom: 40px;
  }
</style>

<div class="dashboard-main-body">
  <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
    <h6 class="fw-semibold mb-0">Lease Documents</h6>
    <ul class="d-flex align-items-center gap-2">
      <li class="fw-medium">
        <a href="<?php echo base_url(); ?>" class="d-flex align-items-center gap-1 hover-text-primary">
          <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon>
          Dashboard
        </a>
      </li>
      <li>-</li>
      <li class="fw-medium">Lease Documents</li>
    </ul>
  </div>

  <?php
  $session = \Config\Services::session();
  $db = \Config\Database::connect();
  ?>
  
  <div class="py-1">
    <?php if ($session->get('message')) { ?>
      <div class="alert alert-success bg-success-100 text-success-600 border-success-600 border-start-width-4-px border-top-0 border-end-0 border-bottom-0 px-24 py-13 mb-0 fw-semibold text-lg radius-4 d-flex align-items-center justify-content-between" role="alert">
        <div class="d-flex align-items-center gap-2">
          <iconify-icon icon="akar-icons:double-check" class="icon text-xl"></iconify-icon>
          <?php echo $session->get('message'); ?>
        </div>
        <button class="remove-button text-success-600 text-xxl line-height-1">
          <iconify-icon icon="iconamoon:sign-times-light" class="icon"></iconify-icon>
        </button>
      </div>
    <?php } ?>
    <?php if ($session->get('error')) { ?>
      <div class="alert alert-danger bg-danger-100 text-danger-600 border-danger-600 border-start-width-4-px border-top-0 border-end-0 border-bottom-0 px-24 py-13 mb-0 fw-semibold text-lg radius-4 d-flex align-items-center justify-content-between" role="alert">
        <div class="d-flex align-items-center gap-2">
          <iconify-icon icon="mdi:alert-circle-outline" class="icon text-xl"></iconify-icon>
          <?php echo $session->get('message'); ?>
        </div>
        <button class="remove-button text-danger-600 text-xxl line-height-1">
          <iconify-icon icon="iconamoon:sign-times-light" class="icon"></iconify-icon>
        </button>
      </div>
    <?php } ?>
  </div>   
<div class="row d-none">
  <div class="card col-lg-12 datatable-init my-3">
    <div class="card-body">
        
<form method="post" action="<?= base_url('home/uploadpdf') ?>" enctype="multipart/form-data">
    <div class="row mb-4">
        <!-- Property Address -->
        <div class="col-lg-6 col-sm-12 mb-4">
            <label for="property_address">Upload File</label>
            <input class="form-control" type="file" name="file" id="file"  accept=".pdf" required />
        </div>
    </div>
    <input type="submit" class="btn btn-primary" value="Upload">
</form>

    </div>
</div>
</div>

  <div class="p-6">
    <!-- Tabs -->
    <div class="main-container">
       
      <button class="mbutton btn tab-button flex-1 py-2 text-center text-lg font-medium text-gray-600 active" data-target="dashboard">
        Lease Application Form
      </button>
      <button class="mbutton btn tab-button flex-1 py-2 text-center text-lg font-medium text-gray-600" data-target="leasing">
        Tenant Selection Criteria
      </button>
      <a class="mbutton btn tab-button flex-1 py-2 text-center text-lg font-medium text-gray-600 " data-target="logout">
        Brokerage Services
      </a>
    </div>

    <!-- Tab Content -->
    <div id="dashboard" class="tab-content hidden">
      <section class="footer-wrapper footer-layout2 pb-2 pt-4" style="background:#012b4b; margin-top:-8px;">
        <div class="container text-center">
          <div class="footer-wrap space-top pt-0">
            <div class="col-md-12">
              <h5 class="mb-0" style="color:#ffffff">Lease Application Form</h5>
              <p style="color:#dfdfdf">Click on 'Download' to view and submit the filled form.</p>
            </div>
          </div>
        </div>
      </section>
      <div style="position: relative; width: 100%; height: 1000px;">
        <iframe src="<?= base_url('assets/form.pdf') ?>" id="pdf-viewer" width="100%" height="1000px"></iframe>
        <form method="post" class="h-100 w-100" action="https://txpre.com/docusign/Lease_Application.php" style="position: absolute; top: 0px; left: 0px;pointer-events: auto;  display: flex; justify-content: center; align-items: center; background: #012b4b73;">
            <div class="trail-bg  text-center d-flex flex-column justify-content-between align-items-center p-16 radius-8" style="background: #012b4b;">
                <input type="hidden" value="<?=$session->get('name')?>" name="name"/>
                <input type="hidden" value="<?=$session->get('user_email')?>" name="email"/>
                <input type="hidden" value="<?=$session->get('user_id')?>" name="cid"/>
                <h6 class="text-white text-xl">Fill Pdf</h6>
                <div class="">
                    <p class="text-white">Complete Your Application. Click the button below to fill and submit your Lease Application.</p>
                    <button type="submit" class="btn py-8 rounded-pill w-100 bg-gradient-blue-warning text-sm ">
                                      Lease Application Form
                    </button>
                </div>
            </div>
        </form>
      </div>
      <!--<button id="save-data-btn" -->
      <!--        style="background-color: #4CAF50; color: white; border: none; padding: 10px 20px; -->
      <!--               text-align: center; text-decoration: none; display: inline-block; -->
      <!--               font-size: 16px; margin: 20px auto; cursor: pointer; border-radius: 5px;">-->
      <!--  Download-->
      <!--</button> -->
    </div>

    <div id="leasing" class="tab-content hidden">
      <section class="footer-wrapper footer-layout2 pb-2 pt-4" style="background:#012b4b; margin-top:-8px;">
        <div class="container text-center">
          <div class="footer-wrap space-top pt-0">
            <div class="col-md-12">
              <h5 class="mb-0" style="color:#ffffff">Tenant Selection Criteria</h5>
              <p style="color:#dfdfdf">Discover the eligibility to qualify for your perfect rental.</p>
            </div>
          </div>
        </div>
      </section>
      <div style="position: relative; width: 100%; height: 1000px;">
        <iframe src="<?= base_url('assets/tenant-selection-criteria-1.3.pdf') ?>" id="pdf-tenant" width="100%" height="1000px"></iframe>
        <form method="post" class="h-100 w-100" action="https://txpre.com/docusign/index.php" style="position: absolute; top: 0px; left: 0px;pointer-events: auto;  display: flex; justify-content: center; align-items: center; background: #012b4b73;">
            <div class="trail-bg text-center d-flex flex-column justify-content-between align-items-center p-16 radius-8" style="background: #012b4b;">
                <input type="hidden" value="<?=$session->get('name')?>" name="name"/>
                <input type="hidden" value="<?=$session->get('user_email')?>" name="email"/>
                <input type="hidden" value="<?=$session->get('user_id')?>" name="cid"/>
                <h6 class="text-white text-xl">Fill Pdf</h6>
                <div class="">
                    <p class="text-white">Complete Your Application. Click the button below to fill and submit your Tenant Selection Criteria.</p>
                    <button type="submit" class="btn py-8 rounded-pill w-100 bg-gradient-blue-warning text-sm ">
                                      Tenant Selection Criteria
                    </button>
                </div>
            </div>
        </form>
      </div>
      <!--<button id="save-tenant-data-btn" -->
      <!--        style="background-color: #4CAF50; color: white; border: none; padding: 10px 20px; -->
      <!--               text-align: center; text-decoration: none; display: inline-block; -->
      <!--               font-size: 16px; margin: 20px auto; cursor: pointer; border-radius: 5px;">-->
      <!--  Download-->
      <!--</button>-->
    </div>

    <div id="logout" class="tab-content mb-3 hidden">
      <section class="footer-wrapper footer-layout2 pb-3 pt-4" style="background:#012b4b; margin-top:-8px;">
        <div class="container text-center">
          <div class="footer-wrap space-top pt-0">
            <div class="col-md-12">
              <h5 class="mb-0" style="color:#ffffff">Information About Brokerage Services</h5>
              <p style="color: #dfdfdf; margin-bottom:10px">
                Texas Law Requires License Holders to Provide Information About Brokerage Services Form to All Prospective Clients.
              </p>
            </div>
          </div>
        </div>
      </section>
      <div style="position: relative; width: 100%; height: 1000px;">
        <iframe src="<?= base_url('assets/iabs-txpre.pdf') ?>" width="100%" height="1000px"></iframe>
      </div>
    </div>
  </div>
  

  
</div>



<?php include('footer.php')?>

<!-- Updated JavaScript for both upload and download -->
<script>
/**
 * Fetch the PDF from the provided URL, then upload it to the server and trigger a download.
 * @param {string} pdfUrl - URL of the PDF to be processed.
 * @param {string} filename - Desired filename for the downloaded file.
 * @param {string} docName - Document name to be recorded on the server.
 * @param {string} type - Type identifier (e.g., 'client' or 'tenant').
 * @param {string} cid - User id (from session) used for database entry.
 */
function uploadAndDownloadPdf(pdfUrl, filename, docName, type, cid) {
    // Fetch the PDF as a Blob
    fetch(pdfUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.blob();
        })
        .then(blob => {
            // Prepare form data for upload
            const formData = new FormData();
            formData.append('file', blob, filename);
            formData.append('docname', docName);
            formData.append('type', type);
            formData.append('cid', cid);
            
            // Upload the PDF to the server
            fetch('home/upload_pdf', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    // Create a temporary object URL for the blob and trigger a download
                    const downloadUrl = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    a.download = filename;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(downloadUrl);
                    document.body.removeChild(a);
                    alert('PDF uploaded and downloaded successfully!');
                } else {
                    alert('Error uploading PDF: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error during upload:', error);
                alert('Error uploading PDF.');
            });
        })
        .catch(error => {
            console.error('Error fetching PDF:', error);
            alert('Error fetching the PDF.');
        });
}

// Attach event listeners to the download buttons
document.getElementById('save-data-btn').addEventListener('click', function() {
    const iframe = document.getElementById('pdf-viewer');
    const pdfUrl = iframe.src;
    uploadAndDownloadPdf(pdfUrl, 'lease_application_form.pdf', 'Lease Application Form', 'client', "<?= session()->get('user_id') ?>");
});

document.getElementById('save-tenant-data-btn').addEventListener('click', function() {
    const iframe = document.getElementById('pdf-tenant');
    const pdfUrl = iframe.src;
    uploadAndDownloadPdf(pdfUrl, 'tenant_selection_criteria.pdf', 'Tenant Selection Criteria', 'tenant', "<?= session()->get('user_id') ?>");
});
</script>

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Select all tab buttons and tab content sections
    const tabs = document.querySelectorAll(".tab-button");
    const tabContents = document.querySelectorAll(".tab-content");

    tabs.forEach((tab) => {
        tab.addEventListener("click", (event) => {
            event.preventDefault();
            // Hide all tab content sections
            tabContents.forEach((content) => content.classList.add("hidden"));

            // Remove active styles from all tabs
            tabs.forEach((btn) => {
                btn.classList.remove("text-[var(--theme-color)]", "border-green-500", "active");
                btn.classList.add("text-gray-600");
            });

            // Get the target tab's ID and display that tab
            const target = tab.getAttribute("data-target");
            if (target) {
                document.getElementById(target).classList.remove("hidden");
            }

            // Add active styles to the clicked tab
            tab.classList.add("text-[var(--theme-color)]", "border-green-500", "active");
            tab.classList.remove("text-gray-600");
        });
    });

    // Initialize the first tab as active on page load
    if (tabs.length > 0) {
        tabs[0].click();
    }
});
</script>
