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

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

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

if (!$application_id) {
    redirect('applications.php');
}

// Get application details
$stmt = $db->prepare("
    SELECT ja.*, j.title as job_title, j.company_id,
           c.first_name, c.last_name, c.email, c.phone
    FROM job_applications ja
    JOIN jobs j ON ja.job_id = j.id
    JOIN candidates c ON ja.candidate_id = c.id
    WHERE ja.id = ? AND j.company_id = ?
");
$stmt->execute([$application_id, $company_id]);
$application = $stmt->fetch();

if (!$application) {
    redirect('applications.php');
}

// Check if interview already exists
$stmt = $db->prepare("SELECT * FROM interviews WHERE application_id = ?");
$stmt->execute([$application_id]);
$existing_interview = $stmt->fetch();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $interview_date = $_POST['interview_date'];
    $interview_time = $_POST['interview_time'];
    $interview_type = $_POST['interview_type'];
    $location = sanitize($_POST['location']);
    $interviewer_name = sanitize($_POST['interviewer_name']);
    $notes = sanitize($_POST['notes']);
    
    if (empty($interview_date) || empty($interview_time) || empty($interview_type)) {
        $error = 'Date, time, and interview type are required.';
    } elseif ($interview_type !== 'phone' && empty($location)) {
        $error = 'Location is required for video and in-person interviews.';
    } else {
        $interview_datetime = $interview_date . ' ' . $interview_time;
        
        // Validate date is in the future
        if (strtotime($interview_datetime) <= time()) {
            $error = 'Interview date and time must be in the future.';
        } else {
            try {
                if ($existing_interview) {
                    // Update existing interview
                    $stmt = $db->prepare("
                        UPDATE interviews 
                        SET interview_date = ?, interview_type = ?, location = ?, 
                            interviewer_name = ?, notes = ?, status = 'scheduled'
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $interview_datetime, $interview_type, $location, 
                        $interviewer_name, $notes, $existing_interview['id']
                    ]);
                } else {
                    // Create new interview
                    $stmt = $db->prepare("
                        INSERT INTO interviews (application_id, interview_date, interview_type, location, interviewer_name, notes) 
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $application_id, $interview_datetime, $interview_type, 
                        $location, $interviewer_name, $notes
                    ]);
                    
                    // Update application status to interviewed if not already
                    if ($application['status'] !== 'interviewed') {
                        $stmt = $db->prepare("UPDATE job_applications SET status = 'interviewed' WHERE id = ?");
                        $stmt->execute([$application_id]);
                    }
                }
                
                $success = 'Interview scheduled successfully!';
                
                // Refresh interview data
                $stmt = $db->prepare("SELECT * FROM interviews WHERE application_id = ?");
                $stmt->execute([$application_id]);
                $existing_interview = $stmt->fetch();
                
            } catch (PDOException $e) {
                $error = 'Error scheduling interview. Please try again.';
            }
        }
    }
}

// Pre-fill form data if editing
$form_data = [];
if ($existing_interview) {
    $interview_datetime = new DateTime($existing_interview['interview_date']);
    $form_data = [
        'interview_date' => $interview_datetime->format('Y-m-d'),
        'interview_time' => $interview_datetime->format('H:i'),
        'interview_type' => $existing_interview['interview_type'],
        'location' => $existing_interview['location'],
        'interviewer_name' => $existing_interview['interviewer_name'],
        'notes' => $existing_interview['notes']
    ];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Schedule Interview - <?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">
                    <!-- Breadcrumb -->
                    <nav aria-label="breadcrumb" class="mb-4">
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                            <li class="breadcrumb-item"><a href="applications.php">Applications</a></li>
                            <li class="breadcrumb-item active">Schedule Interview</li>
                        </ol>
                    </nav>

                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-calendar-plus me-2"></i>
                            <?php echo $existing_interview ? 'Update Interview' : 'Schedule Interview'; ?>
                        </h1>
                        <a href="applications.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Back to Applications
                        </a>
                    </div>

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

                    <?php if ($success): ?>
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            <div class="mt-2">
                                <a href="interviews.php" class="btn btn-success btn-sm me-2">View All Interviews</a>
                                <a href="applications.php" class="btn btn-outline-success btn-sm">Back to Applications</a>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Application Info -->
                        <div class="col-lg-4 mb-4">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="card-title mb-0">
                                        <i class="fas fa-info-circle me-2"></i>Application Details
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <strong>Candidate:</strong><br>
                                        <?php echo htmlspecialchars($application['first_name'] . ' ' . $application['last_name']); ?>
                                    </div>
                                    <div class="mb-3">
                                        <strong>Email:</strong><br>
                                        <a href="mailto:<?php echo htmlspecialchars($application['email']); ?>">
                                            <?php echo htmlspecialchars($application['email']); ?>
                                        </a>
                                    </div>
                                    <?php if ($application['phone']): ?>
                                        <div class="mb-3">
                                            <strong>Phone:</strong><br>
                                            <a href="tel:<?php echo htmlspecialchars($application['phone']); ?>">
                                                <?php echo htmlspecialchars($application['phone']); ?>
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                    <div class="mb-3">
                                        <strong>Position:</strong><br>
                                        <?php echo htmlspecialchars($application['job_title']); ?>
                                    </div>
                                    <div class="mb-0">
                                        <strong>Application Status:</strong><br>
                                        <span class="badge status-<?php echo $application['status']; ?>">
                                            <?php echo ucfirst($application['status']); ?>
                                        </span>
                                    </div>
                                </div>
                            </div>

                            <?php if ($existing_interview): ?>
                                <div class="card mt-4">
                                    <div class="card-header">
                                        <h6 class="card-title mb-0">
                                            <i class="fas fa-calendar me-2"></i>Current Interview
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-2">
                                            <strong>Date & Time:</strong><br>
                                            <?php echo formatDateTime($existing_interview['interview_date']); ?>
                                        </div>
                                        <div class="mb-2">
                                            <strong>Type:</strong><br>
                                            <?php echo ucfirst($existing_interview['interview_type']); ?>
                                        </div>
                                        <?php if ($existing_interview['location']): ?>
                                            <div class="mb-2">
                                                <strong>Location:</strong><br>
                                                <?php echo htmlspecialchars($existing_interview['location']); ?>
                                            </div>
                                        <?php endif; ?>
                                        <div class="mb-0">
                                            <strong>Status:</strong><br>
                                            <span class="badge bg-info"><?php echo ucfirst($existing_interview['status']); ?></span>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        </div>

                        <!-- Interview Form -->
                        <div class="col-lg-8">
                            <div class="card">
                                <div class="card-header">
                                    <h6 class="card-title mb-0">
                                        <i class="fas fa-calendar-plus me-2"></i>Interview Details
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <form method="POST">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="interview_date" class="form-label">Interview Date *</label>
                                                <input type="date" class="form-control" id="interview_date" name="interview_date" 
                                                       value="<?php echo $form_data['interview_date'] ?? ''; ?>" 
                                                       min="<?php echo date('Y-m-d'); ?>" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="interview_time" class="form-label">Interview Time *</label>
                                                <input type="time" class="form-control" id="interview_time" name="interview_time" 
                                                       value="<?php echo $form_data['interview_time'] ?? ''; ?>" required>
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="interview_type" class="form-label">Interview Type *</label>
                                            <select class="form-select" id="interview_type" name="interview_type" required onchange="toggleLocation()">
                                                <option value="">Select interview type</option>
                                                <option value="phone" <?php echo (isset($form_data['interview_type']) && $form_data['interview_type'] === 'phone') ? 'selected' : ''; ?>>Phone Interview</option>
                                                <option value="video" <?php echo (isset($form_data['interview_type']) && $form_data['interview_type'] === 'video') ? 'selected' : ''; ?>>Video Interview</option>
                                                <option value="in-person" <?php echo (isset($form_data['interview_type']) && $form_data['interview_type'] === 'in-person') ? 'selected' : ''; ?>>In-Person Interview</option>
                                            </select>
                                        </div>

                                        <div class="mb-3" id="location-field">
                                            <label for="location" class="form-label">Location/Meeting Details</label>
                                            <input type="text" class="form-control" id="location" name="location" 
                                                   value="<?php echo htmlspecialchars($form_data['location'] ?? ''); ?>" 
                                                   placeholder="Meeting room, Zoom link, or other details">
                                            <div class="form-text">
                                                For video interviews, include meeting link. For in-person, include address.
                                            </div>
                                        </div>

                                        <div class="mb-3">
                                            <label for="interviewer_name" class="form-label">Interviewer Name</label>
                                            <input type="text" class="form-control" id="interviewer_name" name="interviewer_name" 
                                                   value="<?php echo htmlspecialchars($form_data['interviewer_name'] ?? ''); ?>" 
                                                   placeholder="Name of the interviewer">
                                        </div>

                                        <div class="mb-4">
                                            <label for="notes" class="form-label">Additional Notes</label>
                                            <textarea class="form-control" id="notes" name="notes" rows="4" 
                                                      placeholder="Any additional information or instructions for the candidate..."><?php echo htmlspecialchars($form_data['notes'] ?? ''); ?></textarea>
                                        </div>

                                        <div class="d-flex gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="fas fa-calendar-check me-1"></i>
                                                <?php echo $existing_interview ? 'Update Interview' : 'Schedule Interview'; ?>
                                            </button>
                                            <a href="applications.php" class="btn btn-outline-secondary">Cancel</a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleLocation() {
            const interviewType = document.getElementById('interview_type').value;
            const locationField = document.getElementById('location-field');
            const locationInput = document.getElementById('location');
            
            if (interviewType === 'phone') {
                locationField.style.display = 'none';
                locationInput.removeAttribute('required');
            } else {
                locationField.style.display = 'block';
                if (interviewType !== '') {
                    locationInput.setAttribute('required', 'required');
                }
            }
        }
        
        // Initialize on page load
        document.addEventListener('DOMContentLoaded', function() {
            toggleLocation();
        });
    </script>
</body>
</html>