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

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

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

// Handle approval/rejection actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $candidate_id = (int)$_POST['candidate_id'];
    $action = $_POST['action'];
    $notes = sanitize($_POST['notes'] ?? '');
    
    if ($action === 'approve' || $action === 'reject' || $action === 'convert_to_public') {
        try {
            // Verify the candidate belongs to this company
            $stmt = $db->prepare("
                SELECT id, first_name, last_name, email FROM candidates 
                WHERE id = ? AND candidate_type = 'internal' AND company_id = ?
            ");
            $stmt->execute([$candidate_id, $_SESSION['company_id']]);
            $candidate = $stmt->fetch();
            
            if (!$candidate) {
                $error = 'Candidate not found or does not belong to your company.';
            } else {
                if ($action === 'convert_to_public') {
                    // Convert internal candidate to public/external candidate
                    $stmt = $db->prepare("
                        UPDATE candidates 
                        SET candidate_type = 'external',
                            company_id = NULL,
                            employee_code = NULL,
                            hr_approval_status = NULL,
                            hr_approval_date = NULL,
                            hr_approval_notes = ?,
                            approved_by = ?
                        WHERE id = ? AND company_id = ?
                    ");
                    $convert_notes = $notes ?: 'Converted to public candidate - no longer employed by ' . $_SESSION['company_name'];
                    $stmt->execute([$convert_notes, $_SESSION['user_id'], $candidate_id, $_SESSION['company_id']]);
                    
                    if ($stmt->rowCount() > 0) {
                        $success = 'Employee successfully converted to public candidate. They can now apply for external jobs.';
                        
                        // Send notification to candidate
                        try {
                            $notification_stmt = $db->prepare("
                                INSERT INTO notifications (user_id, user_type, title, message, type) 
                                VALUES (?, 'candidate', ?, ?, ?)
                            ");
                            
                            $title = 'Account Status Changed';
                            $message = 'Your employment status with ' . $_SESSION['company_name'] . ' has been updated. You are now registered as a public candidate and can apply for external job opportunities. ' . ($notes ? 'Note: ' . $notes : '');
                            $type = 'info';
                            
                            $notification_stmt->execute([$candidate_id, $title, $message, $type]);
                        } catch (PDOException $e) {
                            error_log("Notification error for candidate conversion: " . $e->getMessage());
                        }
                    } else {
                        $error = 'Failed to convert candidate. Please try again.';
                    }
                } else {
                    // Handle approve/reject actions
                    $status = $action === 'approve' ? 'approved' : 'rejected';
                    
                    $stmt = $db->prepare("
                        UPDATE candidates 
                        SET hr_approval_status = ?, 
                            hr_approval_date = NOW(), 
                            hr_approval_notes = ?, 
                            approved_by = ? 
                        WHERE id = ? AND company_id = ?
                    ");
                    $stmt->execute([$status, $notes, $_SESSION['user_id'], $candidate_id, $_SESSION['company_id']]);
                    
                    if ($stmt->rowCount() > 0) {
                        $success = 'Employee ' . ($action === 'approve' ? 'approved' : 'rejected') . ' successfully.';
                        
                        // Send notification to candidate
                        try {
                            $notification_stmt = $db->prepare("
                                INSERT INTO notifications (user_id, user_type, title, message, type) 
                                VALUES (?, 'candidate', ?, ?, ?)
                            ");
                            
                            if ($action === 'approve') {
                                $title = 'Account Approved';
                                $message = 'Your internal employee account has been approved by ' . $_SESSION['company_name'] . '. You can now apply for jobs.';
                                $type = 'success';
                            } else {
                                $title = 'Account Rejected';
                                $message = 'Your internal employee account has been rejected by ' . $_SESSION['company_name'] . '. ' . ($notes ? 'Reason: ' . $notes : 'Please contact your HR department.');
                                $type = 'warning';
                            }
                            
                            $notification_stmt->execute([$candidate_id, $title, $message, $type]);
                            
                            // Send Gmail email notification (same as admin approval)
                            try {
                                require_once '../includes/gmail_email_service.php';
                                $gmailService = new GmailEmailService($db);
                                
                                // Prepare email content based on action
                                if ($action === 'approve') {
                                    $email_subject = '🎉 Internal Account Approved - Welcome to the Recruitment Portal!';
                                    $email_message = "Dear {$candidate['first_name']},\n\n";
                                    $email_message .= "Great news! Your internal employee account has been approved by {$_SESSION['company_name']}.\n\n";
                                    $email_message .= "You can now:\n";
                                    $email_message .= "• Log in to your account\n";
                                    $email_message .= "• Browse and apply for internal job postings\n";
                                    $email_message .= "• Update your profile and CV\n\n";
                                    $email_message .= "Welcome to our internal recruitment portal!\n\n";
                                    $email_message .= "Best regards,\n{$_SESSION['company_name']} HR Team";
                                } else {
                                    $email_subject = '⚠️ Internal Account Application - Update Required';
                                    $email_message = "Dear {$candidate['first_name']},\n\n";
                                    $email_message .= "We have reviewed your internal employee account application with {$_SESSION['company_name']}.\n\n";
                                    $email_message .= "Unfortunately, we need additional information or there are requirements that need to be addressed before approval.\n\n";
                                    if ($notes) {
                                        $email_message .= "Additional details: " . $notes . "\n\n";
                                    }
                                    $email_message .= "Please contact your HR department for more information on next steps.\n\n";
                                    $email_message .= "Best regards,\n{$_SESSION['company_name']} HR Team";
                                }
                                
                                $email_result = $gmailService->sendApprovalNotificationEmail($candidate, $email_message, $action);
                                
                                if ($email_result) {
                                    $success .= ' Email notification sent successfully!';
                                } else {
                                    error_log("Failed to send email notification for candidate ID: $candidate_id by company");
                                }
                            } catch (Exception $e) {
                                error_log("Email notification error for candidate ID $candidate_id by company: " . $e->getMessage());
                            }
                            
                        } catch (PDOException $e) {
                            error_log("Notification error for candidate approval: " . $e->getMessage());
                        }
                    } else {
                        $error = 'No candidate found or already processed.';
                    }
                }
            }
        } catch (PDOException $e) {
            error_log("Internal employee action error: " . $e->getMessage());
            $error = 'Error processing request. Please try again.';
        }
    }
}

// Get internal candidates for this company
$filter = $_GET['filter'] ?? 'pending';
$search = $_GET['search'] ?? '';

$where_conditions = ["c.candidate_type = 'internal'", "c.company_id = ?"];
$params = [$_SESSION['company_id']];

if ($filter === 'pending') {
    $where_conditions[] = "c.hr_approval_status = 'pending'";
} elseif ($filter === 'approved') {
    $where_conditions[] = "c.hr_approval_status = 'approved'";
} elseif ($filter === 'rejected') {
    $where_conditions[] = "c.hr_approval_status = 'rejected'";
}

if ($search) {
    $where_conditions[] = "(c.first_name LIKE ? OR c.last_name LIKE ? OR c.email LIKE ? OR c.employee_code LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param, $search_param]);
}

$where_clause = "WHERE " . implode(" AND ", $where_conditions);

$stmt = $db->prepare("
    SELECT 
        c.*,
        cu.name as approved_by_name,
        (SELECT COUNT(*) 
         FROM job_applications ja 
         JOIN jobs j ON ja.job_id = j.id 
         JOIN companies comp ON j.company_id = comp.id 
         WHERE ja.candidate_id = c.id AND j.status = 'active' AND comp.status = 'approved') as applications_count
    FROM candidates c 
    LEFT JOIN company_users cu ON c.approved_by = cu.id 
    $where_clause 
    ORDER BY c.created_at DESC
");
$stmt->execute($params);
$candidates = $stmt->fetchAll();

// Get statistics for this company
$stats_query = "
    SELECT 
        hr_approval_status,
        COUNT(*) as count 
    FROM candidates 
    WHERE candidate_type = 'internal' AND company_id = ?
    GROUP BY hr_approval_status
";
$stmt = $db->prepare($stats_query);
$stmt->execute([$_SESSION['company_id']]);
$stats_data = $stmt->fetchAll();

$stats = [
    'pending' => 0,
    'approved' => 0,
    'rejected' => 0
];

foreach ($stats_data as $stat) {
    $stats[$stat['hr_approval_status']] = $stat['count'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Internal Employees - <?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">
                    <i class="fas fa-building me-1"></i><?php echo $_SESSION['company_name']; ?>
                </span>
                <a class="nav-link" href="dashboard.php">Dashboard</a>
                <a class="nav-link" href="../auth/logout.php">Logout</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid py-4">
        <div class="row">
            <!-- Sidebar -->
            <div class="col-md-3 col-lg-2">
                <div class="list-group">
                    <a href="dashboard.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-chart-bar me-2"></i>Dashboard
                    </a>
                    <a href="jobs.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-briefcase me-2"></i>My Jobs
                    </a>
                    <a href="post-job.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-plus me-2"></i>Post Job
                    </a>
                    <a href="applications.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-file-alt me-2"></i>Applications
                    </a>
                    <a href="internal-employees.php" class="list-group-item list-group-item-action active">
                        <i class="fas fa-users me-2"></i>Internal Employees
                    </a>
                    <a href="interviews.php" class="list-group-item list-group-item-action">
                        <i class="fas fa-calendar-alt me-2"></i>Interviews
                    </a>
                </div>
            </div>

            <!-- Main Content -->
            <div class="col-md-9 col-lg-10">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h1 class="h3">Internal Employee Management</h1>
                </div>

                <!-- Statistics Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card text-white bg-warning">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['pending']; ?></h4>
                                        <p class="card-text">Pending Approval</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-success">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['approved']; ?></h4>
                                        <p class="card-text">Approved</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-check fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="card text-white bg-danger">
                            <div class="card-body">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <h4 class="card-title"><?php echo $stats['rejected']; ?></h4>
                                        <p class="card-text">Rejected</p>
                                    </div>
                                    <div class="align-self-center">
                                        <i class="fas fa-times fa-2x"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <?php if ($success): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <?php if ($error): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Info Card -->
                <div class="card mb-4 border-info">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="me-3">
                                <i class="fas fa-info-circle fa-2x text-info"></i>
                            </div>
                            <div>
                                <h6 class="card-title mb-1">Internal Employee Registration</h6>
                                <p class="card-text mb-0">
                                    Your employees can register as internal candidates by selecting your company during registration. 
                                    They will need approval from your company before they can apply for jobs.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filters and Search -->
                <div class="card mb-4">
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <select name="filter" class="form-select">
                                    <option value="pending" <?php echo $filter === 'pending' ? 'selected' : ''; ?>>Pending Approval</option>
                                    <option value="approved" <?php echo $filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                                    <option value="rejected" <?php echo $filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                    <option value="all" <?php echo $filter === 'all' ? 'selected' : ''; ?>>All Status</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <input type="text" name="search" class="form-control" placeholder="Search by name, email, or employee code" value="<?php echo htmlspecialchars($search); ?>">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="fas fa-search"></i> Filter
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Internal Employees List -->
                <div class="card">
                    <div class="card-body">
                        <?php if (empty($candidates)): ?>
                            <div class="text-center py-5">
                                <i class="fas fa-users fa-4x text-muted mb-3"></i>
                                <h5 class="text-muted">No internal employees found</h5>
                                <p class="text-muted">No employees match the current filter criteria.</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Employee</th>
                                            <th>Employee Code</th>
                                            <th>Status</th>
                                            <th>Registered</th>
                                            <th>Job Applications</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($candidates as $candidate): ?>
                                            <tr>
                                                <td>
                                                    <div class="d-flex align-items-center">
                                                        <?php if ($candidate['profile_picture']): ?>
                                                            <img src="<?php echo UPLOAD_URL . 'profiles/' . $candidate['profile_picture']; ?>" 
                                                                 alt="Profile" class="rounded-circle me-2" width="40" height="40">
                                                        <?php else: ?>
                                                            <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center me-2" 
                                                                 style="width: 40px; height: 40px;">
                                                                <i class="fas fa-user text-white"></i>
                                                            </div>
                                                        <?php endif; ?>
                                                        <div>
                                                            <div class="fw-bold"><?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?></div>
                                                            <small class="text-muted"><?php echo htmlspecialchars($candidate['email']); ?></small>
                                                        </div>
                                                    </div>
                                                </td>
                                                <td>
                                                    <span class="badge bg-secondary"><?php echo htmlspecialchars($candidate['employee_code']); ?></span>
                                                </td>
                                                <td>
                                                    <?php
                                                    $status = $candidate['hr_approval_status'];
                                                    $badge_class = [
                                                        'pending' => 'bg-warning',
                                                        'approved' => 'bg-success',
                                                        'rejected' => 'bg-danger'
                                                    ][$status] ?? 'bg-secondary';
                                                    ?>
                                                    <span class="badge <?php echo $badge_class; ?>">
                                                        <?php echo ucfirst($status); ?>
                                                    </span>
                                                    <?php if ($candidate['hr_approval_date']): ?>
                                                        <br><small class="text-muted"><?php echo formatDate($candidate['hr_approval_date']); ?></small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <small><?php echo formatDate($candidate['created_at']); ?></small>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info"><?php echo $candidate['applications_count']; ?></span>
                                                    <?php if ($candidate['applications_count'] > 0): ?>
                                                        <br><small class="text-muted">applications submitted</small>
                                                    <?php endif; ?>
                                                </td>
                                                <td>
                                                    <?php if ($candidate['hr_approval_status'] === 'pending'): ?>
                                                        <button type="button" class="btn btn-sm btn-success me-1" 
                                                                onclick="showApprovalModal(<?php echo $candidate['id']; ?>, 'approve', '<?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?>')">
                                                            <i class="fas fa-check"></i> Approve
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-danger" 
                                                                onclick="showApprovalModal(<?php echo $candidate['id']; ?>, 'reject', '<?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?>')">
                                                            <i class="fas fa-times"></i> Reject
                                                        </button>
                                                    <?php elseif ($candidate['hr_approval_status'] === 'approved'): ?>
                                                        <span class="text-muted">
                                                            <?php echo ucfirst($candidate['hr_approval_status']); ?>
                                                            <?php if ($candidate['approved_by_name']): ?>
                                                                <br><small>by <?php echo htmlspecialchars($candidate['approved_by_name']); ?></small>
                                                            <?php endif; ?>
                                                        </span>
                                                        <?php if ($candidate['hr_approval_notes']): ?>
                                                            <br><button type="button" class="btn btn-sm btn-outline-info me-1" 
                                                                    onclick="showNotesModal('<?php echo htmlspecialchars($candidate['hr_approval_notes']); ?>')">
                                                                <i class="fas fa-sticky-note"></i> Notes
                                                            </button>
                                                        <?php endif; ?>
                                                        <br><button type="button" class="btn btn-sm btn-warning mt-1" 
                                                                onclick="showApprovalModal(<?php echo $candidate['id']; ?>, 'convert_to_public', '<?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?>')">
                                                            <i class="fas fa-external-link-alt"></i> Convert to Public
                                                        </button>
                                                    <?php else: ?>
                                                        <span class="text-muted">
                                                            <?php echo ucfirst($candidate['hr_approval_status']); ?>
                                                            <?php if ($candidate['approved_by_name']): ?>
                                                                <br><small>by <?php echo htmlspecialchars($candidate['approved_by_name']); ?></small>
                                                            <?php endif; ?>
                                                        </span>
                                                        <?php if ($candidate['hr_approval_notes']): ?>
                                                            <br><button type="button" class="btn btn-sm btn-outline-info" 
                                                                    onclick="showNotesModal('<?php echo htmlspecialchars($candidate['hr_approval_notes']); ?>')">
                                                                <i class="fas fa-sticky-note"></i> Notes
                                                            </button>
                                                        <?php endif; ?>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Approval Modal -->
    <div class="modal fade" id="approvalModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <form method="POST" id="approvalForm">
                    <div class="modal-header">
                        <h5 class="modal-title" id="approvalModalTitle"></h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="candidate_id" id="candidate_id">
                        <input type="hidden" name="action" id="action">
                        
                        <p id="approvalModalText"></p>
                        
                        <div class="mb-3">
                            <label for="notes" class="form-label">Notes (optional)</label>
                            <textarea class="form-control" name="notes" id="notes" rows="3" 
                                      placeholder="Add any notes about this decision..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn" id="approvalSubmitBtn"></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Notes Modal -->
    <div class="modal fade" id="notesModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Approval Notes</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p id="notesContent"></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>
        function showApprovalModal(candidateId, action, candidateName) {
            document.getElementById('candidate_id').value = candidateId;
            document.getElementById('action').value = action;
            document.getElementById('notes').value = '';
            
            const modal = document.getElementById('approvalModal');
            const title = document.getElementById('approvalModalTitle');
            const text = document.getElementById('approvalModalText');
            const submitBtn = document.getElementById('approvalSubmitBtn');
            
            if (action === 'approve') {
                title.textContent = 'Approve Internal Employee';
                text.textContent = `Are you sure you want to approve ${candidateName} as an internal employee? They will be able to login and apply for your company's jobs.`;
                submitBtn.textContent = 'Approve';
                submitBtn.className = 'btn btn-success';
            } else if (action === 'reject') {
                title.textContent = 'Reject Internal Employee';
                text.textContent = `Are you sure you want to reject ${candidateName} as an internal employee? They will not be able to login.`;
                submitBtn.textContent = 'Reject';
                submitBtn.className = 'btn btn-danger';
            } else if (action === 'convert_to_public') {
                title.textContent = 'Convert to Public Candidate';
                text.textContent = `Are you sure you want to convert ${candidateName} to a public candidate? This will remove their internal employee status and allow them to apply for external job opportunities. This action cannot be undone.`;
                submitBtn.textContent = 'Convert to Public';
                submitBtn.className = 'btn btn-warning';
            }
            
            new bootstrap.Modal(modal).show();
        }
        
        function showNotesModal(notes) {
            document.getElementById('notesContent').textContent = notes;
            new bootstrap.Modal(document.getElementById('notesModal')).show();
        }
    </script>
</body>
</html>