<?php
// --- 0. DEPENDENCY INCLUDES ---
// Since 'header.php' was moved down, we MUST include the file here 
// that defines the $conn database object and the userHasRole() function.
// NOTE: Please replace 'init.php' with the actual file path that defines these utilities.
require_once 'init.php'; 

// ***************************************************************
// START: HEADERS-FIRST BLOCK (Redirects and POST handling moved to the top)
// ***************************************************************

// NOTE: This entire block MUST be before any HTML output, including the output generated by 'header.php'.

// --- 1. INITIAL SETUP AND SECURITY CHECKS ---
// Assuming userHasRole and $conn dependencies are loaded either globally or from an early include.

// सुरक्षा जांच
if (!userHasRole(['Admin', 'Manager'])) {
    header("Location: dashboard.php");
    exit();
}
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header("Location: employees.php");
    exit();
}
$employee_id = (int)$_GET['id'];
$message = '';
$message_type = '';


// --- 2. ALL POST HANDLING AND REDIRECTS ---

// --- DELETE EMPLOYEE LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_employee'])) {
    // केवल एडमिन को ही यह कार्रवाई करने की अनुमति दें
    if (userHasRole(['Admin'])) {
        $admin_password_input = $_POST['admin_password'] ?? '';
        $FIXED_PASSWORD = "Hvsk@9024"; // फिक्स्ड एडमिन पासवर्ड

        // 1. फिक्स्ड पासवर्ड की जाँच करें
        if ($admin_password_input === $FIXED_PASSWORD) {
            // NOTE: $conn must be defined before this point, likely via a dependency file.
            $conn->begin_transaction();
            try {
                // 2. Foreign Key constraints के कारण पहले user_roles से एंट्रीज डिलीट करें
                $conn->query("DELETE FROM user_roles WHERE user_id = $employee_id");
                
                // 3. यूजर्स टेबल से कर्मचारी को डिलीट करें
                $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
                
                if ($stmt === false) {
                    throw new Exception("Failed to prepare Delete query. MySQLi Error: " . $conn->error);
                }

                $stmt->bind_param("i", $employee_id);
                $stmt->execute();
                $stmt->close();
                
                $conn->commit();
                
                // सफलतापूर्वक डिलीट होने पर एम्प्लॉई लिस्ट पर रीडायरेक्ट करें
                header("Location: employees.php?status=deleted");
                exit();

            } catch (Exception $e) {
                $conn->rollback();
                $message = "Database Error: Deletion failed. " . $e->getMessage();
                $message_type = 'error';
            } catch (mysqli_sql_exception $e) {
                 $conn->rollback();
                $message = "Database Error: Deletion failed. " . $e->getMessage();
                $message_type = 'error';
            }
        } else {
            $message = "Error: Invalid admin password. Deletion failed.";
            $message_type = 'error';
        }
    } else {
        $message = "Error: Only Admin users can delete employees.";
        $message_type = 'error';
    }
}

// --- UPDATE EMPLOYEE LOGIC ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_employee'])) {
    // फॉर्म से सभी फील्ड्स प्राप्त करें
    $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'];
    $daily_target = $_POST['daily_target'];
    $roles = $_POST['roles'] ?? [];
    $secure_note = $_POST['secure_note'];

    if (empty($roles) || empty($name) || empty($email)) {
        $message = "Error: Please fill all mandatory fields (*).";
        $message_type = 'error';
    } else {
        $conn->begin_transaction();
        try {
            // यूजर्स टेबल को अपडेट करें
            $stmt = $conn->prepare("UPDATE users SET name = ?, father_name = ?, contact_no = ?, emergency_number = ?, address = ?, joining_date = ?, email = ?, daily_target = ?, secure_note = ? WHERE id = ?");
            $stmt->bind_param("sssssssssi", $name, $father_name, $contact_no, $emergency_number, $address, $joining_date, $email, $daily_target, $secure_note, $employee_id);
            $stmt->execute();
            
            // पुराने रोल्स डिलीट करें
            $conn->query("DELETE FROM user_roles WHERE user_id = $employee_id");

            // नए रोल्स डालें
            if (!empty($roles)) {
                $stmt_roles = $conn->prepare("INSERT INTO user_roles (user_id, role_id) VALUES (?, ?)");
                foreach ($roles as $role_id) {
                    $stmt_roles->bind_param("ii", $employee_id, $role_id);
                    $stmt_roles->execute();
                }
                $stmt_roles->close();
            }
            
            $conn->commit();
            $message = "Employee details updated successfully!";
            $message_type = 'success';
        } catch (mysqli_sql_exception $exception) {
            $conn->rollback();
            $message = "Error updating employee: " . $exception->getMessage();
            $message_type = 'error';
        }
    }
}

// URL parameters से मैसेज दिखाएं
if (isset($_GET['status']) && $_GET['status'] === 'deleted') {
    $message = "Employee successfully DELETED from the system.";
    $message_type = 'success';
}


// ***************************************************************
// END: HEADERS-FIRST BLOCK
// ***************************************************************


// --- 3. LOAD HEADER AND FETCH DATA (Output starts after this point) ---
// हेडर को शामिल करें (Moved down from line 3)
require_once 'header.php'; 

// --- DATA FETCHING ---
// NOTE: $conn must be defined before this point, likely via a dependency file included before header.php.
$stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
$stmt->bind_param("i", $employee_id);
$stmt->execute();
$employee = $stmt->get_result()->fetch_assoc();
if (!$employee) {
    // अगर कर्मचारी डिलीट हो गया है, तो कर्मचारियों की सूची पर रीडायरेक्ट करें
    header("Location: employees.php"); 
    exit();
}
$stmt->close();

$all_roles_result = $conn->query("SELECT * FROM roles ORDER BY name ASC");
$all_roles = [];
while ($row = $all_roles_result->fetch_assoc()) { $all_roles[] = $row; }

$user_roles_result = $conn->query("SELECT role_id FROM user_roles WHERE user_id = $employee_id");
$user_roles = [];
while ($row = $user_roles_result->fetch_assoc()) { $user_roles[] = $row['role_id']; }

$conn->close();
?>

<title>Edit Employee - <?php echo htmlspecialchars($employee['name']); ?></title>
<h2 class="text-xl font-bold text-gray-800">Edit Employee Details</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="edit-employee.php?id=<?php echo $employee_id; ?>">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div><label class="block text-sm font-medium">Full Name <span class="text-red-500">*</span></label><input type="text" name="name" value="<?php echo htmlspecialchars($employee['name']); ?>" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="block text-sm font-medium">Father's Name</label><input type="text" name="father_name" value="<?php echo htmlspecialchars($employee['father_name']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="block text-sm font-medium">Contact Number</label><input type="text" name="contact_no" value="<?php echo htmlspecialchars($employee['contact_no']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="block text-sm font-medium">Emergency Number</label><input type="text" name="emergency_number" value="<?php echo htmlspecialchars($employee['emergency_number']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div class="md:col-span-2"><label class="block text-sm font-medium">Address</label><textarea name="address" rows="2" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><?php echo htmlspecialchars($employee['address']); ?></textarea></div>
                <div><label class="block text-sm font-medium">Joining Date</label><input type="date" name="joining_date" value="<?php echo htmlspecialchars($employee['joining_date']); ?>" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="block text-sm font-medium">Login Email <span class="text-red-500">*</span></label><input type="email" name="email" value="<?php echo htmlspecialchars($employee['email']); ?>" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></div>
                <div><label class="block text-sm font-medium">Daily Task Target</label><input type="number" name="daily_target" value="<?php echo htmlspecialchars($employee['daily_target']); ?>" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"></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']; ?>" <?php if(in_array($role['id'], $user_roles)) echo 'checked'; ?> 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 class="block text-sm font-medium">Secure Note</label>
                <p class="text-xs text-gray-500 mb-2">This note is encrypted and can only be viewed on the profile page.</p>
                <textarea name="secure_note" rows="3" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm"><?php echo htmlspecialchars($employee['secure_note']); ?></textarea>
            </div>

            <div class="flex justify-between mt-8">
                <!-- Left side: Delete Button (Only for Admin) -->
                <?php if (userHasRole(['Admin'])): ?>
                    <button type="button" onclick="document.getElementById('deleteModal').classList.remove('hidden')" class="px-4 py-2 bg-red-600 text-white rounded-md shadow-md hover:bg-red-700 transition duration-150">Delete Employee</button>
                <?php endif; ?>

                <!-- Right side: Save/Cancel Buttons -->
                <div class="flex justify-end">
                    <a href="employees.php" class="px-4 py-2 border rounded-md">Cancel</a>
                    <button type="submit" name="update_employee" class="ml-3 px-4 py-2 bg-blue-600 text-white rounded-md shadow-md hover:bg-blue-700 transition duration-150">Save Changes</button>
                </div>
            </div>
        </form>
    </div>
</main>

<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50">
    <div class="relative top-20 mx-auto p-5 border w-96 shadow-lg rounded-md bg-white">
        <div class="mt-3 text-center">
            <h3 class="text-lg leading-6 font-medium text-gray-900">Confirm Permanent Deletion</h3>
            <p class="mt-2 text-sm text-gray-500">Are you sure you want to **PERMANENTLY DELETE** **<?php echo htmlspecialchars($employee['name']); ?>**? This action cannot be undone and requires Admin password verification.</p>
            <div class="mt-4 px-7 py-3">
                <form method="POST" action="edit-employee.php?id=<?php echo $employee_id; ?>">
                    <input type="password" name="admin_password" placeholder="Enter Admin Fixed Password (Hvsk@9024)" required class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-red-500 focus:border-red-500">
                    <div class="flex justify-center mt-4 space-x-4">
                        <button type="button" onclick="document.getElementById('deleteModal').classList.add('hidden')" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition duration-150">Cancel</button>
                        <button type="submit" name="delete_employee" class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition duration-150">DELETE PERMANENTLY</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

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