<?php
include "dbconnect.php";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = trim($_POST['name']);
    $father_name = trim($_POST['father_name']);
    $qualification = trim($_POST['qualification']);
    $mobile_no = trim($_POST['mobile_no']);
    $email_id = trim($_POST['email_id']);
    $address = trim($_POST['address']);
    $city = trim($_POST['city']);
    $state = trim($_POST['state']);
    $adharno = trim($_POST['adharno']);
    $pancard = trim($_POST['pancard']);
    $message = trim($_POST['message']);

    // आधार और पैन कार्ड से डुप्लिकेट एंट्री चेक करें
    $check_query = $con->prepare("SELECT id FROM agents WHERE adharno = ? OR pancard = ?");
    $check_query->bind_param("ss", $adharno, $pancard);
    $check_query->execute();
    $result = $check_query->get_result();

    if ($result->num_rows > 0) {
        header("Location: agent.php?error=duplicate");
        exit();
    }
    $check_query->close();

    // मोबाइल और ईमेल वैलिडेशन
    if (!preg_match('/^[0-9]{10}$/', $mobile_no)) {
        header("Location: agent.php?error=invalid_mobile");
        exit();
    }
    if (!filter_var($email_id, FILTER_VALIDATE_EMAIL)) {
        header("Location: agent.php?error=invalid_email");
        exit();
    }

    // आधार और पैन कार्ड वैलिडेशन
    if (!preg_match('/^[0-9]{12}$/', $adharno)) {
        header("Location: agent.php?error=invalid_adhar");
        exit();
    }
    if (!preg_match('/^[A-Z]{5}[0-9]{4}[A-Z]{1}$/', $pancard)) {
        header("Location: agent.php?error=invalid_pan");
        exit();
    }

    // फाइल अपलोड
    $target_dir = "uploads/";
    $file_name = $_FILES["document_upload"]["name"];
    $file_tmp = $_FILES["document_upload"]["tmp_name"];
    $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

    if (!in_array($file_ext, ["pdf", "jpg", "jpeg"])) {
        header("Location: agent.php?error=invalid_file");
        exit();
    }

    $new_file_name = uniqid("doc_") . "." . $file_ext;
    $target_file = $target_dir . $new_file_name;

    if (move_uploaded_file($file_tmp, $target_file)) {
        $stmt = $con->prepare("INSERT INTO agents (name, father_name, qualification, mobile_no, email_id, address, city, state, adharno, pancard, document_upload, message) 
                               VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssssssssss", $name, $father_name, $qualification, $mobile_no, $email_id, $address, $city, $state, $adharno, $pancard, $new_file_name, $message);

        if ($stmt->execute()) {
            header("Location: agent.php?success=1");
            exit();
        } else {
            header("Location: agent.php?error=insert_fail");
            exit();
        }
        $stmt->close();
    } else {
        header("Location: agent.php?error=file_upload");
        exit();
    }
}
?>
