<?php
session_start();
require 'config.php'; // Use config.php for $pdo

$errors = [];
$formData = [
    'full_name' => '',
    'username' => '',
    'email' => '',
    'role' => ''
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Sanitize inputs
    $formData = [
        'full_name' => trim($_POST['full_name']),
        'username' => trim($_POST['username']),
        'email' => trim($_POST['email']),
        'password' => $_POST['password'],
        'confirm_password' => $_POST['confirm_password'],
        'role' => $_POST['role']
    ];

    // Validation
    if (empty($formData['full_name'])) $errors[] = 'Full name is required.';
    if (empty($formData['username'])) $errors[] = 'Username is required.';
    if (empty($formData['email'])) $errors[] = 'Email is required.';
    if (!filter_var($formData['email'], FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email format.';
    if (empty($formData['password'])) $errors[] = 'Password is required.';
    if (strlen($formData['password']) < 8) $errors[] = 'Password must be at least 8 characters.';
    if ($formData['password'] !== $formData['confirm_password']) $errors[] = 'Passwords do not match.';
    if (empty($formData['role'])) $errors[] = 'Role is required.';

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("SELECT user_id FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$formData['username'], $formData['email']]);

            if ($stmt->rowCount() > 0) {
                $errors[] = 'Username or email already exists.';
            } else {
                $hashedPassword = password_hash($formData['password'], PASSWORD_BCRYPT);
                $stmt = $pdo->prepare("INSERT INTO users (username, password, email, full_name, role) 
                                       VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([
                    $formData['username'],
                    $hashedPassword,
                    $formData['email'],
                    $formData['full_name'],
                    $formData['role']
                ]);

                $_SESSION['registration_success'] = true;
                header("Location: login.php");
                exit();
            }
        } catch (PDOException $e) {
            error_log("Registration error: " . $e->getMessage());
            $errors[] = 'Registration failed. Please try again.';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Register - Procurement Management System</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
        }

        .register-container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
            width: 400px;
        }

        h2 {
            text-align: center;
            color: #2e7d32;
            margin-bottom: 1rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }

        input, select {
            width: 100%;
            padding: 10px;
            border-radius: 6px;
            border: 1px solid #ccc;
        }

        .error {
            background-color: #ffe0e0;
            border: 1px solid #ff0000;
            color: #900;
            padding: 10px;
            margin-bottom: 1rem;
        }

        button {
            background-color: #2e7d32;
            color: white;
            border: none;
            width: 100%;
            padding: 10px;
            font-size: 16px;
            border-radius: 6px;
            cursor: pointer;
        }

        button:hover {
            background-color: #1b5e20;
        }

        .login-link {
            text-align: center;
            margin-top: 1rem;
        }

        .login-link a {
            color: #2e7d32;
            text-decoration: none;
        }
    </style>
</head>
<body>

<div class="register-container">
    <h2>Register</h2>

    <?php if (!empty($errors)): ?>
        <div class="error">
            <ul>
                <?php foreach ($errors as $err): ?>
                    <li><?= htmlspecialchars($err) ?></li>
                <?php endforeach; ?>
            </ul>
        </div>
    <?php endif; ?>

    <form method="post" action="register.php">
        <div class="form-group">
            <label>Full Name</label>
            <input type="text" name="full_name" value="<?= htmlspecialchars($formData['full_name']) ?>" required>
        </div>

        <div class="form-group">
            <label>Username</label>
            <input type="text" name="username" value="<?= htmlspecialchars($formData['username']) ?>" required>
        </div>

        <div class="form-group">
            <label>Email</label>
            <input type="email" name="email" value="<?= htmlspecialchars($formData['email']) ?>" required>
        </div>

        <div class="form-group">
            <label>Password (min. 8 characters)</label>
            <input type="password" name="password" required>
        </div>

        <div class="form-group">
            <label>Confirm Password</label>
            <input type="password" name="confirm_password" required>
        </div>

        <div class="form-group">
            <label>Role</label>
<select name="role" required>
    <option value="">-- Select Role --</option>
    <option value="admin" <?= $formData['role'] === 'admin' ? 'selected' : '' ?>>Admin / MD</option>
    <option value="accountant" <?= $formData['role'] === 'accountant' ? 'selected' : '' ?>>Accountant</option>
    <option value="procurement_officer" <?= $formData['role'] === 'procurement_officer' ? 'selected' : '' ?>>Procurement Officer</option>
</select>
            
        </div>

        <button type="submit">Register</button>
    </form>

    <div class="login-link">
        Already have an account? <a href="login.php">Login here</a>
    </div>
</div>

</body>
</html>
