<?php
require_once("../api/config/db.php");

$success = "";
$error = "";

function userColumnExists($conn, $column) {
    $column = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM users LIKE '$column'");
    return $res && $res->num_rows > 0;
}

function uploadImageFile($field, $uploadDir, $relativePath) {
    if (empty($_FILES[$field]['name']) || $_FILES[$field]['error'] !== 0) {
        return "";
    }

    $allowed = ['jpg', 'jpeg', 'png', 'webp'];
    $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed)) {
        return "";
    }

    $fileName = time() . "_" . rand(1000, 9999) . "_" . $field . ".jpg";
    $target = $uploadDir . $fileName;

    if (move_uploaded_file($_FILES[$field]['tmp_name'], $target)) {
        return $relativePath . $fileName;
    }

    return "";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name         = trim($_POST['name'] ?? '');
    $father_name  = trim($_POST['father_name'] ?? '');
    $mobile       = trim($_POST['mobile'] ?? '');
    $dob          = trim($_POST['dob'] ?? '');
    $id_type      = trim($_POST['id_type'] ?? '');
    $village_id   = intval($_POST['village_id'] ?? 0);
    $password     = $_POST['password'] ?? '';
    $confirm_pass = $_POST['confirm_password'] ?? '';

    if (!$village_id || !$name || !$mobile || !$password || !$confirm_pass) {
        $error = "Please complete all required fields.";
    } elseif (!preg_match('/^[0-9]{10}$/', $mobile)) {
        $error = "Please enter valid 10 digit mobile number.";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } elseif ($password !== $confirm_pass) {
        $error = "Password and confirm password do not match.";
    } else {
        $check = $conn->prepare("SELECT id FROM users WHERE mobile=? LIMIT 1");
        $check->bind_param("s", $mobile);
        $check->execute();

        if ($check->get_result()->num_rows > 0) {
            $error = "Mobile number already registered.";
        } else {
            $dob_db = null;
            $age = null;

            if ($dob) {
                $dob_db = date("Y-m-d", strtotime($dob));
                $age = date_diff(date_create($dob_db), date_create('today'))->y;
            }

            $uploadDir = "../uploads/subadmindata/";
            $relativePath = "uploads/subadmindata/";

            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $aadhaar_front = uploadImageFile("aadhaar_front", $uploadDir, $relativePath);
            $aadhaar_back  = uploadImageFile("aadhaar_back", $uploadDir, $relativePath);
            $selfie        = uploadImageFile("selfie", $uploadDir, $relativePath);

            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            $hasAadhaarBack = userColumnExists($conn, "aadhaar_back");

            if ($hasAadhaarBack) {
                $stmt = $conn->prepare("INSERT INTO users 
                    (name, father_name, mobile, password, role, village_id, status, dob, age, id_type, id_proof, aadhaar_back, profile_photo, created_at)
                    VALUES (?, ?, ?, ?, 'sub_admin', ?, 'pending', ?, ?, ?, ?, ?, ?, NOW())");

                $stmt->bind_param(
                    "ssssissssss",
                    $name,
                    $father_name,
                    $mobile,
                    $hashed_password,
                    $village_id,
                    $dob_db,
                    $age,
                    $id_type,
                    $aadhaar_front,
                    $aadhaar_back,
                    $selfie
                );
            } else {
                $stmt = $conn->prepare("INSERT INTO users 
                    (name, father_name, mobile, password, role, village_id, status, dob, age, id_type, id_proof, profile_photo, created_at)
                    VALUES (?, ?, ?, ?, 'sub_admin', ?, 'pending', ?, ?, ?, ?, ?, NOW())");

                $stmt->bind_param(
                    "ssssisssss",
                    $name,
                    $father_name,
                    $mobile,
                    $hashed_password,
                    $village_id,
                    $dob_db,
                    $age,
                    $id_type,
                    $aadhaar_front,
                    $selfie
                );
            }

            if ($stmt->execute()) {
                $success = "Registration successful. Your mobile number is your username and password is the one you created. Please wait for Village Admin approval.";
            } else {
                $error = "Registration failed. Please try again.";
            }
        }
    }
}

$districts = $conn->query("SELECT id, name FROM districts ORDER BY name ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Villager Register</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<style>
*{box-sizing:border-box}
html,body{margin:0;padding:0;width:100%;min-height:100%;font-family:Arial,sans-serif}
body{
    min-height:100vh;
    background:linear-gradient(135deg,#07111f,#123c88,#0ea5e9);
    padding:18px;
}
.wrap{width:100%;max-width:520px;margin:0 auto}
.card{
    background:rgba(255,255,255,.97);
    border-radius:34px;
    padding:26px 22px;
    box-shadow:0 30px 90px rgba(0,0,0,.35);
}
.logo{
    width:72px;height:72px;margin:0 auto 14px;border-radius:26px;
    background:linear-gradient(135deg,#2563eb,#06b6d4);
    display:flex;align-items:center;justify-content:center;color:#fff;font-size:34px
}
h1{text-align:center;margin:0;font-size:26px;color:#0f172a}
.sub{text-align:center;color:#64748b;margin:8px 0 22px;font-size:14px}
.steps{display:flex;gap:8px;margin-bottom:22px}
.step-dot{
    flex:1;height:7px;border-radius:20px;background:#dbeafe
}
.step-dot.active{background:linear-gradient(135deg,#2563eb,#06b6d4)}
.step{display:none}
.step.active{display:block}
h3{margin:0 0 14px;color:#0f172a}
label{display:block;margin:14px 0 8px;font-size:14px;font-weight:700;color:#334155}
input,select{
    width:100%;height:54px;border:1px solid #dbeafe;border-radius:18px;
    padding:0 16px;font-size:15px;outline:none;background:#f8fafc
}
input[type=file]{height:auto;padding:14px;background:#fff}
input:focus,select:focus{border-color:#2563eb;background:#fff;box-shadow:0 0 0 4px rgba(37,99,235,.12)}
.row{display:grid;grid-template-columns:1fr;gap:0}
.btn{
    width:100%;height:56px;border:0;border-radius:20px;margin-top:20px;
    background:linear-gradient(135deg,#2563eb,#06b6d4);
    color:white;font-size:17px;font-weight:800;cursor:pointer;
    box-shadow:0 14px 30px rgba(37,99,235,.35)
}
.btn-light{
    background:#e2e8f0;color:#0f172a;box-shadow:none
}
.btn-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.alert{padding:13px 15px;border-radius:16px;font-size:14px;font-weight:700;margin-bottom:18px;text-align:center;line-height:1.4}
.error{background:#fee2e2;color:#991b1b}
.success{background:#dcfce7;color:#166534}
.note{
    margin-top:14px;background:#eff6ff;border:1px solid #bfdbfe;color:#1e3a8a;
    padding:13px;border-radius:18px;font-size:13px;line-height:1.5
}
.link{text-align:center;margin-top:20px;color:#64748b;font-size:14px}
.link a{color:#2563eb;font-weight:800;text-decoration:none}
.small{font-size:12px;color:#64748b;margin-top:6px}
@media(min-width:760px){
    .wrap{max-width:760px}
    .row{grid-template-columns:1fr 1fr;gap:14px}
}
@media(max-width:480px){
    body{padding:18px;overflow-y:auto}
    .wrap{margin-top:20px}
    .card{border-radius:30px;padding:25px 20px}
}
</style>
</head>

<body>

<div class="wrap">
<div class="card">

<div class="logo">📝</div>
<h1>Villager Register</h1>
<div class="sub">Complete registration in 3 simple steps</div>

<?php if ($error): ?>
    <div class="alert error"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<?php if ($success): ?>
    <div class="alert success"><?= htmlspecialchars($success) ?></div>
<?php endif; ?>

<div class="steps">
    <div class="step-dot active" id="dot1"></div>
    <div class="step-dot" id="dot2"></div>
    <div class="step-dot" id="dot3"></div>
</div>

<form method="POST" enctype="multipart/form-data" id="registerForm">

    <div class="step active" id="step1">
        <h3>Step 1: Area Selection</h3>

        <label>District *</label>
        <select id="district" required>
            <option value="">Select District</option>
            <?php while($d = $districts->fetch_assoc()): ?>
                <option value="<?= intval($d['id']) ?>"><?= htmlspecialchars($d['name']) ?></option>
            <?php endwhile; ?>
        </select>

        <label>Block *</label>
        <select id="block" required>
            <option value="">Select Block</option>
        </select>

        <label>Village *</label>
        <select name="village_id" id="village" required>
            <option value="">Select Village</option>
        </select>

        <button type="button" class="btn" onclick="nextStep(1)">Next</button>
    </div>

    <div class="step" id="step2">
        <h3>Step 2: Personal Information</h3>

        <div class="row">
            <div>
                <label>Name *</label>
                <input type="text" name="name" id="name" placeholder="Full name" required>
            </div>

            <div>
                <label>Father Name</label>
                <input type="text" name="father_name" placeholder="Father name">
            </div>

            <div>
                <label>Mobile Number *</label>
                <input type="text" name="mobile" id="mobile" maxlength="10" inputmode="numeric" placeholder="10 digit mobile" required>
            </div>

            <div>
                <label>Date of Birth</label>
                <input type="date" name="dob">
            </div>

            <div>
                <label>ID Type</label>
                <select name="id_type">
                    <option value="">Select ID Type</option>
                    <option value="aadhaar">Aadhaar</option>
                    <option value="voter_id">Voter ID</option>
                    <option value="driving_license">Driving License</option>
                    <option value="other">Other</option>
                </select>
            </div>

            <div>
                <label>Aadhaar / ID Front</label>
                <input type="file" name="aadhaar_front" id="aadhaar_front" accept="image/*">
                <div class="small">Image will be compressed before upload.</div>
            </div>

            <div>
                <label>Aadhaar / ID Back</label>
                <input type="file" name="aadhaar_back" id="aadhaar_back" accept="image/*">
                <div class="small">Image will be compressed before upload.</div>
            </div>

            <div>
                <label>Selfie / Profile Photo</label>
                <input type="file" name="selfie" id="selfie" accept="image/*">
                <div class="small">Image will be compressed before upload.</div>
            </div>
        </div>

        <div class="btn-row">
            <button type="button" class="btn btn-light" onclick="prevStep(2)">Back</button>
            <button type="button" class="btn" onclick="nextStep(2)">Next</button>
        </div>
    </div>

    <div class="step" id="step3">
        <h3>Step 3: Create Password</h3>

        <label>Create Password *</label>
        <input type="password" name="password" id="password" placeholder="Minimum 6 characters" required>

        <label>Confirm Password *</label>
        <input type="password" name="confirm_password" id="confirm_password" placeholder="Confirm password" required>

        <div class="note">
            Your mobile number is your username. Use the password you created to login after Village Admin approval.
        </div>

        <div class="btn-row">
            <button type="button" class="btn btn-light" onclick="prevStep(3)">Back</button>
            <button type="submit" class="btn" id="submitBtn">Register</button>
        </div>
    </div>

</form>

<div class="link">
    Already registered? <a href="login.php">Login</a>
</div>

</div>
</div>

<script>
let currentStep = 1;

function showStep(step) {
    document.querySelectorAll(".step").forEach(s => s.classList.remove("active"));
    document.querySelectorAll(".step-dot").forEach(d => d.classList.remove("active"));

    document.getElementById("step" + step).classList.add("active");

    for (let i = 1; i <= step; i++) {
        document.getElementById("dot" + i).classList.add("active");
    }

    currentStep = step;
    window.scrollTo({top: 0, behavior: "smooth"});
}

function nextStep(step) {
    if (step === 1) {
        if (!document.getElementById("district").value || !document.getElementById("block").value || !document.getElementById("village").value) {
            alert("Please select district, block and village.");
            return;
        }
    }

    if (step === 2) {
        const name = document.getElementById("name").value.trim();
        const mobile = document.getElementById("mobile").value.trim();

        if (!name || !mobile) {
            alert("Please enter name and mobile number.");
            return;
        }

        if (!/^[0-9]{10}$/.test(mobile)) {
            alert("Please enter valid 10 digit mobile number.");
            return;
        }
    }

    showStep(step + 1);
}

function prevStep(step) {
    showStep(step - 1);
}

const district = document.getElementById("district");
const block = document.getElementById("block");
const village = document.getElementById("village");

district.addEventListener("change", function () {
    block.innerHTML = '<option value="">Loading...</option>';
    village.innerHTML = '<option value="">Select Village</option>';

    fetch("../api/location/get_blocks.php?district_id=" + this.value)
        .then(res => res.json())
        .then(data => {
            block.innerHTML = '<option value="">Select Block</option>';
            if (data.status) {
                data.data.forEach(item => {
                    block.innerHTML += `<option value="${item.id}">${item.name}</option>`;
                });
            }
        });
});

block.addEventListener("change", function () {
    village.innerHTML = '<option value="">Loading...</option>';

    fetch("../api/location/get_villages.php?block_id=" + this.value)
        .then(res => res.json())
        .then(data => {
            village.innerHTML = '<option value="">Select Village</option>';
            if (data.status) {
                data.data.forEach(item => {
                    village.innerHTML += `<option value="${item.id}">${item.village_name}</option>`;
                });
            }
        });
});

async function compressImageInput(inputId, maxWidth = 1100, quality = 0.70) {
    const input = document.getElementById(inputId);
    if (!input || !input.files || !input.files[0]) return;

    const file = input.files[0];
    if (!file.type.startsWith("image/")) return;

    const img = new Image();
    const reader = new FileReader();

    const loaded = new Promise(resolve => {
        reader.onload = e => {
            img.onload = resolve;
            img.src = e.target.result;
        };
    });

    reader.readAsDataURL(file);
    await loaded;

    let width = img.width;
    let height = img.height;

    if (width > maxWidth) {
        height = Math.round(height * maxWidth / width);
        width = maxWidth;
    }

    const canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;

    canvas.getContext("2d").drawImage(img, 0, 0, width, height);

    const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/jpeg", quality));
    if (!blob) return;

    const newFile = new File([blob], inputId + "_" + Date.now() + ".jpg", {type: "image/jpeg"});
    const dt = new DataTransfer();
    dt.items.add(newFile);
    input.files = dt.files;
}

document.getElementById("registerForm").addEventListener("submit", async function(e) {
    e.preventDefault();

    const pass = document.getElementById("password").value;
    const cpass = document.getElementById("confirm_password").value;

    if (pass.length < 6) {
        alert("Password must be at least 6 characters.");
        return;
    }

    if (pass !== cpass) {
        alert("Password and confirm password do not match.");
        return;
    }

    const btn = document.getElementById("submitBtn");
    btn.innerText = "Compressing images...";
    btn.disabled = true;

    await compressImageInput("aadhaar_front");
    await compressImageInput("aadhaar_back");
    await compressImageInput("selfie");

    btn.innerText = "Submitting...";
    this.submit();
});
</script>

</body>
</html>
