<?php
require_once '../config/config.php';
requireLogin('admin');

$database = new Database();
$db = $database->getConnection();

$company_id = isset($_GET['company_id']) ? (int)$_GET['company_id'] : 0;
$error = '';
$success = '';

if (!$company_id) {
    header('Location: companies.php');
    exit();
}

// Get company details
$stmt = $db->prepare("SELECT * FROM companies WHERE id = ?");
$stmt->execute([$company_id]);
$company = $stmt->fetch();

if (!$company) {
    header('Location: companies.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name']);
    $email = sanitize($_POST['email']);
    $password = $_POST['password'];
    $phone = sanitize($_POST['phone']);
    $position = sanitize($_POST['position']);
    $is_primary = isset($_POST['is_primary']) ? 1 : 0;
    
    if (empty($name) || empty($email) || empty($password)) {
        $error = 'Name, email, and password are required.';
    } elseif (strlen($password) < 6) {
        $error = 'Password must be at least 6 characters long.';
    } else {
        // Check if email already exists
        $check_tables = [
            ['table' => 'company_users', 'email_field' => 'email'],
            ['table' => 'candidates', 'email_field' => 'email'],
            ['table' => 'admins', 'email_field' => 'email']
        ];
        
        $email_exists = false;
        foreach ($check_tables as $check) {
            $stmt = $db->prepare("SELECT id FROM {$check['table']} WHERE {$check['email_field']} = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $email_exists = true;
                break;
            }
        }
        
        if ($email_exists) {
            $error = 'Email address is already registered.';
        } else {
            try {
                $db->beginTransaction();
                
                // If this is being set as primary, remove primary status from other users
                if ($is_primary) {
                    $stmt = $db->prepare("UPDATE company_users SET is_primary = 0 WHERE company_id = ?");
                    $stmt->execute([$company_id]);
                }
                
                // Insert new user
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $stmt = $db->prepare("
                    INSERT INTO company_users (company_id, name, email, password, phone, position, is_primary) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([$company_id, $name, $email, $hashed_password, $phone, $position, $is_primary]);
                
                $db->commit();
                $success = 'User added successfully!';
                
                // Clear form data on success
                $_POST = [];
                
            } catch (PDOException $e) {
                $db->rollBack();
                $error = 'Error adding user. Please try again.';
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add User - <?php echo htmlspecialchars($company['name']); ?> - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['username']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="companies.php">
                                <i class="fas fa-building me-2"></i>Manage Companies
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="candidates.php">
                                <i class="fas fa-users me-2"></i>Manage Candidates
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="categories.php">
                                <i class="fas fa-tags me-2"></i>Job Categories
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="admin-users.php">
                                <i class="fas fa-user-shield me-2"></i>Admin Users
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <!-- Breadcrumb -->
                    <nav aria-label="breadcrumb" class="mb-4">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="companies.php">Companies</a></li>
                            <li class="breadcrumb-item"><a href="view-company.php?id=<?php echo $company['id']; ?>"><?php echo htmlspecialchars($company['name']); ?></a></li>
                            <li class="breadcrumb-item active">Add User</li>
                        </ol>
                    </nav>

                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-user-plus me-2"></i>Add User to <?php echo htmlspecialchars($company['name']); ?>
                        </h1>
                        <a href="view-company.php?id=<?php echo $company['id']; ?>" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Back to Company
                        </a>
                    </div>

                    <?php if ($error): ?>
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            <div class="mt-2">
                                <a href="view-company.php?id=<?php echo $company['id']; ?>" class="btn btn-success btn-sm me-2">Back to Company</a>
                                <a href="add-company-user.php?company_id=<?php echo $company['id']; ?>" class="btn btn-outline-success btn-sm">Add Another User</a>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-user me-2"></i>User Information
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label for="name" class="form-label">Full Name *</label>
                                            <input type="text" class="form-control" id="name" name="name" 
                                                   value="<?php echo isset($_POST['name']) ? htmlspecialchars($_POST['name']) : ''; ?>" 
                                                   required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="email" class="form-label">Email Address *</label>
                                            <input type="email" class="form-control" id="email" name="email" 
                                                   value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" 
                                                   required>
                                            <div class="form-text">This will be used to login to the system</div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="password" class="form-label">Password *</label>
                                            <input type="password" class="form-control" id="password" name="password" 
                                                   placeholder="Minimum 6 characters" required>
                                        </div>

                                        <div class="mb-3">
                                            <label for="phone" class="form-label">Phone Number</label>
                                            <input type="tel" class="form-control" id="phone" name="phone" 
                                                   value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                                        </div>

                                        <div class="mb-3">
                                            <label for="position" class="form-label">Position/Title</label>
                                            <input type="text" class="form-control" id="position" name="position" 
                                                   value="<?php echo isset($_POST['position']) ? htmlspecialchars($_POST['position']) : ''; ?>" 
                                                   placeholder="e.g., HR Manager, Recruiter">
                                        </div>

                                        <div class="mb-4">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" id="is_primary" name="is_primary" 
                                                       <?php echo (isset($_POST['is_primary']) && $_POST['is_primary']) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="is_primary">
                                                    Set as Primary User
                                                </label>
                                                <div class="form-text">Primary users have full access to company features</div>
                                            </div>
                                        </div>

                                        <div class="d-flex gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-user-plus me-1"></i>Add User
                                            </button>
                                            <a href="view-company.php?id=<?php echo $company['id']; ?>" class="btn btn-outline-secondary">Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>