<?php
// हेडर को शामिल करें
require_once 'header.php';

// सुरक्षा जांच
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}

$message = '';
$message_type = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // फॉर्म से सभी नई फील्ड्स प्राप्त करें
    $name = $_POST['name'];
    $father_name = $_POST['father_name'];
    $contact_no = $_POST['contact_no'];
    $emergency_number = $_POST['emergency_number'];
    $address = $_POST['address'];
    $joining_date = $_POST['joining_date'];
    $email = $_POST['email'];
    $password_input = $_POST['password'];
    $roles = $_POST['roles'] ?? [];
    
    // सिक्योर नोट को अभी के लिए हम खाली सेव करेंगे, इसे एडिट पेज से अपडेट किया जाएगा
    $secure_note = $_POST['secure_note']; 

    if (empty($roles) || empty($name) || empty($email) || empty($password_input)) {
        $message = "Error: Please fill all mandatory fields (*).";
        $message_type = 'error';
    } else {
        $conn->begin_transaction();
        try {
            $password_hash = password_hash($password_input, PASSWORD_DEFAULT);
            
            $stmt = $conn->prepare("INSERT INTO users (name, father_name, contact_no, emergency_number, address, joining_date, email, password_hash, secure_note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->bind_param("sssssssss", $name, $father_name, $contact_no, $emergency_number, $address, $joining_date, $email, $password_hash, $secure_note);
            $stmt->execute();
            
            $new_user_id = $conn->insert_id;
            $stmt->close();

            $stmt_roles = $conn->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
            foreach ($roles as $role_id) {
                $stmt_roles->bind_param("ii", $new_user_id, $role_id);
                $stmt_roles->execute();
            }
            $stmt_roles->close();

            $conn->commit();
            $message = "Employee added successfully!";
            $message_type = 'success';

        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            if ($conn->errno == 1062) {
                $message = "Error: An employee with this email already exists.";
            } else {
                $message = "An error occurred: " . $exception->getMessage();
            }
            $message_type = 'error';
        }
    }
}

// सभी रोल्स प्राप्त करें
$roles_result = $conn->query("SELECT * FROM roles ORDER BY name ASC");
$all_roles = [];
while ($row = $roles_result->fetch_assoc()) {
    $all_roles[] = $row;
}
$conn->close();
?>

<title>Add Employee - Digify OS</title>
<h2 class="text-xl font-bold text-gray-800">Add New Employee</h2>

<main class="p-6 md:p-10">
    <div class="max-w-3xl mx-auto bg-white p-8 rounded-lg shadow-lg">
        <?php if (!empty($message)): ?>
            <div class="mb-6 p-4 rounded <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="add-employee.php">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div><label for="name" class="block text-sm font-medium">Full Name <span class="text-red-500">*</span></label><input type="text" name="name" id="name" required class="mt-1 block w-full ..."></div>
                <div><label for="father_name" class="block text-sm font-medium">Father's Name</label><input type="text" name="father_name" id="father_name" class="mt-1 block w-full ..."></div>
                <div><label for="contact_no" class="block text-sm font-medium">Contact Number</label><input type="text" name="contact_no" id="contact_no" class="mt-1 block w-full ..."></div>
                <div><label for="emergency_number" class="block text-sm font-medium">Emergency Number</label><input type="text" name="emergency_number" id="emergency_number" class="mt-1 block w-full ..."></div>
                <div class="md:col-span-2"><label for="address" class="block text-sm font-medium">Address</label><textarea name="address" id="address" rows="2" class="mt-1 block w-full ..."></textarea></div>
                <div><label for="joining_date" class="block text-sm font-medium">Joining Date</label><input type="date" name="joining_date" id="joining_date" class="mt-1 block w-full ..."></div>
                <div><label for="email" class="block text-sm font-medium">Login Email <span class="text-red-500">*</span></label><input type="email" name="email" id="email" required class="mt-1 block w-full ..."></div>
                <div><label for="password" class="block text-sm font-medium">Password <span class="text-red-500">*</span></label><input type="password" name="password" id="password" required class="mt-1 block w-full ..."></div>
            </div>

            <div class="mt-6">
                <label class="block text-sm font-medium text-gray-700">Roles <span class="text-red-500">*</span></label>
                <div class="mt-2 grid grid-cols-2 sm:grid-cols-4 gap-4">
                    <?php foreach ($all_roles as $role): ?>
                        <label class="inline-flex items-center"><input type="checkbox" name="roles[]" value="<?php echo $role['id']; ?>" class="rounded border-gray-300"><span class="ml-2"><?php echo htmlspecialchars($role['name']); ?></span></label>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="mt-6">
                <label for="secure_note" class="block text-sm font-medium">Secure Note</label>
                <p class="text-xs text-gray-500 mb-2">This note will be encrypted. It can only be viewed on the employee's profile by entering a profile password.</p>
                <textarea name="secure_note" id="secure_note" rows="3" class="mt-1 block w-full ..."></textarea>
            </div>

            <div class="flex justify-end mt-8">
                <a href="employees.php" class="px-4 py-2 border rounded-md">Cancel</a>
                <button type="submit" class="ml-3 px-4 py-2 bg-blue-600 text-white rounded-md">Save Employee</button>
            </div>
        </form>
    </div>
</main>

<?php
// फुटर को शामिल करें
require_once 'footer.php';
?>