<?php
require_once 'config/database.php';

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Form data
    $full_name = trim($_POST['full_name']);
    $nic_passport = trim($_POST['nic_passport']);
    $contact_number = trim($_POST['contact_number']);
    $email = trim($_POST['email']);
    $department = $_POST['department'];
    $username = strtolower(str_replace(' ', '.', $full_name));
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    
    try {
        $pdo->beginTransaction();
        
        // Check if username already exists
        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
        $stmt->execute([$username, $email]);
        if ($stmt->fetch()) {
            throw new Exception("Username or email already exists!");
        }
        
        // Check if NIC already registered
        $stmt = $pdo->prepare("SELECT id FROM employees WHERE nic_passport = ?");
        $stmt->execute([$nic_passport]);
        if ($stmt->fetch()) {
            throw new Exception("NIC/Passport already registered!");
        }
        
        // Create user (inactive by default)
        $stmt = $pdo->prepare("
            INSERT INTO users (username, password, email, role, is_active, created_at) 
            VALUES (?, ?, ?, 'employee', 0, NOW())
        ");
        $stmt->execute([$username, $password, $email]);
        $user_id = $pdo->lastInsertId();
        
        // Create employee record
        $stmt = $pdo->prepare("
            INSERT INTO employees 
            (user_id, full_name, nic_passport, contact_number, email, department, employment_type, join_date) 
            VALUES (?, ?, ?, ?, ?, ?, 'full-time', CURDATE())
        ");
        $stmt->execute([$user_id, $full_name, $nic_passport, $contact_number, $email, $department]);
        $employee_id = $pdo->lastInsertId();
        
        // Create leave balance - use the CORRECT employee_id from employees table
        $stmt = $pdo->prepare("
            INSERT INTO leave_balance (employee_id, casual_leaves, sick_leaves, annual_leaves) 
            VALUES (?, 7, 14, 14)
        ");
        $stmt->execute([$employee_id]);  // This should be employee_id, not user_id
        
        // Also, we should update the employee record with email if needed
        $stmt = $pdo->prepare("UPDATE employees SET email = ? WHERE id = ?");
        $stmt->execute([$email, $employee_id]);
        
        $pdo->commit();
        
        $success = "Registration successful! Your account is pending admin approval. You will receive an email when activated.";
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error = "Registration failed: " . $e->getMessage();
    }
}

// Get departments for dropdown
$stmt = $pdo->query("SELECT department_name FROM departments ORDER BY department_name");
$departments = $stmt->fetchAll();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Registration - HR System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            padding: 20px 0;
        }
        .registration-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            max-width: 800px;
            width: 100%;
            margin: 0 auto;
        }
        .registration-header {
            background: linear-gradient(90deg, #0d6efd, #0dcaf0);
            color: white;
            padding: 30px;
            border-radius: 15px 15px 0 0;
            text-align: center;
        }
        .form-section {
            padding: 30px;
        }
        .info-box {
            background: #f8f9fa;
            border-left: 4px solid #0d6efd;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 0 8px 8px 0;
        }
        .password-strength {
            height: 5px;
            margin-top: 5px;
            border-radius: 2px;
            transition: all 0.3s;
        }
    </style>
</head>
<body>
    <div class="registration-card">
        <div class="registration-header">
            <h2><i class="bi bi-person-plus"></i> Employee Registration</h2>
            <p class="mb-0">Join our HR System - Account requires admin approval</p>
        </div>
        
        <div class="form-section">
            <?php if($success): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="bi bi-check-circle"></i> <?php echo $success; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                <div class="mt-3">
                    <a href="login.php" class="btn btn-primary">Go to Login</a>
                    <a href="register.php" class="btn btn-outline-primary">Register Another</a>
                </div>
            </div>
            <?php endif; ?>
            
            <?php if($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle"></i> <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>
            
            <div class="info-box">
                <h5><i class="bi bi-info-circle"></i> Registration Process</h5>
                <ol class="mb-0">
                    <li>Fill in all required details accurately</li>
                    <li>Submit the registration form</li>
                    <li>Your account will be <strong>pending approval</strong></li>
                    <li>Admin will review and activate your account</li>
                    <li>You'll receive notification when activated</li>
                    <li>Use your username and password to login</li>
                </ol>
            </div>
            
            <form method="POST" id="registrationForm">
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Full Name *</label>
                        <input type="text" name="full_name" class="form-control" required 
                               placeholder="Enter your full name">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">NIC/Passport Number *</label>
                        <input type="text" name="nic_passport" class="form-control" required 
                               placeholder="Enter NIC or Passport number">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Contact Number *</label>
                        <input type="text" name="contact_number" class="form-control" required 
                               placeholder="Enter mobile number">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Email Address *</label>
                        <input type="email" name="email" class="form-control" required 
                               placeholder="Enter email address">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Department *</label>
                        <select name="department" class="form-control" required>
                            <option value="">Select Department</option>
                            <?php foreach($departments as $dept): ?>
                            <option value="<?php echo htmlspecialchars($dept['department_name']); ?>">
                                <?php echo htmlspecialchars($dept['department_name']); ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Username (Auto-generated)</label>
                        <input type="text" id="username_preview" class="form-control" readonly 
                               placeholder="Will be generated from your name">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Password *</label>
                        <input type="password" name="password" id="password" class="form-control" required 
                               placeholder="Create a password" onkeyup="checkPasswordStrength()">
                        <div class="password-strength" id="passwordStrength"></div>
                        <small class="form-text text-muted">Minimum 8 characters with letters and numbers</small>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Confirm Password *</label>
                        <input type="password" name="confirm_password" id="confirm_password" class="form-control" required 
                               placeholder="Confirm your password" onkeyup="checkPasswordMatch()">
                        <small class="form-text" id="passwordMatchText"></small>
                    </div>
                </div>
                
                <div class="mb-3 form-check">
                    <input type="checkbox" class="form-check-input" id="terms" required>
                    <label class="form-check-label" for="terms">
                        I agree to the <a href="#" data-bs-toggle="modal" data-bs-target="#termsModal">Terms and Conditions</a>
                    </label>
                </div>
                
                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                    <a href="login.php" class="btn btn-secondary">Back to Login</a>
                    <button type="submit" class="btn btn-primary" id="submitBtn">Register Now</button>
                </div>
            </form>
            
            <hr class="my-4">
            
            <div class="text-center">
                <p class="mb-0">Already have an account? <a href="login.php">Login here</a></p>
                <p class="text-muted small mt-2">Note: After registration, please wait for admin approval before logging in.</p>
            </div>
        </div>
    </div>
    
    <!-- Terms Modal -->
    <div class="modal fade" id="termsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Terms and Conditions</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <h6>HR System Registration Agreement</h6>
                    <p>By registering, you agree to:</p>
                    <ol>
                        <li>Provide accurate and truthful information</li>
                        <li>Keep your login credentials confidential</li>
                        <li>Use the system only for authorized purposes</li>
                        <li>Comply with company policies and procedures</li>
                        <li>Accept that your account requires admin approval</li>
                        <li>Understand that false information may lead to account termination</li>
                    </ol>
                    <p>Your account will be activated after verification by the HR department.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto-generate username from full name
        document.querySelector('input[name="full_name"]').addEventListener('input', function() {
            const fullName = this.value.trim().toLowerCase();
            if (fullName) {
                const username = fullName.replace(/\s+/g, '.');
                document.getElementById('username_preview').value = username;
            }
        });
        
        // Password strength checker
        function checkPasswordStrength() {
            const password = document.getElementById('password').value;
            const strengthBar = document.getElementById('passwordStrength');
            
            let strength = 0;
            if (password.length >= 8) strength++;
            if (password.match(/[a-z]/)) strength++;
            if (password.match(/[A-Z]/)) strength++;
            if (password.match(/[0-9]/)) strength++;
            if (password.match(/[^a-zA-Z0-9]/)) strength++;
            
            const colors = ['#dc3545', '#ffc107', '#ffc107', '#20c997', '#198754'];
            const texts = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong'];
            
            strengthBar.style.width = (strength * 20) + '%';
            strengthBar.style.backgroundColor = colors[strength - 1] || '#dc3545';
            strengthBar.textContent = texts[strength - 1] || '';
        }
        
        // Password match checker
        function checkPasswordMatch() {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            const matchText = document.getElementById('passwordMatchText');
            
            if (!confirmPassword) {
                matchText.textContent = '';
                matchText.className = 'form-text';
                return;
            }
            
            if (password === confirmPassword) {
                matchText.textContent = '✓ Passwords match';
                matchText.className = 'form-text text-success';
            } else {
                matchText.textContent = '✗ Passwords do not match';
                matchText.className = 'form-text text-danger';
            }
        }
        
        // Form validation
        document.getElementById('registrationForm').addEventListener('submit', function(e) {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;
            
            if (password !== confirmPassword) {
                e.preventDefault();
                alert('Passwords do not match!');
                return false;
            }
            
            if (password.length < 8) {
                e.preventDefault();
                alert('Password must be at least 8 characters long!');
                return false;
            }
            
            return true;
        });
    </script>
</body>
</html>