<?php

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

require_once("../config/db.php");

// 🔹 INPUT
$name = $_POST['name'] ?? '';
$father_name = $_POST['father_name'] ?? '';
$mobile = $_POST['mobile'] ?? '';
$dob = $_POST['dob'] ?? '';
$password = $_POST['password'] ?? '';
$village_id = intval($_POST['village_id'] ?? 0);
$id_type = $_POST['id_type'] ?? '';

// 🔹 VALIDATION
if (empty($name) || empty($mobile) || empty($password) || $village_id <= 0) {
    echo json_encode(["status" => false, "message" => "All required fields must be filled"]);
    exit;
}

if (!preg_match('/^[0-9]{10}$/', $mobile)) {
    echo json_encode(["status" => false, "message" => "Invalid mobile number"]);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(["status" => false, "message" => "Password must be at least 6 characters"]);
    exit;
}

// 🎂 DOB FIX (DD-MM-YYYY → YYYY-MM-DD)
$dob_db = null;
$age = null;

if (!empty($dob)) {
    $parts = explode('-', $dob);

    if (count($parts) === 3) {
        $day = $parts[0];
        $month = $parts[1];
        $year = $parts[2];

        if (checkdate((int)$month, (int)$day, (int)$year)) {
            $dob_db = "$year-$month-$day";

            $today = new DateTime();
            $birthDate = new DateTime($dob_db);
            $age = $today->diff($birthDate)->y;
        }
    }
}

// 🔐 HASH PASSWORD
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// 🔍 CHECK MOBILE
$check = $conn->prepare("SELECT id FROM users WHERE mobile=?");
$check->bind_param("s", $mobile);
$check->execute();

if ($check->get_result()->num_rows > 0) {
    echo json_encode(["status" => false, "message" => "Mobile already registered"]);
    exit;
}

// 📁 UPLOAD CONFIG
$uploadDir = "../../uploads/subadmindata/";
$relativePath = "uploads/subadmindata/";

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

// 🔐 ALLOWED TYPES
$allowedTypes = ['jpg', 'jpeg', 'png'];

// 📄 DOCUMENT UPLOAD
$docPath = "";
if (!empty($_FILES['id_proof']['name'])) {

    $ext = strtolower(pathinfo($_FILES['id_proof']['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedTypes)) {
        echo json_encode(["status" => false, "message" => "Invalid document type"]);
        exit;
    }

    $docName = time() . "_doc." . $ext;

    if (move_uploaded_file($_FILES['id_proof']['tmp_name'], $uploadDir . $docName)) {
        $docPath = $relativePath . $docName;
    }
}

// 📸 SELFIE UPLOAD
$selfiePath = "";
if (!empty($_FILES['profile_photo']['name'])) {

    $ext = strtolower(pathinfo($_FILES['profile_photo']['name'], PATHINFO_EXTENSION));

    if (!in_array($ext, $allowedTypes)) {
        echo json_encode(["status" => false, "message" => "Invalid image type"]);
        exit;
    }

    $selfieName = time() . "_selfie." . $ext;

    if (move_uploaded_file($_FILES['profile_photo']['tmp_name'], $uploadDir . $selfieName)) {
        $selfiePath = $relativePath . $selfieName;
    }
}

// 🔹 INSERT
$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,
    $docPath,
    $selfiePath
);

if ($stmt->execute()) {

    // 🔥 ADMIN FETCH
    $admin = $conn->query("
        SELECT name, mobile FROM users 
        WHERE village_id = $village_id 
        AND role='village_admin' LIMIT 1
    ")->fetch_assoc();

    echo json_encode([
        "status" => true,
        "message" => "Registration successful",
        "admin_name" => $admin['name'] ?? 'Village Admin',
        "admin_mobile" => $admin['mobile'] ?? 'N/A'
    ]);

} else {
    echo json_encode([
        "status" => false,
        "message" => "Database error: " . $conn->error
    ]);
}