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

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

// Insert Code
if(isset($_POST['submit_distributor'])){

    $name    = mysqli_real_escape_string($conn, $_POST['name']);
    $email   = mysqli_real_escape_string($conn, $_POST['email']);
    $mobile  = mysqli_real_escape_string($conn, $_POST['mobile']);
    $address = mysqli_real_escape_string($conn, $_POST['address']);
    $password_raw = $_POST['password'];
    $status  = mysqli_real_escape_string($conn, $_POST['status']);
    $aadhar_number = mysqli_real_escape_string($conn, $_POST['aadhar_number']);

    // Secure password
    $password = password_hash($password_raw, PASSWORD_DEFAULT);

    // File Upload
    $file_name = $_FILES['aadhar_file']['name'];
    $file_tmp  = $_FILES['aadhar_file']['tmp_name'];
    $file_size = $_FILES['aadhar_file']['size'];
    $file_error= $_FILES['aadhar_file']['error'];

    // Validation
    if(empty($name) || empty($email) || empty($mobile) || empty($address) || empty($password_raw) || empty($aadhar_number)){
        $error = "All fields are required";
    } elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $error = "Invalid email format";
    } elseif(!preg_match('/^[0-9]{10,15}$/', $mobile)){
        $error = "Mobile must be number and 10-15 digits";
    } elseif(!preg_match('/^[0-9]{12}$/', $aadhar_number)){
        $error = "Aadhar must be 12 digits";
    } elseif($file_error !== 0){
        $error = "File upload error";
    } else {

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

        if(!in_array($file_ext, $allowed_ext)){
            $error = "Only JPG, PNG, PDF allowed";
        } elseif($file_size > 2*1024*1024){
            $error = "File must be less than 2MB";
        } else {

            $new_file_name = time() . "_" . rand(1000,9999) . "." . $file_ext;
            $final_path = $upload_dir . $new_file_name;

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

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

                if(mysqli_query($conn, $query)){
                    echo "<script>alert('Distributor Added Successfully'); window.location.href='distributor_list.php';</script>";
                    exit;
                } else {
                    $error = "Database error: ".mysqli_error($conn);
                }

            } else {
                $error = "File upload failed";
            }
        }
    }
}
?>

<div class="main-content-inner">
    <div class="main-content-wrap">

        <div class="flex items-center flex-wrap justify-between gap20 mb-30">
            <h3>Add Nursury</h3>
        </div>

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

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

            <div class="wg-box mb-30">

                <!-- SAME GRID (UNCHANGED) -->
                <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap:20px;">

                    <fieldset>
                        <div class="body-title mb-10">Distributor Name <span class="tf-color-1">*</span></div>
                        <input type="text" name="name" placeholder="Enter Name" required>
                    </fieldset>

                    <fieldset>
                        <div class="body-title mb-10">Distributor Email <span class="tf-color-1">*</span></div>
                        <input type="email" name="email" placeholder="Enter Email" required>
                    </fieldset>

                    <fieldset>
                        <div class="body-title mb-10">Distributor Mobile <span class="tf-color-1">*</span></div>
                        <input type="text" name="mobile" placeholder="Enter Mobile No" maxlength="10" required>
                    </fieldset>

                    <fieldset>
                        <div class="body-title mb-10">Distributor Address <span class="tf-color-1">*</span></div>
                        <input type="text" name="address" placeholder="Enter Address" required>
                    </fieldset>

                    <fieldset>
                        <div class="body-title mb-10">Login Password <span class="tf-color-1">*</span></div>
                        <input type="password" name="password" placeholder="Enter Password" required>
                    </fieldset>

                    <fieldset>
                        <div class="body-title mb-10">Status <span class="tf-color-1">*</span></div>
                        <select name="status" required>
                            <option value="Active" selected>Active</option>
                            <option value="Inactive">Inactive</option>
                        </select>
                    </fieldset>

                    <!-- ✅ NEW FIELD (MATCHING SAME STYLE) -->
                    <fieldset>
                        <div class="body-title mb-10">Aadhar Number <span class="tf-color-1">*</span></div>
                        <input type="text" name="aadhar_number" placeholder="Enter 12 Digit Aadhar" required>
                    </fieldset>

                    <!-- ✅ FILE UPLOAD (SAME UI STYLE) -->
                    <fieldset>
                        <div class="body-title mb-10">Upload Aadhar Card <span class="tf-color-1">*</span></div>
                        <input type="file" name="aadhar_file" accept=".jpg,.jpeg,.png,.pdf" required>
                    </fieldset>

                </div>

            </div>

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

        </form>
    </div>
</div>

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