<?php 
session_start();
include 'includes/header.php'; 
include 'includes/sidebar.php'; 
include 'includes/connect.php'; 

$upload_dir = "uploads/aadhar/";
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// ✅ Logged-in distributor
$logged_in_id = $_SESSION['distributor_id'];
$logged_in_role = $_SESSION['role'];

// print_r($logged_in_role);die;
if($logged_in_role == 'Super-Admin'){

    // 🔥 Super Admin → ALL distributors
    $parent_query = "SELECT id, name 
                     FROM distributor 
                     WHERE role='distributor'
                     ORDER BY name ASC";

} else {

    // 🔥 Distributor → only self
    $parent_query = "SELECT id, name 
                     FROM distributor 
                     WHERE id='$logged_in_id' 
                     AND role='distributor'
                     ORDER BY name ASC";
}

$parent_result = mysqli_query($conn, $parent_query);

if(isset($_POST['submit_sub_distributor'])){

    // ✅ Force parent from session (secure)
    $parent_id = $_SESSION['distributor_id'];

    $name    = $_POST['name'];
    $email   = $_POST['email'];
    $mobile  = $_POST['mobile'];
    $address = $_POST['address'];
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $status  = $_POST['status'];
    $aadhar_number = $_POST['aadhar_number'];

    $file_name = $_FILES['aadhar_file']['name'];
    $file_tmp  = $_FILES['aadhar_file']['tmp_name'];

    if(empty($parent_id)){
        $error = "Distributor not found";
    } else {

        $ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','pdf'];

        if(!in_array($ext, $allowed)){
            $error = "Invalid file";
        } else {

            $new_name = time().'_'.rand(1000,9999).'.'.$ext;
            $path = $upload_dir.$new_name;

            if(move_uploaded_file($file_tmp, $path)){

                $query = "INSERT INTO distributor 
                (parent_id, name, email, mobile, address, password, status, role, aadhar_number, aadhar_file, created_at) 
                VALUES 
                ('$parent_id', '$name', '$email', '$mobile', '$address', '$password', '$status', 'nursery', '$aadhar_number', '$new_name', NOW())";

                if(mysqli_query($conn, $query)){
                    echo "<script>alert('Sub Nursery Added'); window.location.href='distributor_list.php';</script>";
                    exit;
                } else {
                    $error = "DB Error";
                }

            } else {
                $error = "Upload failed";
            }
        }
    }
}
?>
// <script>
// alert("Role: <?php echo $logged_in_role; ?>");
// </script>
<div class="main-content-inner">
<div class="main-content-wrap">

<div class="flex items-center justify-between mb-30">
    <h3>Add Sub Nursery</h3>
</div>

<?php if(isset($error)){ ?>
<div class="text-red-500 mb-4"><?php echo $error; ?></div>
<?php } ?>

<form method="POST" enctype="multipart/form-data" class="form-add-category">

<div class="wg-box mb-30">
<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap:20px;">

<fieldset>
<div class="body-title mb-10">Select Distributor *</div>
<select name="parent_id" required>
<option value="">-- Select --</option>
<?php while($row = mysqli_fetch_assoc($parent_result)){ ?>
<option value="<?php echo $row['id']; ?>">
    <?php echo $row['name']; ?>
</option>
<?php } ?>
</select>
</fieldset>

<fieldset>
<div class="body-title mb-10">Name *</div>
<input type="text" name="name" placeholder="Name" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Email *</div>
<input type="email" name="email" placeholder="Email" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Mobile *</div>
<input type="text" name="mobile" placeholder="Mobile" maxlength="10" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Address *</div>
<input type="text" name="address" placeholder="Address" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Password *</div>
<input type="password" name="password" placeholder="Password" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Status *</div>
<select name="status">
<option value="Active">Active</option>
<option value="Inactive">Inactive</option>
</select>
</fieldset>

<fieldset>
<div class="body-title mb-10">Aadhar *</div>
<input type="text" name="aadhar_number" placeholder="Aadhar" required>
</fieldset>

<fieldset>
<div class="body-title mb-10">Upload Aadhar *</div>
<input type="file" name="aadhar_file" required>
</fieldset>

</div>
</div>

<div class="cols gap10" style="display:flex; gap:20px;">
<button class="tf-button w380" type="submit" name="submit_sub_distributor">Add Sub Nursery</button>
<a href="distributor_list.php" class="tf-button style-3 w380">Cancel</a>
</div>

</form>

</div>
</div>

<?php include 'includes/footer.php'; ?>