<?php
// This script assumes it is included in admin_dashboard.php, 
// so the $conn object (database connection) and $_SESSION data are already available.

$status_message = '';

// Define upload directories
$photo_upload_dir = 'uploads/employee_photos/'; 
$nid_upload_dir = 'uploads/employee_nids/'; 

// 1. Ensure required directories exist
if (!is_dir($photo_upload_dir)) { mkdir($photo_upload_dir, 0777, true); }
if (!is_dir($nid_upload_dir)) { mkdir($nid_upload_dir, 0777, true); }


// --- A. Logic for Adding a New Employee ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_employee'])) {
    
    // 1. Get and sanitize input
    $name = $conn->real_escape_string($_POST['name']);
    $phone = $conn->real_escape_string($_POST['phone_number']);
    $email = $conn->real_escape_string($_POST['email']);
    $blood_group = $conn->real_escape_string($_POST['blood_group']);
    $bank_details = $conn->real_escape_string($_POST['bank_details']);

    $photo_path = '';
    $nid_path = '';

    // 2. Handle Photo Upload (PNG file)
    if (isset($_FILES['photo']) && $_FILES['photo']['error'] == 0) {
        $photo_ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));
        if ($photo_ext === 'png') {
            $photo_file_name = uniqid('photo_') . '.' . $photo_ext;
            $photo_target = $photo_upload_dir . $photo_file_name;
            if (move_uploaded_file($_FILES['photo']['tmp_name'], $photo_target)) {
                $photo_path = $photo_target;
            } else {
                $status_message .= "<p style='color:orange;'>Warning: Photo upload failed.</p>";
            }
        } else {
             $status_message .= "<p style='color:orange;'>Warning: Photo must be a PNG file.</p>";
        }
    }

    // 3. Handle NID Upload (PDF file)
    if (isset($_FILES['nid']) && $_FILES['nid']['error'] == 0) {
        $nid_ext = strtolower(pathinfo($_FILES['nid']['name'], PATHINFO_EXTENSION));
        if ($nid_ext === 'pdf') {
            $nid_file_name = uniqid('nid_') . '.' . $nid_ext;
            $nid_target = $nid_upload_dir . $nid_file_name;
            if (move_uploaded_file($_FILES['nid']['tmp_name'], $nid_target)) {
                $nid_path = $nid_target;
            } else {
                $status_message .= "<p style='color:orange;'>Warning: NID document upload failed.</p>";
            }
        } else {
            $status_message .= "<p style='color:orange;'>Warning: NID must be a PDF file.</p>";
        }
    }

    // 4. Insert data into the employees table
    $sql = "INSERT INTO employees (name, phone_number, email, photo_path, nid_path, blood_group, bank_details) 
            VALUES (?, ?, ?, ?, ?, ?, ?)";
    
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("sssssss", $name, $phone, $email, $photo_path, $nid_path, $blood_group, $bank_details);
    
    if ($stmt->execute()) {
        echo "<script>alert('✅ Success! Employee {$name} added to the database.');</script>";
    } else {
        $status_message .= "<p style='color:red;'>Error adding employee to database: " . $conn->error . "</p>";
        // Cleanup files if database insert fails
        if ($photo_path) unlink($photo_path);
        if ($nid_path) unlink($nid_path);
    }
    $stmt->close();
}


// --- B. Logic for Viewing All Employees (Data Fetch) ---
$employee_data = [];
$sql_view = "SELECT 
                employee_id, name, phone_number, email, blood_group, bank_details, photo_path, nid_path
            FROM employees 
            ORDER BY name ASC";

$result = $conn->query($sql_view);

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $employee_data[] = $row;
    }
}
?>

<style>
    /* Specific styling for the Employee Modal/Popup */
    .employee-modal {
        display: none; /* Hidden by default */
        position: fixed; 
        z-index: 1001; /* Must be higher than the dashboard content */
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        overflow: auto;
        background-color: rgba(0,0,0,0.6); /* Semi-transparent background */
        backdrop-filter: blur(5px);
    }
    .employee-modal-content {
        background-color: #fff;
        margin: 5% auto; /* Centered vertically and horizontally */
        padding: 25px;
        border-radius: 12px;
        width: 95%; 
        max-width: 1100px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.5);
        position: relative;
        max-height: 85vh;
        overflow-y: auto;
    }
    .modal-close {
        color: #aaa;
        float: right;
        font-size: 36px;
        font-weight: bold;
        transition: color 0.3s;
    }
    .modal-close:hover,
    .modal-close:focus {
        color: #e74c3c;
        text-decoration: none;
        cursor: pointer;
    }
    .file-link {
        color: #3498db;
        text-decoration: underline;
        font-weight: bold;
    }
</style>

<div class="form-card">
    <h3>Employee Database Viewer</h3>
    <p>The database currently contains <?php echo count($employee_data); ?> records.</p>
    
    <!-- The Button to show the data in a popup -->
    <button onclick="document.getElementById('employeeDataModal').style.display='block'" 
           style="background-color: #3498db; color: white; padding: 10px 25px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer;">
        <b>View All Employee Details<b/>
    </button>
</div>

<!-- Employee Data Modal (Popup Box) -->
<div id="employeeDataModal" class="employee-modal">
    <div class="employee-modal-content">
        <span class="modal-close" onclick="document.getElementById('employeeDataModal').style.display='none'">&times;</span>
        <h2>Full Employee Database Records</h2>
        <p>This shows confidential employee information. Access is restricted to Admin only.</p>

        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Contact</th>
                    <th>Blood Group</th>
                    <th>Bank Details</th>
                    <th>Photo (PNG)</th>
                    <th>NID (PDF)</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($employee_data)): ?>
                    <tr><td colspan="7" style="text-align: center;">No employee records found. Use the form below to add one.</td></tr>
                <?php else: ?>
                    <?php foreach ($employee_data as $employee): ?>
                    <tr>
                        <td><?php echo htmlspecialchars($employee['employee_id']); ?></td>
                        <td><?php echo htmlspecialchars($employee['name']); ?></td>
                        <td><?php echo htmlspecialchars($employee['phone_number']) . "<br>" . htmlspecialchars($employee['email']); ?></td>
                        <td><?php echo htmlspecialchars($employee['blood_group']); ?></td>
                        <td><?php echo htmlspecialchars($employee['bank_details']); ?></td>
                        <td>
                            <?php if ($employee['photo_path']): ?>
                                <a href="<?php echo htmlspecialchars($employee['photo_path']); ?>" target="_blank" class="file-link">View Photo</a>
                            <?php else: ?>
                                N/A
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($employee['nid_path']): ?>
                                <a href="<?php echo htmlspecialchars($employee['nid_path']); ?>" target="_blank" class="file-link">View NID</a>
                            <?php else: ?>
                                N/A
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- --- Add Employee Form --- -->
<div class="form-card" style="margin-top: 30px;">
    <h3>Add New Employee Record</h3>
    
    
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=view_employees" method="post" enctype="multipart/form-data">
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
            <div>
                <label for="name">Name:</label>
                <input type="text" name="name" id="name" required>

                <label for="phone_number">Phone Number:</label>
                <input type="text" name="phone_number" id="phone_number" required>

                <label for="email">Email Address:</label>
                <input type="email" name="email" id="email" required>

                <label for="blood_group">Blood Group:</label>
                <input type="text" name="blood_group" id="blood_group" required>
            </div>
            <div>
                <label for="bank_details">Bank Details (Account No., etc.):</label>
                <input type="text" name="bank_details" id="bank_details" required>

                <label for="photo">Photo (PNG file only):</label>
                <input type="file" name="photo" id="photo" accept=".png" required style="width: auto;">
                
                <label for="nid">NID (PDF file only):</label>
                <input type="file" name="nid" id="nid" accept=".pdf" required style="width: auto;">
            </div>
        </div>
        <button type="submit" name="add_employee"><b>Add Employee to Database</b></button>
    </form>
</div>
