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

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

$candidate_id = $_SESSION['user_id'];

// Get candidate statistics
$stats = [];

// Total applications - only count applications for active jobs from approved companies
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND j.status = 'active' AND c.status = 'approved'
");
$stmt->execute([$candidate_id]);
$stats['total_applications'] = $stmt->fetch()['count'];

// Pending applications
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND ja.status = 'applied' AND j.status = 'active' AND c.status = 'approved'
");
$stmt->execute([$candidate_id]);
$stats['pending_applications'] = $stmt->fetch()['count'];

// Shortlisted applications
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND ja.status = 'shortlisted' AND j.status = 'active' AND c.status = 'approved'
");
$stmt->execute([$candidate_id]);
$stats['shortlisted'] = $stmt->fetch()['count'];

// Interviews scheduled - only count for active jobs from approved companies
$stmt = $db->prepare("
    SELECT COUNT(*) as count 
    FROM interviews i
    JOIN job_applications ja ON i.application_id = ja.id
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND i.status = 'scheduled' AND j.status = 'active' AND c.status = 'approved'
");
$stmt->execute([$candidate_id]);
$stats['interviews'] = $stmt->fetch()['count'];

// Get candidate profile
$stmt = $db->prepare("SELECT * FROM candidates WHERE id = ?");
$stmt->execute([$candidate_id]);
$candidate = $stmt->fetch();

// Get recent applications - only from active jobs and approved companies
$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, j.location, j.employment_type,
           c.name as company_name
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND j.status = 'active' AND c.status = 'approved'
    ORDER BY ja.applied_at DESC
    LIMIT 5
");
$stmt->execute([$candidate_id]);
$recent_applications = $stmt->fetchAll();

// Get upcoming interviews - only for active jobs from approved companies
$stmt = $db->prepare("
    SELECT i.*, j.title as job_title, c.name as company_name
    FROM interviews i
    JOIN job_applications ja ON i.application_id = ja.id
    JOIN jobs j ON ja.job_id = j.id
    JOIN companies c ON j.company_id = c.id
    WHERE ja.candidate_id = ? AND i.status = 'scheduled' AND i.interview_date > NOW() 
          AND j.status = 'active' AND c.status = 'approved'
    ORDER BY i.interview_date ASC
    LIMIT 5
");
$stmt->execute([$candidate_id]);
$upcoming_interviews = $stmt->fetchAll();

// Check if profile is complete
$profile_completion = 0;
$total_fields = 8;
$completed_fields = 0;

if ($candidate['first_name']) $completed_fields++;
if ($candidate['last_name']) $completed_fields++;
if ($candidate['email']) $completed_fields++;
if ($candidate['phone']) $completed_fields++;
if ($candidate['address']) $completed_fields++;
if ($candidate['date_of_birth']) $completed_fields++;
if ($candidate['gender']) $completed_fields++;
if ($candidate['profile_picture']) $completed_fields++;

$profile_completion = round(($completed_fields / $total_fields) * 100);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Dashboard - <?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['first_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 active" 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-user me-2"></i>My Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="cv-builder.php">
                                <i class="fas fa-file-alt me-2"></i>CV Builder
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../jobs.php">
                                <i class="fas fa-search me-2"></i>Browse Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-briefcase me-2"></i>My Applications
                                <?php if ($stats['pending_applications'] > 0): ?>
                                    <span class="badge bg-warning ms-2"><?php echo $stats['pending_applications']; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                                <?php if ($stats['interviews'] > 0): ?>
                                    <span class="badge bg-info ms-2"><?php echo $stats['interviews']; ?></span>
                                <?php endif; ?>
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <h1 class="h2 mb-4">
                        <i class="fas fa-tachometer-alt me-2"></i>My Dashboard
                    </h1>

                    <!-- Profile Completion Alert -->
                    <?php if ($profile_completion < 80): ?>
                        <div class="alert alert-warning mb-4">
                            <div class="d-flex align-items-center">
                                <div class="me-3">
                                    <i class="fas fa-exclamation-triangle fa-2x"></i>
                                </div>
                                <div class="flex-grow-1">
                                    <h5 class="alert-heading mb-2">Complete Your Profile</h5>
                                    <p class="mb-2">Your profile is <?php echo $profile_completion; ?>% complete. A complete profile helps employers find you!</p>
                                    <div class="progress mb-2" style="height: 8px;">
                                        <div class="progress-bar" role="progressbar" style="width: <?php echo $profile_completion; ?>%"></div>
                                    </div>
                                    <a href="profile.php" class="btn btn-warning btn-sm">Complete Profile</a>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-primary mb-2">
                                        <i class="fas fa-briefcase fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['total_applications']; ?></h3>
                                    <p class="text-muted mb-0">Total Applications</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-warning mb-2">
                                        <i class="fas fa-clock fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['pending_applications']; ?></h3>
                                    <p class="text-muted mb-0">Pending</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-success mb-2">
                                        <i class="fas fa-star fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['shortlisted']; ?></h3>
                                    <p class="text-muted mb-0">Shortlisted</p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-3">
                            <div class="card dashboard-card text-center">
                                <div class="card-body">
                                    <div class="text-info mb-2">
                                        <i class="fas fa-calendar-alt fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['interviews']; ?></h3>
                                    <p class="text-muted mb-0">Interviews</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Quick Actions -->
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-bolt me-2"></i>Quick Actions
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3 mb-2">
                                    <a href="../jobs.php" class="btn btn-primary w-100">
                                        <i class="fas fa-search me-2"></i>Browse Jobs
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="cv-builder.php" class="btn btn-outline-success w-100">
                                        <i class="fas fa-file-alt me-2"></i>Build CV
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="applications.php" class="btn btn-outline-info w-100">
                                        <i class="fas fa-briefcase me-2"></i>My Applications
                                    </a>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <a href="profile.php" class="btn btn-outline-secondary w-100">
                                        <i class="fas fa-user me-2"></i>Edit Profile
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Recent Applications -->
                        <div class="col-lg-6 mb-4">
                            <div class="card h-100">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-briefcase me-2"></i>Recent Applications
                                    </h5>
                                    <a href="applications.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($recent_applications)): ?>
                                        <div class="text-center py-3">
                                            <i class="fas fa-briefcase fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No applications yet.</p>
                                            <a href="../jobs.php" class="btn btn-primary">Browse Jobs</a>
                                        </div>
                                    <?php else: ?>
                                        <div class="list-group list-group-flush">
                                            <?php foreach ($recent_applications as $application): ?>
                                                <div class="list-group-item d-flex justify-content-between align-items-center px-0">
                                                    <div>
                                                        <h6 class="mb-1"><?php echo htmlspecialchars($application['job_title']); ?></h6>
                                                        <small class="text-muted">
                                                            <?php echo htmlspecialchars($application['company_name']); ?> • 
                                                            <?php echo htmlspecialchars($application['location']); ?>
                                                        </small>
                                                    </div>
                                                    <div class="text-end">
                                                        <span class="badge status-<?php echo $application['status']; ?> d-block mb-1">
                                                            <?php echo ucfirst($application['status']); ?>
                                                        </span>
                                                        <small class="text-muted"><?php echo formatDate($application['applied_at']); ?></small>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <!-- Upcoming Interviews -->
                        <div class="col-lg-6 mb-4">
                            <div class="card h-100">
                                <div class="card-header d-flex justify-content-between align-items-center">
                                    <h5 class="card-title mb-0">
                                        <i class="fas fa-calendar-alt me-2"></i>Upcoming Interviews
                                    </h5>
                                    <a href="interviews.php" class="btn btn-sm btn-outline-primary">View All</a>
                                </div>
                                <div class="card-body">
                                    <?php if (empty($upcoming_interviews)): ?>
                                        <div class="text-center py-3">
                                            <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
                                            <p class="text-muted">No upcoming interviews.</p>
                                        </div>
                                    <?php else: ?>
                                        <div class="list-group list-group-flush">
                                            <?php foreach ($upcoming_interviews as $interview): ?>
                                                <div class="list-group-item px-0">
                                                    <div class="d-flex justify-content-between align-items-start">
                                                        <div>
                                                            <h6 class="mb-1"><?php echo htmlspecialchars($interview['job_title']); ?></h6>
                                                            <p class="mb-1 text-muted"><?php echo htmlspecialchars($interview['company_name']); ?></p>
                                                            <small class="text-muted">
                                                                <i class="fas fa-calendar me-1"></i><?php echo formatDateTime($interview['interview_date']); ?>
                                                            </small>
                                                        </div>
                                                        <span class="badge bg-info"><?php echo ucfirst($interview['interview_type']); ?></span>
                                                    </div>
                                                </div>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Profile Summary -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">
                                <i class="fas fa-user me-2"></i>Profile Summary
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row align-items-center">
                                <div class="col-md-2 text-center">
                                    <?php if ($candidate['profile_picture']): ?>
                                        <img src="<?php echo UPLOAD_URL . 'profiles/' . $candidate['profile_picture']; ?>" 
                                             alt="Profile Picture" class="profile-picture">
                                    <?php else: ?>
                                        <div class="profile-picture bg-light d-flex align-items-center justify-content-center">
                                            <i class="fas fa-user fa-3x text-muted"></i>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="col-md-8">
                                    <h4><?php echo htmlspecialchars($candidate['first_name'] . ' ' . $candidate['last_name']); ?></h4>
                                    <p class="text-muted mb-2">
                                        <i class="fas fa-envelope me-2"></i><?php echo htmlspecialchars($candidate['email']); ?>
                                    </p>
                                    <?php if ($candidate['phone']): ?>
                                        <p class="text-muted mb-2">
                                            <i class="fas fa-phone me-2"></i><?php echo htmlspecialchars($candidate['phone']); ?>
                                        </p>
                                    <?php endif; ?>
                                    <?php if ($candidate['address']): ?>
                                        <p class="text-muted mb-2">
                                            <i class="fas fa-map-marker-alt me-2"></i><?php echo htmlspecialchars($candidate['address']); ?>
                                        </p>
                                    <?php endif; ?>
                                    
                                    <!-- Nationality Status -->
                                    <div class="mb-2">
                                        <?php if (isset($candidate['is_foreign_national']) && $candidate['is_foreign_national'] === 'yes'): ?>
                                            <span class="badge bg-info">
                                                <i class="fas fa-globe me-1"></i>Foreign National
                                                <?php if (isset($candidate['country']) && $candidate['country']): ?>
                                                    - <?php echo htmlspecialchars($candidate['country']); ?>
                                                <?php endif; ?>
                                            </span>
                                            <?php if (isset($candidate['passport_number']) && $candidate['passport_number']): ?>
                                                <small class="text-muted d-block mt-1">
                                                    <i class="fas fa-passport me-1"></i>Passport: <?php echo htmlspecialchars($candidate['passport_number']); ?>
                                                </small>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <span class="badge bg-success">
                                                <i class="fas fa-flag me-1"></i>SA Citizen/PR
                                            </span>
                                            <?php if (isset($candidate['sa_id_number']) && $candidate['sa_id_number']): ?>
                                                <small class="text-muted d-block mt-1">
                                                    <i class="fas fa-id-card me-1"></i>ID Number: <?php echo htmlspecialchars($candidate['sa_id_number']); ?>
                                                </small>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="col-md-2 text-end">
                                    <div class="mb-2">
                                        <small class="text-muted">Profile Completion</small>
                                        <div class="progress" style="height: 8px;">
                                            <div class="progress-bar bg-success" role="progressbar" style="width: <?php echo $profile_completion; ?>%"></div>
                                        </div>
                                        <small class="text-muted"><?php echo $profile_completion; ?>%</small>
                                    </div>
                                    <a href="profile.php" class="btn btn-outline-primary btn-sm">Edit Profile</a>
                                </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>