<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id']; 

// Database connection
$servername = "localhost";
$username = "gobolcha_gobolchain";
$password = "@Jibala1997";
$dbname = "gobolcha_gobolchain";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to fetch KYC status - use bind_result
$sql = "SELECT kyc_status FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $userId);
$stmt->execute();
$stmt->bind_result($kycStatus);

if (!$stmt->fetch()) {
    $kycStatus = "not_submitted";
}

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>KYC Verification - Gobolcoin</title>
    <link rel="icon" type="image/png" href="/favicon.png">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <style>
      :root {
          --maroon: #8B0000;
          --white: #ffffff;
      }
      html, body {
          height: 100%;
          margin: 0;
          padding: 0;
          font-family: 'Inter', sans-serif;
          background: linear-gradient(to top right, #ffffff 70%, #8B0000 130%);
          display: flex;
          flex-direction: column;
      }
      .main-content {
          flex-grow: 1;
          display: flex;
          justify-content: center;
          align-items: flex-start;
          padding: 2em 1em;
      }
      .form-wrapper {
          background-color: white;
          color: #8B0000;
          border-radius: 20px;
          padding: 2em;
          width: 100%;
          max-width: 450px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
      }
      h1 {
          text-align: center;
          margin-bottom: 1em;
      }
      .warning {
          background-color: #ffe0e0;
          border: 1px solid #cc0000;
          color: #cc0000;
          padding: 1em;
          border-radius: 10px;
          margin-bottom: 1.5em;
          font-size: 0.95em;
      }
      label {
          display: block;
          margin-top: 1em;
          font-weight: bold;
      }
      input, select {
          width: 100%;
          padding: 0.8em;
          margin-top: 0.3em;
          border: 1px solid #ccc;
          border-radius: 10px;
          font-size: 1em;
      }
      input[type="file"] {
          background-color: white;
          padding: 0.6em;
      }
      .face-icon {
          font-size: 2em;
          display: flex;
          justify-content: center;
          margin: 1em 0;
          cursor: pointer;
          border: 2px dashed #8B0000;
          padding: 1em;
          border-radius: 15px;
      }
      .face-icon:hover {
          background-color: #f8f8f8;
      }
      #video, #face-preview {
          display: none;
          width: 100%;
          max-width: 100%;
          margin: 1em 0;
          border-radius: 10px;
      }
      button {
          margin-top: 1.5em;
          width: 100%;
          background-color: #c70000;
          color: white;
          padding: 1em;
          font-size: 1.1em;
          font-weight: bold;
          border: none;
          border-radius: 10px;
          cursor: pointer;
      }
      footer {
          text-align: center;
          padding: 1.2em;
          background-color: var(--white);
          color: #777;
          font-size: 0.9em;
      }
      footer a {
          margin: 0 10px;
          color: #8B0000;
          font-size: 1.4em;
          text-decoration: none;
      }
      .logo-box {
          position: fixed;
          top: 20px;
          left: 20px;
          background: rgba(139, 0, 0, 0.9);
          color: white;
          padding: 8px 14px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          z-index: 999;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
      }
      .logo-box img {
          width: 32px;
          height: 32px;
          object-fit: contain;
          margin-right: 10px;
      }
      .logo-box span {
          font-size: 1.2rem;
          font-weight: bold;
      }
      .socials {
          margin-top: 1em;
      }
      .socials a {
          margin: 0 8px;
          display: inline-block;
      }
      .socials img {
          width: 24px;
          height: 24px;
      }
      @media (max-width: 600px) {
          .logo-box {
              top: 10px;
              left: 10px;
              padding: 6px 10px;
          }
          .logo-box img {
              width: 26px;
              height: 26px;
          }
          .logo-box span {
              font-size: 1rem;
          }
      }
    </style>
</head>
<body>

<div class="logo-box">
    <img src="images/gobolcoin-logo.png" alt="Gobolcoin Logo">
    <span>Gobolchain Network</span>
</div>

<div class="main-content">
    <div class="form-wrapper">
        <?php
        // Check the KYC status and display content accordingly
        if ($kycStatus === "approved") {
            // If KYC is approved, display this message
            echo '<h1>KYC Approved</h1>';
            echo '<div class="warning" style="background-color: #e0ffe0; border: 1px solid #009900; color: #009900;">';
            echo '🎉 <strong>Congratulations!</strong> Your KYC verification has been successfully approved. You do not need to submit the form again.';
            echo '</div>';
        } else {
            // Otherwise, display the full KYC form as before
        ?>
            <h1>KYC FORM</h1>
            <div class="warning">
        <strong>Important:</strong> Fill your details carefully. Ensure that they match your official documents. Once submitted, you can't edit them. Mistakes may lead to KYC rejection.
      </div>
            <form action="submit-kyc.php" method="POST" enctype="multipart/form-data" onsubmit="return validateForm()">
                <label>First Name</label>
                <input type="text" name="firstName" required>
                <label>Middle Name</label>
                <input type="text" name="middleName">
                <label>Last Name</label>
                <input type="text" name="lastName" required>
                <label>Phone Number (include country code)</label>
                <input type="tel" name="phone" placeholder="e.g. +2349012345678" required>
                <label>Country of Residence</label>
  <select name="country" required>
  <option value="">Select country</option>
  <option value="Afghanistan">Afghanistan</option>
  <option value="Albania">Albania</option>
  <option value="Algeria">Algeria</option>
  <option value="Andorra">Andorra</option>
  <option value="Angola">Angola</option>
  <option value="Argentina">Argentina</option>
  <option value="Armenia">Armenia</option>
  <option value="Australia">Australia</option>
  <option value="Austria">Austria</option>
  <option value="Azerbaijan">Azerbaijan</option>
  <option value="Bahamas">Bahamas</option>
  <option value="Bahrain">Bahrain</option>
  <option value="Bangladesh">Bangladesh</option>
  <option value="Barbados">Barbados</option>
  <option value="Belarus">Belarus</option>
  <option value="Belgium">Belgium</option>
  <option value="Benin">Benin</option>
  <option value="Bhutan">Bhutan</option>
  <option value="Bolivia">Bolivia</option>
  <option value="Bosnia and Herzegovina">Bosnia and Herzegovina</option>
  <option value="Botswana">Botswana</option>
  <option value="Brazil">Brazil</option>
  <option value="Brunei">Brunei</option>
  <option value="Bulgaria">Bulgaria</option>
  <option value="Burkina Faso">Burkina Faso</option>
  <option value="Burundi">Burundi</option>
  <option value="Cambodia">Cambodia</option>
  <option value="Cameroon">Cameroon</option>
  <option value="Canada">Canada</option>
  <option value="Cape Verde">Cape Verde</option>
  <option value="Central African Republic">Central African Republic</option>
  <option value="Chad">Chad</option>
  <option value="Chile">Chile</option>
  <option value="China">China</option>
  <option value="Colombia">Colombia</option>
  <option value="Comoros">Comoros</option>
  <option value="Costa Rica">Costa Rica</option>
  <option value="Croatia">Croatia</option>
  <option value="Cuba">Cuba</option>
  <option value="Cyprus">Cyprus</option>
  <option value="Czech Republic">Czech Republic</option>
  <option value="Denmark">Denmark</option>
  <option value="Djibouti">Djibouti</option>
  <option value="Dominica">Dominica</option>
  <option value="Dominican Republic">Dominican Republic</option>
  <option value="DR Congo">DR Congo</option>
  <option value="Ecuador">Ecuador</option>
  <option value="Egypt">Egypt</option>
  <option value="El Salvador">El Salvador</option>
  <option value="Equatorial Guinea">Equatorial Guinea</option>
  <option value="Eritrea">Eritrea</option>
  <option value="Estonia">Estonia</option>
  <option value="Eswatini">Eswatini</option>
  <option value="Ethiopia">Ethiopia</option>
  <option value="Fiji">Fiji</option>
  <option value="Finland">Finland</option>
  <option value="France">France</option>
  <option value="Gabon">Gabon</option>
  <option value="Gambia">Gambia</option>
  <option value="Georgia">Georgia</option>
  <option value="Germany">Germany</option>
  <option value="Ghana">Ghana</option>
  <option value="Greece">Greece</option>
  <option value="Grenada">Grenada</option>
  <option value="Guatemala">Guatemala</option>
  <option value="Guinea">Guinea</option>
  <option value="Guinea-Bissau">Guinea-Bissau</option>
  <option value="Guyana">Guyana</option>
  <option value="Haiti">Haiti</option>
  <option value="Honduras">Honduras</option>
  <option value="Hungary">Hungary</option>
  <option value="Iceland">Iceland</option>
  <option value="India">India</option>
  <option value="Indonesia">Indonesia</option>
  <option value="Iran">Iran</option>
  <option value="Iraq">Iraq</option>
  <option value="Ireland">Ireland</option>
  <option value="Israel">Israel</option>
  <option value="Italy">Italy</option>
  <option value="Ivory Coast">Ivory Coast</option>
  <option value="Jamaica">Jamaica</option>
  <option value="Japan">Japan</option>
  <option value="Jordan">Jordan</option>
  <option value="Kazakhstan">Kazakhstan</option>
  <option value="Kenya">Kenya</option>
  <option value="Kiribati">Kiribati</option>
  <option value="Kuwait">Kuwait</option>
  <option value="Kyrgyzstan">Kyrgyzstan</option>
  <option value="Laos">Laos</option>
  <option value="Latvia">Latvia</option>
  <option value="Lebanon">Lebanon</option>
  <option value="Lesotho">Lesotho</option>
  <option value="Liberia">Liberia</option>
  <option value="Libya">Libya</option>
  <option value="Liechtenstein">Liechtenstein</option>
  <option value="Lithuania">Lithuania</option>
  <option value="Luxembourg">Luxembourg</option>
  <option value="Madagascar">Madagascar</option>
  <option value="Malawi">Malawi</option>
  <option value="Malaysia">Malaysia</option>
  <option value="Maldives">Maldives</option>
  <option value="Mali">Mali</option>
  <option value="Malta">Malta</option>
  <option value="Mauritania">Mauritania</option>
  <option value="Mauritius">Mauritius</option>
  <option value="Mexico">Mexico</option>
  <option value="Moldova">Moldova</option>
  <option value="Monaco">Monaco</option>
  <option value="Mongolia">Mongolia</option>
  <option value="Montenegro">Montenegro</option>
  <option value="Morocco">Morocco</option>
  <option value="Mozambique">Mozambique</option>
  <option value="Myanmar">Myanmar</option>
  <option value="Namibia">Namibia</option>
  <option value="Nepal">Nepal</option>
  <option value="Netherlands">Netherlands</option>
  <option value="New Zealand">New Zealand</option>
  <option value="Nicaragua">Nicaragua</option>
  <option value="Niger">Niger</option>
  <option value="Nigeria">Nigeria</option>
  <option value="North Korea">North Korea</option>
  <option value="North Macedonia">North Macedonia</option>
  <option value="Norway">Norway</option>
  <option value="Oman">Oman</option>
  <option value="Pakistan">Pakistan</option>
  <option value="Palestine">Palestine</option>
  <option value="Panama">Panama</option>
  <option value="Papua New Guinea">Papua New Guinea</option>
  <option value="Paraguay">Paraguay</option>
  <option value="Peru">Peru</option>
  <option value="Philippines">Philippines</option>
  <option value="Poland">Poland</option>
  <option value="Portugal">Portugal</option>
  <option value="Qatar">Qatar</option>
  <option value="Republic of the Congo">Republic of the Congo</option>
  <option value="Romania">Romania</option>
  <option value="Russia">Russia</option>
  <option value="Rwanda">Rwanda</option>
  <option value="Saint Lucia">Saint Lucia</option>
  <option value="Saint Vincent and the Grenadines">Saint Vincent and the Grenadines</option>
  <option value="Samoa">Samoa</option>
  <option value="San Marino">San Marino</option>
  <option value="Saudi Arabia">Saudi Arabia</option>
  <option value="Senegal">Senegal</option>
  <option value="Serbia">Serbia</option>
  <option value="Seychelles">Seychelles</option>
  <option value="Sierra Leone">Sierra Leone</option>
  <option value="Singapore">Singapore</option>
  <option value="Slovakia">Slovakia</option>
  <option value="Slovenia">Slovenia</option>
  <option value="Somalia">Somalia</option>
  <option value="South Africa">South Africa</option>
  <option value="South Korea">South Korea</option>
  <option value="South Sudan">South Sudan</option>
  <option value="Spain">Spain</option>
  <option value="Sri Lanka">Sri Lanka</option>
  <option value="Sudan">Sudan</option>
  <option value="Suriname">Suriname</option>
  <option value="Sweden">Sweden</option>
  <option value="Switzerland">Switzerland</option>
  <option value="Syria">Syria</option>
  <option value="Taiwan">Taiwan</option>
  <option value="Tajikistan">Tajikistan</option>
  <option value="Tanzania">Tanzania</option>
  <option value="Thailand">Thailand</option>
  <option value="Togo">Togo</option>
  <option value="Trinidad and Tobago">Trinidad and Tobago</option>
  <option value="Tunisia">Tunisia</option>
  <option value="Turkey">Turkey</option>
  <option value="Turkmenistan">Turkmenistan</option>
  <option value="Uganda">Uganda</option>
  <option value="Ukraine">Ukraine</option>
  <option value="United Arab Emirates">United Arab Emirates</option>
  <option value="United Kingdom">United Kingdom</option>
  <option value="United States">United States</option>
  <option value="Uruguay">Uruguay</option>
  <option value="Uzbekistan">Uzbekistan</option>
  <option value="Vanuatu">Vanuatu</option>
  <option value="Vatican City">Vatican City</option>
  <option value="Venezuela">Venezuela</option>
  <option value="Vietnam">Vietnam</option>
  <option value="Yemen">Yemen</option>
  <option value="Zambia">Zambia</option>
  <option value="Zimbabwe">Zimbabwe</option>
</select>
                <label>Upload Government-issued ID (Max: 1.5MB)</label>
                <input type="file" name="govID" accept="image/*,.pdf,.doc,.docx" required />
                <label>Face Verification</label>
                <div class="face-icon" onclick="startCamera()">Tap to take photo</div>
                <video id="video" autoplay playsinline></video>
                <canvas id="canvas" style="display: none;"></canvas>
                <img id="face-preview" alt="Face preview" />
                <button type="button" id="snapBtn" style="display: none; margin-top: 10px;">Take Snapshot</button>
                <input type="hidden" name="face_image_data" id="faceImage">
                <button type="submit">Submit</button>
            </form>
        <?php
        }
        ?>
    </div>
</div>

<footer>
    <div class="socials">
        <a href="https://x.com/gobolcoin?s=08" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/733/733579.png" alt="Twitter">
        </a>
        <a href="https://youtube.com/@gobolcoin?si=ByrsmImTnkALKIzX" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/1384/1384060.png" alt="YouTube">
        </a>
        <a href="https://t.me/+DvAqx1PFYAE2MDE0" target="_blank">
            <img src="https://cdn-icons-png.flaticon.com/512/2111/2111646.png" alt="Telegram">
        </a>
    </div>
    <p style="margin-top: 0.5em;">All right reserve &copy; Gobolchain Network 2025</p>
</footer>

<script>
    // Global variables to hold state
    let videoStream = null;
    let faceImageData = null;

    // Function to start the camera and display the video feed
    function startCamera() {
        const video = document.getElementById('video');
        const snapBtn = document.getElementById('snapBtn');

        // Check for an existing stream to prevent opening multiple cameras
        if (videoStream) {
            videoStream.getTracks().forEach(track => track.stop());
        }

        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                videoStream = stream;
                video.srcObject = stream;
                video.style.display = 'block';
                snapBtn.style.display = 'block';
            })
            .catch(err => alert("Camera error: " + err.message));
    }

    // Event listener for the "Take Snapshot" button
document.getElementById('snapBtn').addEventListener('click', function () {
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const preview = document.getElementById('face-preview');
    const context = canvas.getContext('2d');
    
    // Ensure the video element is ready to capture
    if (!video.srcObject) {
        alert("Camera stream is not active. Please start the camera first.");
        return;
    }

    if (video.videoWidth === 0 || video.videoHeight === 0) {
        alert("Camera video dimensions are zero. This can happen if the camera is still starting. Please wait a moment and try again.");
        return;
    }

    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    context.drawImage(video, 0, 0, canvas.width, canvas.height);
    
    // Get the image data
    const imageData = canvas.toDataURL('image/png');
    
    // IMPORTANT: Add this check to see what imageData contains
    if (imageData === 'data:,') {
        alert("Failed to capture image from canvas. The canvas is likely empty.");
        console.error("Canvas toDataURL returned empty data string.");
        return;
    }

    // Store the data in the hidden input and the global variable
    document.getElementById('faceImage').value = imageData;
    faceImageData = imageData;
    
    preview.src = imageData;
    preview.style.display = 'block';

    // Stop the camera stream and hide the video element
    if (videoStream) {
        videoStream.getTracks().forEach(track => track.stop());
        videoStream = null; // Clear the stream variable
    }
    video.style.display = 'none';
    document.getElementById('snapBtn').style.display = 'none';
    
    // Add a console log to confirm success
    console.log("Snapshot taken successfully. faceImageData is now set.");
});

    // Client-side form validation
    function validateForm() {
        const govID = document.querySelector('input[name="govID"]');
        
        // Check for file size
        if (govID.files.length > 0 && govID.files[0].size > 1572864) {
            alert("Government-issued ID must be less than 1.5MB.");
            return false;
        }
        
        // Check if a face image was captured
        if (!faceImageData) {
            alert("Please take a snapshot for face verification.");
            return false;
        }
        
        return true; // All validations passed
    }

    // Attach the `startCamera` function to the face-icon click event
    // This is the best practice and avoids the ReferenceError.
    document.querySelector('.face-icon').addEventListener('click', startCamera);

    // Make the validateForm function globally accessible for the form's onsubmit attribute
    window.validateForm = validateForm;

</script>


</body>
</html>