<?php

require('../lib/dbclass.php');

$id = $_POST['id'];

if (!$id) {
    $id = 0;
}


if ($_POST['clubid'] == '') {
    $_POST['clubid'] = 0;
}



if ($id > 0) {
    $usertype = 2;
    unset($_POST['user_type1']);
    unset($_POST['user_type']);
} else {
    $usertype = 2;
    unset($_POST['user_type1']);
    $_POST['user_type'] = 2;
}

if ($_POST['ward_id'] == '') {
    // Step 1: Ensure default Assembly
    $assembly = findQuery("SELECT id FROM tbl_assembly WHERE name = 'NA' AND district = 1 LIMIT 1");

    if (!$assembly) {
        $assemblyData = [
            'name'     => 'NA',
            'district' => 1,
        ];
        $assembly_id = saveArray('tbl_assembly', $assemblyData, 0);
    } else {
        $assembly_id = $assembly[0]['id'];
    }


    // Step 2: Ensure default Panchayat
    $panchayat = findQuery("SELECT id FROM tbl_panchayat WHERE panchayat_name = 'NA' AND assembly_id = $assembly_id LIMIT 1");

    if (!$panchayat) {
        $panchayatData = [
            'panchayat_name' => 'NA',
            'assembly_id'    => $assembly_id,
        ];
        $panchayat_id = saveArray('tbl_panchayat', $panchayatData, 0);
    } else {
        $panchayat_id = $panchayat[0]['id'];
    }


    // Step 3: Ensure default Ward
    $ward = findQuery("SELECT id FROM tbl_ward WHERE ward_name = 'NA' AND panchayat_id = $panchayat_id LIMIT 1");

    if (!$ward) {
        $wardData = [
            'ward_name'    => 'NA',
            'panchayat_id' => $panchayat_id,

        ];
        $_POST['ward_id'] = saveArray('tbl_ward', $wardData, 0);
    } else {
        $_POST['ward_id'] = $ward[0]['id'];
    }
}



unset($_POST['club_needed']);

$name = $_POST['name'];

$ward_name = $_POST['ward_id'];

$totalward = findQuery("select COUNT(*) nos from tbl_user where ward_id='$ward_name' and name='$name' and  user_type=$usertype and status=0 and id!=$id");
$count     = $totalward[0]['nos'];




if ($count > 0) {
    $message = 'Already Taken.';


    $encodedMessage = urlencode($message);



    $url = "add_user.php?message={$encodedMessage}";

    // Redirect to the new URL
    echo "<script>window.location.href='{$url}';</script>";
} else {
    unset($_POST['id']);


    $idnew = saveArray('tbl_user', $_POST, $id);

    $password = $name . '-' . $idnew;
    $password = encrypt($password);

    if ($idnew != $id) {
        updateQuery("update tbl_user set username=concat(10000,$idnew),password='$password' where id=$idnew");
    }
}

if ($idnew) {
    $message = 'Registered successfully!';



    $encodedMessage = urlencode($message);



    $url = "add_user.php?message={$encodedMessage}";

    // Redirect to the new URL
    echo "<script>window.location.href='{$url}';</script>";
} else {
    $message = 'Something went wrong, please try again.';


    $encodedMessage = urlencode($message);



    $url = "add_user.php?message={$encodedMessage}";

    // Redirect to the new URL
    echo "<script>window.location.href='{$url}';</script>";
}
