<?php require("header_cur.php"); ?>

<?php
// ✅ Check if service3 (KYC2) is enabled
$stmt = $pdo->query("SELECT service3 FROM settings LIMIT 1");
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
$kyc_enabled = $settings && $settings['service3'] == 1;

if (!$kyc_enabled) {
    echo "<script>window.location.href='kyc3.php';</script>";
    exit;
}

// ✅ Always use logged-in user ID
$id = $_SESSION['SESS_USERID'] ?? null;
if (!$id) {
    header("Location: logout.php");
    exit();
}

// ✅ Upload Handler
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['addressUpload'])) {
    $docType = $_POST['addressType'] ?? '';
    $maxsize = 104857600; // 100MB
    $doc_location = null;

    // Absolute path for saving
    $target_dir = __DIR__ . "/upload/doc/";

    // Ensure directory exists
    if (!is_dir($target_dir)) {
        mkdir($target_dir, 0777, true);
    }

    if (!empty($_FILES['docFile']['name'])) {
        $extension = strtolower(pathinfo($_FILES["docFile"]["name"], PATHINFO_EXTENSION));
        $extensions_arr = ["jpg", "jpeg", "png", "pdf"];

        $filename = time() . "_addr_" . basename($_FILES["docFile"]["name"]);
        $target_file = $target_dir . $filename;

        // Relative path for DB
        $db_file_path = "accounts/upload/doc/" . $filename;

        if (in_array($extension, $extensions_arr)) {
            if ($_FILES['docFile']['size'] < $maxsize && $_FILES["docFile"]["size"] > 0) {
                
                // ✅ Delete old file if exists
                $stmtOld = $pdo->prepare("SELECT address_doc FROM logins WHERE id = :id");
                $stmtOld->execute(["id" => $id]);
                $old = $stmtOld->fetchColumn();

                if ($old && file_exists(__DIR__ . "/../" . $old)) {
                    unlink(__DIR__ . "/../" . $old);
                }

                // ✅ Upload new file
                if (move_uploaded_file($_FILES["docFile"]["tmp_name"], $target_file)) {
                    $doc_location = $db_file_path;
                } else {
                    echo "<script>alert('❌ Failed to upload file. Check folder permissions.');</script>";
                }
            } else {
                echo "<script>alert('❌ File too large. Max 100MB allowed.');</script>";
            }
        } else {
            echo "<script>alert('❌ Invalid file type. Allowed: JPG, PNG, JPEG, PDF');</script>";
        }
    }

    if (!empty($doc_location)) {
        $stmt = $pdo->prepare("UPDATE logins SET 
            address_doc_type = :doctype,
            address_doc = :doc,
            verified = 1
            WHERE id = :id");

        if ($stmt->execute([
            ":doctype" => $docType,
            ":doc" => $doc_location,
            ":id" => $id
        ])) {
            echo "<script>alert('✅ Address document uploaded successfully!'); window.location.href='kyc3.php';</script>";
            exit;
        } else {
            $error = $stmt->errorInfo();
            echo "<pre>DB Error: " . print_r($error, true) . "</pre>";
        }
    }
}
?>



 <div wire:snapshot="{&quot;data&quot;:{&quot;subject&quot;:null,&quot;message&quot;:null,&quot;search&quot;:&quot;&quot;},&quot;memo&quot;:{&quot;id&quot;:&quot;V6kSc3a2Zc4A4AdWtQNv&quot;,&quot;name&quot;:&quot;user.contact-support&quot;,&quot;path&quot;:&quot;user\/contact-support&quot;,&quot;method&quot;:&quot;GET&quot;,&quot;children&quot;:[],&quot;scripts&quot;:[],&quot;assets&quot;:[],&quot;errors&quot;:[],&quot;locale&quot;:&quot;en&quot;},&quot;checksum&quot;:&quot;449e4d3fd1c77f434a1f266473766dc0fc4545a4a7a6c2c0967344509f9a2120&quot;}" wire:effects="[]" wire:id="V6kSc3a2Zc4A4AdWtQNv" class="space-y-6 mb-5 md:mb-1">
 <!--<div class="grid lg:grid-cols-3 gap-6">-->
     
     

<div class="flex items-center justify-center min-h-screen bg-[#0A0714] text-white px-4">
  <div class="w-full max-w-3xl bg-[#161223] rounded-2xl shadow-xl border border-gray-800 p-8">
    
    <!-- Header -->
    <div class="text-center mb-6">
      <h2 class="text-2xl font-bold text-[#2FE6DE]">KYC Level 2 – Proof of Address</h2>
      <p class="text-gray-400 mt-2">Please provide a valid proof of address document to continue.</p>
    </div>

    <!-- Info -->
    <div class="bg-[#1A1428] border-l-4 border-[#2FE6DE] p-5 rounded-xl mb-6">
      <h3 class="text-[#2FE6DE] font-semibold mb-2">📄 Requirements</h3>
      <ul class="list-disc list-inside text-sm text-gray-300 space-y-1">
        <li>Accepted: Utility Bill, Bank Statement, Lease Agreement</li>
        <li>Must show your <strong>full name and address</strong></li>
        <li>Document not older than <strong>3 months</strong></li>
        <li>Formats: JPG, PNG, JPEG, PDF</li>
        <li>Max size: 100MB</li>
      </ul>
    </div>

    <!-- Upload Form -->
  <!-- Upload Form -->
<form method="POST" enctype="multipart/form-data" id="uploadForm">

  <!-- File Upload -->
  <div class="mb-5">
    <label class="block text-sm text-gray-400 mb-2">Upload Document *</label>
    <input type="file" name="docFile" accept="image/*,application/pdf" 
      class="w-full file:mr-4 file:py-2 file:px-4
             file:rounded-lg file:border-0
             file:text-sm file:font-semibold
             file:bg-gradient-to-r file:from-[#2FE6DE] file:to-[#1BC4B7] file:text-black
             hover:file:brightness-110
             bg-[#1A1428] border border-gray-700 rounded-xl px-4 py-3 text-white"
      required>
  </div>

  <!-- Document Type -->
  <div class="mb-5">
    <label class="block text-sm text-gray-400 mb-2">Document Type *</label>
    <select name="addressType" class="w-full bg-[#1A1428] border border-gray-700 rounded-xl px-4 py-3 text-white focus:border-[#2FE6DE]" required>
      <option value="Utility Bill">Utility Bill</option>
      <option value="Bank Statement">Bank Statement</option>
      <option value="Lease Agreement">Lease Agreement</option>
    </select>
  </div>

  <!-- Submit -->
  <button type="submit" name="addressUpload" 
    class="w-full mt-4 bg-gradient-to-r from-[#2FE6DE] to-[#1BC4B7] text-black font-semibold py-3 rounded-xl hover:brightness-110 transition">
    📤 Upload Document
  </button>
</form>

  </div>
</div>
<hr>
<br>
<br>
<br>

</div>

<script>
  const dropzone = document.getElementById("dropzone");
  const input = dropzone.querySelector("input");
  const preview = document.getElementById("preview");

  dropzone.addEventListener("click", () => input.click());
  dropzone.addEventListener("dragover", (e) => {
    e.preventDefault(); dropzone.classList.add("bg-[#1A1428]");
  });
  dropzone.addEventListener("dragleave", () => {
    dropzone.classList.remove("bg-[#1A1428]");
  });
  dropzone.addEventListener("drop", (e) => {
    e.preventDefault(); input.files = e.dataTransfer.files;
    showPreview(input.files);
  });
  input.addEventListener("change", () => showPreview(input.files));

  function showPreview(files) {
    preview.innerHTML = "";
    [...files].forEach(file => {
      const div = document.createElement("div");
      div.className = "bg-[#1A1428] border border-gray-700 rounded-lg p-3 w-28 text-center text-xs";
      if (file.type.startsWith("image/")) {
        const img = document.createElement("img");
        img.src = URL.createObjectURL(file);
        img.className = "rounded mb-2";
        div.appendChild(img);
      }
      div.innerHTML += `<p class="truncate">${file.name}</p>`;
      preview.appendChild(div);
    });
  }
</script>

<?php require("footer.php"); ?>
