<?php 
session_start();
include("connect.php");

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
   
    //$role     = trim($_POST['role']); 

    // Prepare and execute login query with status check
    $stmt = $conn->prepare(
        "SELECT id, userid, role FROM usermaster 
         WHERE userid = ? 
        
           AND Userstatus = 'active'"
    );
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result && $result->num_rows === 1) {
        $user = $result->fetch_assoc();
        // Set session variables
        $_SESSION['id']  = $user['id'];
        $_SESSION['user_id']  = $user['userid'];
        $_SESSION['username'] = $username;
        $_SESSION['role']     = $user['role'];
        
        // Redirect to dashboard
        header('Location: dashboard.php');
        exit;
    } else {
        $error = "Invalid credentials or inactive account.";
    }
    $stmt->close();
}
$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>index</title>
  
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="css/styles.css" rel="stylesheet">
 

</head>
<body  >
 

  <div class="container bg2 ">
  <header>
      <div class="row align-items-center">
        <div class="col-6 text-start">
        <?php 
 
 if( $_SESSION['formtype']=="abr")  {   echo '<a href="abr.php"> <img src="images/lpt-left-logo.png" class="img-fluid" alt="Left logo"></a>'; }
 if( $_SESSION['formtype']=="drl") { echo  '<a href="drl.php"> <img src="images/lpt-left-logo.png" class="img-fluid" alt="Left logo"></a>'; }
 if( $_SESSION['formtype']=="form") { echo  '<a href="form.php"> <img src="images/lpt-left-logo.png" class="img-fluid" alt="Left logo"></a>'; }

    ?>
        </div>
        <div class="col-6 text-end">
          <img src="images/topmenu-logo.png" class="img-fluid" alt="Topmenu logo">
        </div>
      </div>
    </header>
  
<div class="content   mt-3">
<form id="mainForm" method="post" action="form-preview.php"  form enctype= "multipart/form-data" >

<input type="hidden" id="uploaded_form_file" name="uploaded_form_file">
<input type="hidden" id="uploaded_photo_file" name="uploaded_photo_file">
<input type="hidden" id="uploaded_video_file" name="uploaded_video_file">
          <div class="row mb-3">
          <div class="col-1 col-md-2 "></div> 
            <div class="col-10 col-md-8  text-center"><div class="box">Healthy Heart Camp</div></div>
            <div class="col-1 col-md-2 "></div>
          </div>

 <div class="row">
          <div class="mb-3">
            <label for="doctorname" class="form-label">Doctor Name</label>
            <input type="text" class="form-control" id="doctorname" name="doctorname" required>
          </div>
        </div>
          <div class="row mb-2 ">
           
            <div class="col-8 col-md-8 "> <a href="#"><div id="button1" class="button1" data-bs-toggle="modal" data-bs-target="#formModal">Upload Form</div></a> </div>
            <div class="col-4 col-md-4 "> <a  href="#" id="edit_form"  class="d-none"><div  class="edit_form button3  "  data-bs-toggle="modal" data-bs-target="#formModal"> Edit</div></a></div>
            
          </div>
          <div class="row mb-2 ">
           

            <div class="col-8 col-md-8 "> <a href="#"><div id="button1" class="button1" data-bs-toggle="modal" data-bs-target="#photoModal">Upload Photo</div></a> </div>
         
            <div class="col-4 col-md-4"><a  href="#" id="edit_photo"  class="d-none"><div  class="edit_photo button3  "  data-bs-toggle="modal" data-bs-target="#photoModal"> Edit</div></a></div>
          </div>
          <div class="row mb-2 ">
           
          <div class="col-8 col-md-8 "> <a href="#"><div id="button1" class="button1" data-bs-toggle="modal" data-bs-target="#videoModal">Upload Video</div></a>  </div>
          <div class="col-4 col-md-4"><a  href="#" id="edit_video"  class="d-none"><div  class="edit_video button3  "  data-bs-toggle="modal" data-bs-target="#videoModal"> Edit</div></a></div>
          </div>

          <div class="row   ">
            <div class="col-2 col-md-4 "></div>
            <div class="col-8 col-md-4 ">  <center> <button id="preview" class="btn w-100" type="button" disabled>  <img src="images/preview_btn.png" class="img-fluid"></button> <center></div>
            <div class="col-2 col-md-4"></div>
          </div>

</form>          


</div>
 
<div class="row text-center">
       <div class="col-2 text-center"></div>
       <div class="col-8 text-center"><a href="my-tracker.php"><img src="images/view-my-tracker.png" alt="View my tracker" class="img-fluid"></a></div>
       <div class="col-2"></div>
    </div>
 
    <footer class="mt-4">
    <div class="row">
      <div class="col-6 text-center" style="background:#ECE9F8">
      <div class="mt-4"><a href="#"  data-bs-toggle="modal" data-bs-target="#findUserModal" style="color:#54308E;font-weight:bold;text-decoration:none;"> Find Your User Code</a></div>
      </div>
      <div class="col-6 text-center" style="background:#54308E">
      <img src="images/contact-us.png" class="img-fluid" style="cursor:pointer;" data-bs-toggle="modal" data-bs-target="#contactModal">
      </div>
    </div>
  </footer>
</div>



 <!-- Form Modal -->
 <div class="modal fade" id="formModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Submit Form</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <form id="formUploadForm"        enctype="multipart/form-data">
            <input type="hidden" name="upload_id" id="formUploadId">
            <div class="mb-3">
              <label for="formFile" class="form-label">Select File</label>
              <input type="file" class="form-control" id="formFile" name="upload_file"
                     accept=".jpg,.jpeg,.png,.pdf" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">Upload</button>
          </form>
          <div id="formUploadStatus" class="mt-2"></div>
        </div>
      </div>
    </div>
  </div>


<!-- Photo Modal -->
<div class="modal fade" id="photoModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Photo Upload</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <form id="photoUploadForm"  method="post"   enctype="multipart/form-data">
            <div class="mb-3">
              <label for="photoFile" class="form-label">Select Photo</label>
              <input type="file" class="form-control" id="photoFile" name="photo"
                     accept=".jpg,.jpeg,.png,.pdf" required>
            </div>
            <button type="submit" class="btn btn-primary w-100">Upload</button>
          </form>
          <div id="photoUploadStatus" class="mt-2"></div>
        </div>
      </div>
    </div>
  </div>
 <!-- Video Modal -->
 <div class="modal fade" id="videoModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Video Upload</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form id="videoUploadForm"
              action="form_upload_video.php"
              method="post"
              enctype="multipart/form-data">
          <div class="mb-3">
            <label for="videoFileInput" class="form-label">Select Video ( Maximum Size : 50MB) </label>
            <input type="file"
                   class="form-control"
                   id="videoFileInput"
                   name="video"
                   accept=".mp4,.mov,.avi"
                   required>
          </div>
          <button type="submit" class="btn btn-secondary w-100">
            Upload
          </button>
        </form>
        <div id="videoUploadStatus" class="mt-2"></div>
      </div>
    </div>
  </div>
</div>





<!-- Contact Us Modal -->
<div class="modal fade" id="contactModal" tabindex="-1" aria-labelledby="contactModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="contactModalLabel">Contact Us</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
      <p><strong>Name:</strong> Ravindra Veer</p>
        <p><strong>Support Email:</strong> ravindra.veer@exicongroup.com</p>
        <p><strong>Phone:</strong> +91-9284759607,+91-8446704280 (Whatsapp) </p>
        <p><strong>Contact Time:</strong> Time, 9 AM to 6 PM</p>
        <!-- Add any other contact details here -->
      </div>
    </div>
  </div>
</div>



<!-- Find User Code Modal -->
<div class="modal fade" id="findUserModal" tabindex="-1" aria-labelledby="findUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="findUserModalLabel">Find Your User Code</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
      <div class="mb-3">
  <label for="fullnameInput" class="form-label">Full Name (partial allowed)</label>
  <input type="text" class="form-control" id="fullnameInput" placeholder="Enter full or partial name">
</div>
<div class="mb-3">
  <label for="stateInput" class="form-label">State (partial allowed)</label>
  <input type="text" class="form-control" id="stateInput" placeholder="Enter full or partial state">
</div>
        <div id="userDetails" class="d-none">
          <p><strong>User ID:</strong> <span id="userId"></span></p>
          <p><strong>Full Name:</strong> <span id="fullName"></span></p>
          <p><strong>State:</strong> <span id="userState"></span></p>
        </div>
        <div id="userError" class="text-danger d-none">TM ID not found.</div>
      </div>
      <div class="modal-footer">
        <button type="button" id="fetchUserBtn" class="btn btn-primary">Fetch Details</button>
      </div>
    </div>
  </div>
</div>


  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>


// Allowed mime types
const allowedMimes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];

// Helper to validate MIME type
function validateMime(file, allowedList) {
    return allowedList.includes(file.type.toLowerCase());
}

// Upload Form File
$('#formUploadForm').on('submit', function (e) {
    e.preventDefault();
    var form      = this;
    var fileInput = $('#formFile')[0].files[0];
    var statusDiv = $('#formUploadStatus');
    var submitBtn = $(form).find('button[type="submit"]');

    // Client-side MIME check
    if (!validateMime(fileInput, allowedMimes)) {
        statusDiv.html('<div class="alert alert-danger">Allowed types: JPEG, PNG, PDF only.</div>');
        return;
    }

    var formData = new FormData(form);
    submitBtn.prop('disabled', true).text('Uploading…');
    statusDiv.html('<div>Starting upload...</div>');

    $.ajax({
        url: 'form_upload.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',

        // XHR override for progress events
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function(evt) {
                    if (evt.lengthComputable) {
                        var percent = Math.round((evt.loaded / evt.total) * 100);
                        statusDiv.html(
                            `<div class="progress">
                               <div class="progress-bar" role="progressbar"
                                    style="width: ${percent}%;"
                                    aria-valuenow="${percent}" aria-valuemin="0" aria-valuemax="100">
                                 ${percent}%
                               </div>
                             </div>`
                        );
                    }
                }, false);
            }
            return xhr;
        },

        success: function (response) {
            statusDiv.html(
              `<div class="alert alert-${response.success ? 'success' : 'danger'}">
                 ${response.message}
               </div>`
            );
            if (response.success && response.filename) {
  $('#uploaded_form_file').val(response.filename);
  $('#edit_form').removeClass('d-none');
}
        },

        error: function () {
            statusDiv.html('<div class="alert alert-danger">Upload failed. Please try again.</div>');
        },

        complete: function() {
            submitBtn.prop('disabled', false).text('Upload');
        }
    });
});


// Upload Photo
$('#photoUploadForm').on('submit', function (e) {
    e.preventDefault();
    var fileInput = $('#photoFile')[0].files[0];
    var statusDiv = $('#photoUploadStatus');
    var submitBtn = $(this).find('button[type="submit"]');

    // Client-side MIME check
    if (!validateMime(fileInput, ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'])) {
        statusDiv.html('<div class="alert alert-danger">Allowed types: JPEG, PNG, PDF only.</div>');
        return;
    }

    var formData = new FormData(this);
    submitBtn.prop('disabled', true).text('Uploading…');
    statusDiv.html('<div>Starting upload...</div>');

    $.ajax({
        url: 'photo_upload.php',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        dataType: 'json',

        // Add this block to track progress
        xhr: function() {
            var xhr = $.ajaxSettings.xhr();
            if (xhr.upload) {
                xhr.upload.addEventListener('progress', function(event) {
                    if (event.lengthComputable) {
                        var percent = Math.round((event.loaded / event.total) * 100);
                        statusDiv.html(
                          `<div class="progress">
                             <div class="progress-bar" role="progressbar" 
                                  style="width: ${percent}%;" 
                                  aria-valuenow="${percent}" 
                                  aria-valuemin="0" 
                                  aria-valuemax="100">
                               ${percent}%
                             </div>
                           </div>`
                        );
                    }
                }, false);
            }
            return xhr;
        },

        success: function (response) {
            statusDiv.html(
              `<div class="alert alert-${response.success ? 'success' : 'danger'}">
                ${response.message}
              </div>`
            );
            if (response.success && response.filename) {
              $('#uploaded_photo_file').val(response.filename);
$('#edit_photo').removeClass('d-none');
checkAllUploaded();
            }
        },

        error: function () {
            statusDiv.html('<div class="alert alert-danger">Upload failed. Please try again.</div>');
        },

        complete: function() {
            submitBtn.prop('disabled', false).text('Upload');
        }
    });
});


$(function() {
  $('#videoUploadForm').on('submit', function (e) {
    e.preventDefault();

    const form    = this;
    const formData = new FormData(form);
    const statusDiv = $('#videoUploadStatus');
    const submitBtn = $(form).find('button[type="submit"]');

    submitBtn.prop('disabled', true).text('Uploading…');
    statusDiv.html('');

    $.ajax({
      url: 'video_upload.php',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      dataType: 'json',

      // Optional: track upload progress
      xhr: function() {
        const xhr = $.ajaxSettings.xhr();
        if (xhr.upload) {
          xhr.upload.addEventListener('progress', function(evt) {
            if (evt.lengthComputable) {
              const percent = Math.round(evt.loaded / evt.total * 100);
              statusDiv.html(`<div>Uploading: ${percent}%</div>`);
            }
          }, false);
        }
        return xhr;
      },

      success: function (response) {
        statusDiv.html(
          `<div class="alert alert-${response.success ? 'success' : 'danger'}">` +
            response.message +
          `</div>`
        );
        if (response.success && response.filename) {
          $('#uploaded_video_file').val(response.filename);
$('#edit_video').removeClass('d-none');
checkAllUploaded();
        }
      },

      error: function (xhr, status, error) {
        console.error('Upload error:', status, error);
        statusDiv.html(
          '<div class="alert alert-danger">Upload failed. Please try again.</div>'
        );
      },

      complete: function() {
        submitBtn.prop('disabled', false).text('Upload');
      }
    });
  });
});

$('#preview').on('click', function (e) {
    e.preventDefault(); // Prevent default form submission

    const doctorName = $('#doctorname').val().trim();

    if (doctorName === '') {
        alert('Please enter the doctor\'s name.');
        $('#doctorname').focus();exit();
    } else {
        $('#mainForm').submit();
    }
});


// Clear status when edit buttons are clicked
$('#edit_form').on('click', function () {
    $('#formUploadStatus').html('');
});
$('#edit_photo').on('click', function () {
    $('#photoUploadStatus').html('');
});
$('#edit_video').on('click', function () {
    $('#videoUploadStatus').html('');
});

function checkAllUploaded() {
 

  const formFile  = $('#uploaded_form_file').val().trim();
  const photoFile = $('#uploaded_photo_file').val().trim();
  const videoFile = $('#uploaded_video_file').val().trim();

  if (formFile && photoFile && videoFile) {
    // all three are present
    $('#preview').prop('disabled', false);
  } else {
    $('#preview').prop('disabled', true);
  }
}


$('#preview').click(function(){
  if ($(this).prop('disabled')) return;  // guard
  $('#mainForm').submit();
});
</script>
 


<script>
document.getElementById('fetchUserBtn').addEventListener('click', function () {
  const fullname = document.getElementById('fullnameInput').value.trim();
  const state = document.getElementById('stateInput').value.trim();

  if (!fullname && !state) {
    alert('Please enter Full Name or State to search.');
    return;
  }

  fetch('get-user-by-tmid.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ fullname, state })
  })
  .then(res => res.json())
  .then(data => {
    const userDetails = document.getElementById('userDetails');
    const userError = document.getElementById('userError');

    if (data.success) {
      let output = '<ul class="list-group">';
      data.data.forEach(user => {
        output += `<li class="list-group-item">
          <strong>User ID:</strong> ${user.userid}<br>
          <strong>Full Name:</strong> ${user.fullname}<br>
          <strong>State:</strong> ${user.state}
        </li>`;
      });
      output += '</ul>';
      userDetails.innerHTML = output;
      userDetails.classList.remove('d-none');
      userError.classList.add('d-none');
    } else {
      userDetails.classList.add('d-none');
      userError.textContent = data.message || 'No users found.';
      userError.classList.remove('d-none');
    }
  })
  .catch(() => {
    alert('Something went wrong. Please try again.');
  });
});

</script>
</body>
</html>