<?php
// Check permission
if(!isAdmin() && !isManager()) {
    echo "<div class='alert alert-danger'>Access Denied</div>";
    exit();
}

// Handle form submission
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_employee'])) {
    $full_name = $_POST['full_name'];
    $nic = $_POST['nic'];
    $contact = $_POST['contact'];
    $department = $_POST['department'];
    $emp_type = $_POST['employment_type'];
    $join_date = $_POST['join_date'];
    $salary = $_POST['salary'];
    $allowance = $_POST['allowance'] ?? 0;
    
    // Create user first
    $default_password = password_hash('password123', PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, 'employee')");
    $stmt->execute([strtolower(str_replace(' ', '.', $full_name)), $default_password, $nic.'@company.com']);
    
    $user_id = $pdo->lastInsertId();
    
    // Create employee record with allowance
    $stmt = $pdo->prepare("INSERT INTO employees (user_id, full_name, nic_passport, contact_number, department, employment_type, join_date, salary, allowance) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $full_name, $nic, $contact, $department, $emp_type, $join_date, $salary, $allowance]);
    
    echo "<div class='alert alert-success'>Employee added successfully!</div>";
}

// Fetch employees
$stmt = $pdo->query("SELECT * FROM employees ORDER BY join_date DESC");
$employees = $stmt->fetchAll();
?>

<!-- Add salary management button -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>Employee Profiles</h2>
    <div>
        <?php if (isAdmin() || hasPermission('manage_salary')): ?>
        <a href="dashboard.php?page=salary_update" class="btn btn-success me-2">
            <i class="bi bi-cash-coin me-1"></i> Manage Salary
        </a>
        <?php endif; ?>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addEmployeeModal">
            <i class="bi bi-plus-circle me-1"></i> Add Employee
        </button>
    </div>
</div>

<!-- Add Employee Modal -->
<div class="modal fade" id="addEmployeeModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST">
                <div class="modal-header">
                    <h5 class="modal-title">Add New Employee</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Full Name</label>
                            <input type="text" name="full_name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>NIC/Passport</label>
                            <input type="text" name="nic" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Contact Number</label>
                            <input type="text" name="contact" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Department</label>
                            <select name="department" class="form-control" required>
                                <option value="">Select</option>
                                <option value="IT">IT</option>
                                <option value="HR">HR</option>
                                <option value="Finance">Finance</option>
                                <option value="Marketing">Marketing</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Employment Type</label>
                            <select name="employment_type" class="form-control" required>
                                <option value="full-time">Full Time</option>
                                <option value="part-time">Part Time</option>
                                <option value="intern">Intern</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Join Date</label>
                            <input type="date" name="join_date" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Salary</label>
                            <input type="number" name="salary" class="form-control" step="0.01" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Allowance</label>
                            <input type="number" name="allowance" class="form-control" step="0.01" value="0">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_employee" class="btn btn-primary">Save Employee</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Employees Table -->
<div class="card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>NIC/Passport</th>
                        <th>Department</th>
                        <th>Type</th>
                        <th>Salary</th>
                        <th>Allowance</th>
                        <th>Join Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($employees as $emp): ?>
                    <tr>
                        <td>EMP<?php echo str_pad($emp['id'], 4, '0', STR_PAD_LEFT); ?></td>
                        <td><?php echo htmlspecialchars($emp['full_name']); ?></td>
                        <td><?php echo htmlspecialchars($emp['nic_passport']); ?></td>
                        <td><?php echo htmlspecialchars($emp['department']); ?></td>
                        <td>
                            <span class="badge bg-<?php 
                                echo $emp['employment_type'] == 'full-time' ? 'primary' : 
                                     ($emp['employment_type'] == 'part-time' ? 'warning' : 'info'); 
                            ?>">
                                <?php echo ucfirst($emp['employment_type']); ?>
                            </span>
                        </td>
                        <td>Rs. <?php echo number_format($emp['salary'], 2); ?></td>
                        <td>Rs. <?php echo number_format($emp['allowance'], 2); ?></td>
                        <td><?php echo date('Y-m-d', strtotime($emp['join_date'])); ?></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary">View</button>
                            <button class="btn btn-sm btn-outline-warning">Edit</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>