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

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

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

// Handle interview status updates
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $interview_id = (int)$_POST['interview_id'];
    $action = $_POST['action'];
    
    // Verify the interview belongs to this company
    $stmt = $db->prepare("
        SELECT i.* FROM interviews i
        JOIN job_applications ja ON i.application_id = ja.id
        JOIN jobs j ON ja.job_id = j.id
        WHERE i.id = ? AND j.company_id = ?
    ");
    $stmt->execute([$interview_id, $company_id]);
    $interview = $stmt->fetch();
    
    if ($interview) {
        $new_status = '';
        $new_result = '';
        
        switch ($action) {
            case 'complete':
                $new_status = 'completed';
                $new_result = 'pending';
                break;
            case 'cancel':
                $new_status = 'cancelled';
                break;
            case 'reschedule':
                $new_status = 'rescheduled';
                break;
            case 'pass':
                $new_result = 'passed';
                break;
            case 'fail':
                $new_result = 'failed';
                break;
        }
        
        if ($new_status) {
            try {
                $stmt = $db->prepare("UPDATE interviews SET status = ? WHERE id = ?");
                $stmt->execute([$new_status, $interview_id]);
                $message = 'Interview status updated successfully!';
            } catch (PDOException $e) {
                $message = 'Error updating interview status.';
            }
        } elseif ($new_result) {
            try {
                $stmt = $db->prepare("UPDATE interviews SET result = ? WHERE id = ?");
                $stmt->execute([$new_result, $interview_id]);
                $message = 'Interview result updated successfully!';
            } catch (PDOException $e) {
                $message = 'Error updating interview result.';
            }
        }
    }
}

// Get filter parameters
$status_filter = isset($_GET['status']) ? $_GET['status'] : '';
$date_filter = isset($_GET['date']) ? $_GET['date'] : '';

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

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

if ($date_filter) {
    $where_conditions[] = "DATE(i.interview_date) = ?";
    $params[] = $date_filter;
}

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

// Get interviews
$stmt = $db->prepare("
    SELECT i.*, ja.status as application_status,
           j.title as job_title, j.location as job_location,
           c.first_name, c.last_name, c.email, c.phone, c.profile_picture
    FROM interviews i
    JOIN job_applications ja ON i.application_id = ja.id
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    $where_clause
    ORDER BY i.interview_date ASC
");
$stmt->execute($params);
$interviews = $stmt->fetchAll();

// Get statistics
$stats = [];
$stmt = $db->prepare("
    SELECT i.status, 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
    WHERE j.company_id = ?
    GROUP BY i.status
");
$stmt->execute([$company_id]);
$status_counts = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

$stats['total'] = array_sum($status_counts);
$stats['scheduled'] = $status_counts['scheduled'] ?? 0;
$stats['completed'] = $status_counts['completed'] ?? 0;
$stats['cancelled'] = $status_counts['cancelled'] ?? 0;

// Get upcoming interviews count
$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
    WHERE j.company_id = ? AND i.status = 'scheduled' AND i.interview_date > NOW()
");
$stmt->execute([$company_id]);
$stats['upcoming'] = $stmt->fetch()['count'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interviews - <?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" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" 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-calendar-alt me-2"></i>Interview Management
                        </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-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-calendar-alt fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['total']; ?></h3>
                                    <p class="text-muted mb-0">Total Interviews</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-clock fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['upcoming']; ?></h3>
                                    <p class="text-muted mb-0">Upcoming</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-check-circle fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['completed']; ?></h3>
                                    <p class="text-muted mb-0">Completed</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-danger mb-2">
                                        <i class="fas fa-times-circle fa-2x"></i>
                                    </div>
                                    <h3 class="fw-bold"><?php echo $stats['cancelled']; ?></h3>
                                    <p class="text-muted mb-0">Cancelled</p>
                                </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-4">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="">All Status</option>
                                        <option value="scheduled" <?php echo $status_filter === 'scheduled' ? 'selected' : ''; ?>>Scheduled</option>
                                        <option value="completed" <?php echo $status_filter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                        <option value="cancelled" <?php echo $status_filter === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                                        <option value="rescheduled" <?php echo $status_filter === 'rescheduled' ? 'selected' : ''; ?>>Rescheduled</option>
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="date" class="form-label">Date</label>
                                    <input type="date" class="form-control" id="date" name="date" 
                                           value="<?php echo htmlspecialchars($date_filter); ?>">
                                </div>
                                <div class="col-md-4 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="interviews.php" class="btn btn-outline-secondary">Clear</a>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Interviews List -->
                    <div class="card">
                        <div class="card-header">
                            <h5 class="card-title mb-0">Interviews (<?php echo count($interviews); ?>)</h5>
                        </div>
                        <div class="card-body p-0">
                            <?php if (empty($interviews)): ?>
                                <div class="text-center py-4">
                                    <i class="fas fa-calendar-alt fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No interviews scheduled.</p>
                                    <a href="applications.php" class="btn btn-primary">View Applications</a>
                                </div>
                            <?php else: ?>
                                <div class="table-responsive">
                                    <table class="table table-hover mb-0">
                                        <thead>
                                            <tr>
                                                <th>Candidate</th>
                                                <th>Position</th>
                                                <th>Date & Time</th>
                                                <th>Type</th>
                                                <th>Status</th>
                                                <th>Result</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php foreach ($interviews as $interview): ?>
                                                <?php
                                                $is_upcoming = strtotime($interview['interview_date']) > time();
                                                $is_today = date('Y-m-d', strtotime($interview['interview_date'])) === date('Y-m-d');
                                                ?>
                                                <tr class="<?php echo $is_today ? 'table-warning' : ''; ?>">
                                                    <td>
                                                        <div class="d-flex align-items-center">
                                                            <div class="me-3">
                                                                <?php if ($interview['profile_picture']): ?>
                                                                    <img src="<?php echo UPLOAD_URL . 'profiles/' . $interview['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($interview['first_name'] . ' ' . $interview['last_name']); ?></h6>
                                                                <small class="text-muted"><?php echo htmlspecialchars($interview['email']); ?></small>
                                                                <?php if ($interview['phone']): ?>
                                                                    <br><small class="text-muted"><?php echo htmlspecialchars($interview['phone']); ?></small>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <h6 class="mb-0"><?php echo htmlspecialchars($interview['job_title']); ?></h6>
                                                            <small class="text-muted"><?php echo htmlspecialchars($interview['job_location']); ?></small>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <div>
                                                            <strong><?php echo formatDateTime($interview['interview_date']); ?></strong>
                                                            <?php if ($is_today): ?>
                                                                <br><span class="badge bg-warning text-dark">Today</span>
                                                            <?php elseif ($is_upcoming): ?>
                                                                <br><span class="badge bg-info">Upcoming</span>
                                                            <?php endif; ?>
                                                        </div>
                                                    </td>
                                                    <td>
                                                        <span class="badge bg-secondary">
                                                            <?php echo ucfirst($interview['interview_type']); ?>
                                                        </span>
                                                        <?php if ($interview['location']): ?>
                                                            <br><small class="text-muted"><?php echo htmlspecialchars(substr($interview['location'], 0, 30)) . (strlen($interview['location']) > 30 ? '...' : ''); ?></small>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <span class="badge 
                                                            <?php 
                                                            switch($interview['status']) {
                                                                case 'scheduled': echo 'bg-info'; break;
                                                                case 'completed': echo 'bg-success'; break;
                                                                case 'cancelled': echo 'bg-danger'; break;
                                                                case 'rescheduled': echo 'bg-warning text-dark'; break;
                                                                default: echo 'bg-secondary';
                                                            }
                                                            ?>">
                                                            <?php echo ucfirst($interview['status']); ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($interview['result'] && $interview['result'] !== 'pending'): ?>
                                                            <span class="badge <?php echo $interview['result'] === 'passed' ? 'bg-success' : 'bg-danger'; ?>">
                                                                <?php echo ucfirst($interview['result']); ?>
                                                            </span>
                                                        <?php elseif ($interview['status'] === 'completed'): ?>
                                                            <span class="badge bg-warning text-dark">Pending</span>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <div class="btn-group btn-group-sm">
                                                            <button type="button" class="btn btn-outline-primary dropdown-toggle" 
                                                                    data-bs-toggle="dropdown">
                                                                Actions
                                                            </button>
                                                            
                                                            <ul class="dropdown-menu">
                                                                <li>
                                                                    <a href="view-application.php?id=<?php echo $interview['application_id']; ?>" class="dropdown-item">
                                                                        <i class="fas fa-eye me-2"></i>View Application
                                                                    </a>
                                                                </li>
                                                                
                                                                <?php if ($interview['status'] === 'scheduled'): ?>
                                                                    <li>
                                                                        <a href="schedule-interview.php?application_id=<?php echo $interview['application_id']; ?>" class="dropdown-item">
                                                                            <i class="fas fa-edit me-2"></i>Edit Interview
                                                                        </a>
                                                                    </li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="interview_id" value="<?php echo $interview['id']; ?>">
                                                                            <input type="hidden" name="action" value="complete">
                                                                            <button type="submit" class="dropdown-item">
                                                                                <i class="fas fa-check me-2"></i>Mark Completed
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                    <li><hr class="dropdown-divider"></li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to cancel this interview?')">
                                                                            <input type="hidden" name="interview_id" value="<?php echo $interview['id']; ?>">
                                                                            <input type="hidden" name="action" value="cancel">
                                                                            <button type="submit" class="dropdown-item text-danger">
                                                                                <i class="fas fa-times me-2"></i>Cancel Interview
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                                
                                                                <?php if ($interview['status'] === 'completed' && $interview['result'] === 'pending'): ?>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="interview_id" value="<?php echo $interview['id']; ?>">
                                                                            <input type="hidden" name="action" value="pass">
                                                                            <button type="submit" class="dropdown-item text-success">
                                                                                <i class="fas fa-check-circle me-2"></i>Mark as Passed
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                    <li>
                                                                        <form method="POST" class="d-inline">
                                                                            <input type="hidden" name="interview_id" value="<?php echo $interview['id']; ?>">
                                                                            <input type="hidden" name="action" value="fail">
                                                                            <button type="submit" class="dropdown-item text-danger">
                                                                                <i class="fas fa-times-circle me-2"></i>Mark as Failed
                                                                            </button>
                                                                        </form>
                                                                    </li>
                                                                <?php endif; ?>
                                                            </ul>
                                                        </div>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        </tbody>
                                    </table>
                                </div>
                            <?php endif; ?>
                        </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>