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

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

$company_id = $_SESSION['company_id'];
$message = '';

// Handle status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $application_id = (int)$_POST['application_id'];
    $action = $_POST['action'];
    
    // Verify the application belongs to this company and get deadline info
    $stmt = $db->prepare("
        SELECT ja.*, j.deadline FROM job_applications ja 
        JOIN jobs j ON ja.job_id = j.id 
        WHERE ja.id = ? AND j.company_id = ?
    ");
    $stmt->execute([$application_id, $company_id]);
    $application = $stmt->fetch();
    
    if ($application) {
        // Check if shortlisting is allowed (only after deadline)
        if ($action === 'shortlist') {
            $job_deadline = $application['deadline'];
            $current_date = date('Y-m-d');
            
            if ($job_deadline && $current_date <= $job_deadline) {
                $message = 'Shortlisting is only allowed after the application deadline (' . formatDate($job_deadline) . ').';
            } else {
                $new_status = 'shortlisted';
            }
        } else {
            // For other actions, proceed normally
            switch ($action) {
                case 'reject':
                    $new_status = 'rejected';
                    break;
                case 'interview':
                    $new_status = 'interviewed';
                    break;
                case 'hire':
                    $new_status = 'hired';
                    break;
            }
        }
        
        if (isset($new_status) && $new_status && !$message) {
            try {
                // Store old status for notification
                $old_status = $application['status'];
                
                $stmt = $db->prepare("UPDATE job_applications SET status = ? WHERE id = ?");
                $stmt->execute([$new_status, $application_id]);
                
                // Send notification to candidate
                require_once '../includes/notification_system.php';
                $notificationSystem = new NotificationSystem($db);
                $notificationSystem->notifyApplicationStatusChange($application_id, $old_status, $new_status);
                
                $message = 'Application status updated successfully! Candidate has been notified.';
            } catch (PDOException $e) {
                $message = 'Error updating application status.';
            }
        }
    }
}

// Get filter parameters
$job_filter = isset($_GET['job']) ? (int)$_GET['job'] : '';
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$search = isset($_GET['search']) ? sanitize($_GET['search']) : '';

// Build query conditions
$where_conditions = ["j.company_id = ?"];
$params = [$company_id];

if ($job_filter) {
    $where_conditions[] = "j.id = ?";
    $params[] = $job_filter;
}

if ($status_filter) {
    $where_conditions[] = "ja.status = ?";
    $params[] = $status_filter;
}

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

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

// Get applications
$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, j.location, j.deadline,
           c.first_name, c.last_name, c.email, c.phone, c.profile_picture,
           r.title as resume_title
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    LEFT JOIN resumes r ON ja.resume_id = r.id
    $where_clause
    ORDER BY ja.applied_at DESC
");
$stmt->execute($params);
$applications = $stmt->fetchAll();

// Get company's jobs for filter
$stmt = $db->prepare("SELECT id, title FROM jobs WHERE company_id = ? ORDER BY title");
$stmt->execute([$company_id]);
$company_jobs = $stmt->fetchAll();

// Get statistics
$stats = [];
$stmt = $db->prepare("
    SELECT ja.status, COUNT(*) as count 
    FROM job_applications ja 
    JOIN jobs j ON ja.job_id = j.id 
    WHERE j.company_id = ? 
    GROUP BY ja.status
");
$stmt->execute([$company_id]);
$status_counts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stats['total'] = array_sum($status_counts);
$stats['applied'] = $status_counts['applied'] ?? 0;
$stats['shortlisted'] = $status_counts['shortlisted'] ?? 0;
$stats['interviewed'] = $status_counts['interviewed'] ?? 0;
$stats['hired'] = $status_counts['hired'] ?? 0;
$stats['rejected'] = $status_counts['rejected'] ?? 0;
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Applications - <?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['company_name']); ?>
                </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" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </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="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-file-alt me-2"></i>Job Applications
                        </h1>
                    </div>

                    <?php if ($message): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <?php echo $message; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-primary mb-1">
                                        <i class="fas fa-file-alt fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['total']; ?></h4>
                                    <small class="text-muted">Total</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-info mb-1">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['applied']; ?></h4>
                                    <small class="text-muted">New</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-warning mb-1">
                                        <i class="fas fa-star fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['shortlisted']; ?></h4>
                                    <small class="text-muted">Shortlisted</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-purple mb-1">
                                        <i class="fas fa-calendar-alt fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['interviewed']; ?></h4>
                                    <small class="text-muted">Interviewed</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-success mb-1">
                                        <i class="fas fa-check-circle fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['hired']; ?></h4>
                                    <small class="text-muted">Hired</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-lg-2 col-md-4 col-sm-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-danger mb-1">
                                        <i class="fas fa-times-circle fa-2x"></i>
                                    </div>
                                    <h4 class="fw-bold"><?php echo $stats['rejected']; ?></h4>
                                    <small class="text-muted">Rejected</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Filters -->
                    <div class="card mb-4">
                        <div class="card-body">
                            <form method="GET" class="row g-3">
                                <div class="col-md-3">
                                    <label for="search" class="form-label">Search Candidates</label>
                                    <input type="text" class="form-control" id="search" name="search" 
                                           placeholder="Name or email..." value="<?php echo htmlspecialchars($search); ?>">
                                </div>
                                <div class="col-md-3">
                                    <label for="job" class="form-label">Job Position</label>
                                    <select class="form-select" id="job" name="job">
                                        <option value="">All Jobs</option>
                                        <?php foreach ($company_jobs as $job): ?>
                                            <option value="<?php echo $job['id']; ?>" <?php echo $job_filter == $job['id'] ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($job['title']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">All Status</option>
                                        <option value="applied" <?php echo $status_filter === 'applied' ? 'selected' : ''; ?>>Applied</option>
                                        <option value="shortlisted" <?php echo $status_filter === 'shortlisted' ? 'selected' : ''; ?>>Shortlisted</option>
                                        <option value="interviewed" <?php echo $status_filter === 'interviewed' ? 'selected' : ''; ?>>Interviewed</option>
                                        <option value="hired" <?php echo $status_filter === 'hired' ? 'selected' : ''; ?>>Hired</option>
                                        <option value="rejected" <?php echo $status_filter === 'rejected' ? 'selected' : ''; ?>>Rejected</option>
                                    </select>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button type="submit" class="btn btn-primary me-2">
                                        <i class="fas fa-search me-1"></i>Filter
                                    </button>
                                    <a href="applications.php" class="btn btn-outline-secondary me-2">Clear</a>
                                    <button type="button" class="btn btn-success" onclick="exportApplications()">
                                        <i class="fas fa-file-excel me-1"></i>Export Excel
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Applications List -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Applications (<?php echo count($applications); ?>)</h5>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($applications)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-file-alt fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No applications found.</p>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Candidate</th>
                                                <th>Job Position</th>
                                                <th>Applied Date</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($applications as $app): ?>
                                                <tr>
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="me-3">
                                                                <?php if ($app['profile_picture']): ?>
                                                                    <img src="<?php echo UPLOAD_URL . 'profiles/' . $app['profile_picture']; ?>" 
                                                                         alt="Profile" class="rounded-circle" style="width: 40px; height: 40px; object-fit: cover;">
                                                                <?php else: ?>
                                                                    <div class="rounded-circle bg-light d-flex align-items-center justify-content-center" 
                                                                         style="width: 40px; height: 40px;">
                                                                        <i class="fas fa-user text-muted"></i>
                                                                    </div>
                                                                <?php endif; ?>
                                                            </div>
                                                            <div>
                                                                <h6 class="mb-0"><?php echo htmlspecialchars($app['first_name'] . ' ' . $app['last_name']); ?></h6>
                                                                <small class="text-muted"><?php echo htmlspecialchars($app['email']); ?></small>
                                                                <?php if ($app['resume_title']): ?>
                                                                    <br><small class="text-info">
                                                                        <i class="fas fa-file-alt me-1"></i><?php echo htmlspecialchars($app['resume_title']); ?>
                                                                    </small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($app['job_title']); ?></h6>
                                                            <small class="text-muted"><?php echo htmlspecialchars($app['location']); ?></small>
                                                        </div>
                                                    </td>
                                                    <td><?php echo formatDate($app['applied_at']); ?></td>
                                                    <td>
                                                        <span class="badge status-<?php echo $app['status']; ?>">
                                                            <?php echo ucfirst($app['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <a href="view-application.php?id=<?php echo $app['id']; ?>" 
                                                               class="btn btn-outline-primary" title="View Details">
                                                                <i class="fas fa-eye"></i>
                                                            </a>
                                                            
                                                            <button type="button" class="btn btn-outline-secondary dropdown-toggle dropdown-toggle-split" 
                                                                    data-bs-toggle="dropdown">
                                                                <span class="visually-hidden">Toggle Dropdown</span>
                                                            </button>
                                                            
                                                            <ul class="dropdown-menu">
                                                                <?php if ($app['status'] === 'applied'): ?>
                                                                    <?php
                                                                    // Check if shortlisting is allowed for this application
                                                                    $shortlisting_allowed = true;
                                                                    if ($app['deadline']) {
                                                                        $current_date = date('Y-m-d');
                                                                        if ($current_date <= $app['deadline']) {
                                                                            $shortlisting_allowed = false;
                                                                        }
                                                                    }
                                                                    ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="shortlist">
                                                                            <button type="submit" class="dropdown-item text-warning<?php echo !$shortlisting_allowed ? ' disabled' : ''; ?>" 
                                                                                    <?php echo !$shortlisting_allowed ? 'disabled title="Available after deadline: ' . formatDate($app['deadline']) . '"' : ''; ?>>
                                                                                <i class="fas fa-star me-2"></i>Shortlist
                                                                                <?php if (!$shortlisting_allowed): ?>
                                                                                    <small class="text-muted">(after <?php echo formatDate($app['deadline']); ?>)</small>
                                                                                <?php endif; ?>
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (in_array($app['status'], ['applied', 'shortlisted'])): ?>
                                                                    <li>
                                                                        <a href="schedule-interview.php?application_id=<?php echo $app['id']; ?>" class="dropdown-item text-info">
                                                                            <i class="fas fa-calendar-plus me-2"></i>Schedule Interview
                                                                        </a>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($app['status'] === 'interviewed'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="hire">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-check me-2"></i>Hire
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if (!in_array($app['status'], ['hired', 'rejected'])): ?>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline" 
                                                                              onsubmit="return confirm('Are you sure you want to reject this application?')">
                                                                            <input type="hidden" name="application_id" value="<?php echo $app['id']; ?>">
                                                                            <input type="hidden" name="action" value="reject">
                                                                            <button type="submit" class="dropdown-item text-danger">
                                                                                <i class="fas fa-times me-2"></i>Reject
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- Hidden Export Form -->
    <form id="exportForm" method="POST" action="export_applications.php" style="display: none;">
        <input type="hidden" name="job_id" id="export_job_id">
        <input type="hidden" name="status" id="export_status">
        <input type="hidden" name="date_from" id="export_date_from">
        <input type="hidden" name="date_to" id="export_date_to">
    </form>

    <!-- Export Modal -->
    <div class="modal fade" id="exportModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-file-excel me-2 text-success"></i>
                        Export Applications to Excel
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="exportOptionsForm">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="export_job_filter" class="form-label">Filter by Job</label>
                                <select class="form-select" id="export_job_filter" name="job_id">
                                    <option value="">All Jobs</option>
                                    <?php foreach ($company_jobs as $job): ?>
                                        <option value="<?php echo $job['id']; ?>">
                                            <?php echo htmlspecialchars($job['title']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="export_status_filter" class="form-label">Filter by Status</label>
                                <select class="form-select" id="export_status_filter" name="status">
                                    <option value="">All Statuses</option>
                                    <option value="applied">Applied</option>
                                    <option value="shortlisted">Shortlisted</option>
                                    <option value="interviewed">Interviewed</option>
                                    <option value="hired">Hired</option>
                                    <option value="rejected">Rejected</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="export_date_from_filter" class="form-label">From Date</label>
                                <input type="date" class="form-control" id="export_date_from_filter" name="date_from">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="export_date_to_filter" class="form-label">To Date</label>
                                <input type="date" class="form-control" id="export_date_to_filter" name="date_to">
                            </div>
                        </div>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            <strong>Export will include:</strong> Candidate details, job information, application status, applied date, and cover letter preview.<br>
                            <small><strong>Note:</strong> The file will be generated in native Excel (.xlsx) format with professional formatting and styling.</small>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="confirmExport()">
                        <i class="fas fa-download me-1"></i>Download Excel
                    </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 exportApplications() {
            // Set current filter values in modal
            document.getElementById('export_job_filter').value = '<?php echo $job_filter; ?>';
            document.getElementById('export_status_filter').value = '<?php echo $status_filter; ?>';
            
            // Show export modal
            new bootstrap.Modal(document.getElementById('exportModal')).show();
        }
        
        function confirmExport() {
            // Get values from modal form
            const jobId = document.getElementById('export_job_filter').value;
            const status = document.getElementById('export_status_filter').value;
            const dateFrom = document.getElementById('export_date_from_filter').value;
            const dateTo = document.getElementById('export_date_to_filter').value;
            
            // Set values in hidden form
            document.getElementById('export_job_id').value = jobId;
            document.getElementById('export_status').value = status;
            document.getElementById('export_date_from').value = dateFrom;
            document.getElementById('export_date_to').value = dateTo;
            
            // Submit export form
            document.getElementById('exportForm').submit();
            
            // Hide modal
            bootstrap.Modal.getInstance(document.getElementById('exportModal')).hide();
            
            // Show success message
            setTimeout(function() {
                const alertDiv = document.createElement('div');
                alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
                alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; width: 350px;';
                alertDiv.innerHTML = `
                    <i class="fas fa-check-circle me-2"></i>
                    <strong>Excel Export Started!</strong> Your file will download shortly.
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                `;
                document.body.appendChild(alertDiv);
                
                // Auto-remove after 5 seconds
                setTimeout(function() {
                    alertDiv.remove();
                }, 5000);
            }, 500);
        }
        
        // Set current date as default max date
        document.getElementById('export_date_to_filter').value = new Date().toISOString().split('T')[0];
    </script>
</body>
</html>