<?php
// This script is intended to be included within admin_dashboard.php,
// ensuring $conn (database connection) and $_SESSION variables are available.

// Check if $conn exists (safety check, typically handled by dashboard)
if (!isset($conn)) {
    if (file_exists('config/db_connection.php')) {
        require_once 'config/db_connection.php';
    } else {
        echo "<div class='message error'>FATAL ERROR: Database connection configuration file not found.</div>";
        exit();
    }
}

$message = '';
$message_class = '';
$MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB limit for PDF files
$search_query = $_GET['search_query'] ?? ''; // Initialize search query from GET
$search_results = []; // Array to hold search results
$all_applications = []; // Array to hold all applications
$message_fetch = ''; // Initialize error message

// Helper function to handle file upload and validation
function handle_pdf_upload($file_key, $upload_dir) {
    global $message, $message_class, $MAX_FILE_SIZE;

    if (!isset($_FILES[$file_key]) || $_FILES[$file_key]['error'] == UPLOAD_ERR_NO_FILE) {
        return ['success' => false, 'path' => null, 'error' => "Missing file for '{$file_key}'. It is a required field."];
    }
    
    $file = $_FILES[$file_key];

    // 1. Check for upload errors
    if ($file['error'] !== UPLOAD_ERR_OK) {
        return ['success' => false, 'path' => null, 'error' => "Upload error for '{$file_key}': " . $file['error']];
    }

    // 2. Check file size (5MB limit)
    if ($file['size'] > $MAX_FILE_SIZE) {
        return ['success' => false, 'path' => null, 'error' => "File size exceeds the 5MB limit for '{$file_key}'."];
    }

    // 3. Check file extension and MIME type (PDF only)
    $file_info = pathinfo($file['name']);
    $file_ext = strtolower($file_info['extension'] ?? '');
    $mime_type = $file['type'] ?? '';

    $allowed_mime = 'application/pdf';

    if ($file_ext !== 'pdf' || $mime_type !== $allowed_mime) {
        return ['success' => false, 'path' => null, 'error' => "Invalid file type for '{$file_key}'. Only PDF files are allowed."];
    }
    
    // 4. Sanitize file name and create unique path
    $safe_file_name = preg_replace("/[^a-zA-Z0-9_\.]/", "_", basename($file['name']));
    $final_file_name = time() . "_" . uniqid() . "_" . $safe_file_name;
    $target_file = $upload_dir . $final_file_name;

    // 5. Move uploaded file
    // NOTE: In a real system, ensure the 'uploads/cv_bank/' directory exists and is writable.
    if (move_uploaded_file($file['tmp_name'], $target_file)) {
        return ['success' => true, 'path' => $target_file, 'error' => null];
    } else {
        return ['success' => false, 'path' => null, 'error' => "Error moving the uploaded file for '{$file_key}'. Check server permissions."];
    }
}


// --- 1. HANDLE CV BANK APPLICATION SUBMISSION ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit_application'])) {
    
    // Define the upload directory (relative to where the dashboard script is run)
    $upload_dir = 'uploads/cv_bank/';
    if (!is_dir($upload_dir)) {
        // Attempt to create the directory if it doesn't exist
        mkdir($upload_dir, 0777, true);
    }
    
    // --- Step 1: Handle File Uploads (CV and Cover Letter) ---
    $cv_upload_result = handle_pdf_upload('full_cv_file', $upload_dir);
    
    // Cover Letter is optional in this logic, but if provided, must be a PDF
    $cover_letter_upload_result = ['success' => true, 'path' => null, 'error' => null]; // Default to success/null path
    if (isset($_FILES['cover_letter_file']) && $_FILES['cover_letter_file']['error'] !== UPLOAD_ERR_NO_FILE) {
        $cover_letter_upload_result = handle_pdf_upload('cover_letter_file', $upload_dir);
    }

    // Check for upload errors
    if (!$cv_upload_result['success']) {
        $message = "CV Upload Error: " . $cv_upload_result['error'];
        $message_class = 'error';
    } elseif (!$cover_letter_upload_result['success']) {
        $message = "Cover Letter Upload Error: " . $cover_letter_upload_result['error'];
        $message_class = 'error';
    } else {
        
        // --- Step 2: Prepare Application Data for Database ---
        $applicant_name = trim($_POST['applicant_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone_number = trim($_POST['phone_number'] ?? '');
        $desired_job_role = trim($_POST['desired_job_role'] ?? '');
        $area_of_specialty = trim($_POST['area_of_specialty'] ?? '');
        $highest_degree_education = trim($_POST['highest_degree_education'] ?? '');
        $certification = trim($_POST['certification'] ?? '');
        
        // Mandatory fields check
        if (empty($applicant_name) || empty($email) || empty($desired_job_role)) {
            $message = "Error: Applicant Name, Email, and Desired Job Role are required fields.";
            $message_class = 'error';
            // Cleanup uploaded files if the rest of the form data is missing
            if ($cv_upload_result['path'] && file_exists($cv_upload_result['path'])) unlink($cv_upload_result['path']);
            if ($cover_letter_upload_result['path'] && file_exists($cover_letter_upload_result['path'])) unlink($cover_letter_upload_result['path']);
        } else {
            
            // Get the user ID of the admin performing the upload
            $uploaded_by_id = $_SESSION['user_id'] ?? 1; // Default to user_id 1 if not set

            // --- Step 3: Insert into Database (applicants_cv_bank) ---
            $sql_insert = "INSERT INTO applicants_cv_bank
                            (applicant_name, email, phone_number, desired_job_role, area_of_specialty,
                             highest_degree_education, certification, cv_file_path, cover_letter_file_path, uploaded_by)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                            
            if ($stmt = $conn->prepare($sql_insert)) {
                // 'sssssssssi' -> 9 strings and 1 integer
                $stmt->bind_param("sssssssssi",
                    $applicant_name, $email, $phone_number, $desired_job_role, $area_of_specialty,
                    $highest_degree_education, $certification, $cv_upload_result['path'], $cover_letter_upload_result['path'],
                    $uploaded_by_id
                );
                
                if ($stmt->execute()) {
                    $message = "Success: Application for '{$applicant_name}' submitted successfully.";
                    $message_class = 'success';
                } else {
                    $message = "Error submitting application: " . $stmt->error;
                    $message_class = 'error';
                    // Cleanup uploaded files on DB failure
                    if ($cv_upload_result['path'] && file_exists($cv_upload_result['path'])) unlink($cv_upload_result['path']);
                    if ($cover_letter_upload_result['path'] && file_exists($cover_letter_upload_result['path'])) unlink($cover_letter_upload_result['path']);
                }
                $stmt->close();
            } else {
                $message = "Error: Database preparation failed for application submission.";
                $message_class = 'error';
            }
        }
    }
}

// ----------------------------------------------------------------------
// 2. HANDLE SEARCH & FETCH APPLICATIONS FOR DISPLAY
// ----------------------------------------------------------------------

if (isset($conn)) {
    // --- A. Handle Search (Populate $search_results if query is active) ---
    if (!empty($search_query)) {
        $search_term = "%" . trim($search_query) . "%";
        
        $sql_search = "SELECT applicant_id, applicant_name, desired_job_role, application_date, area_of_specialty, cv_file_path, cover_letter_file_path 
                       FROM applicants_cv_bank 
                       WHERE applicant_name LIKE ? OR desired_job_role LIKE ? 
                       ORDER BY application_date DESC";
        
        if ($stmt_search = $conn->prepare($sql_search)) {
            $stmt_search->bind_param("ss", $search_term, $search_term);
            $stmt_search->execute();
            $result_search = $stmt_search->get_result();
            while ($row = $result_search->fetch_assoc()) {
                $search_results[] = $row;
            }
            $stmt_search->close();
        }
    }
    
    // --- B. Fetch All Applications (The original logic, always runs) ---
    $sql_fetch = "SELECT applicant_id, applicant_name, desired_job_role, application_date, area_of_specialty, cv_file_path, cover_letter_file_path 
                  FROM applicants_cv_bank 
                  ORDER BY application_date DESC";
    $result = $conn->query($sql_fetch);

    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $all_applications[] = $row;
        }
    } else {
        $message_fetch = "Error: Could not retrieve applications. Please run the SQL query to create the 'applicants_cv_bank' table.";
    }
}
?>

<!-- ==================================================================== -->
<!-- CV BANK MANAGEMENT HTML SECTION -->
<!-- ==================================================================== -->

<style>
    /* Styling specific to this section, reusing form-card from dashboard */
    .section-header {
        margin-bottom: 25px;
        color: #2c3e50;
    }
    .data-container {
        margin-top: 30px;
    }
    .message {
        padding: 10px;
        margin-bottom: 20px;
        border-radius: 4px;
        font-weight: bold;
    }
    .message.success {
        background-color: #d4edda;
        color: #155724;
        border: 1px solid #c3e6cb;
    }
    .message.error {
        background-color: #f8d7da;
        color: #721c24;
        border: 1px solid #f5c6cb;
    }
    .grid-form {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
    }
    .grid-form .full-width {
        grid-column: 1 / -1;
    }
    .grid-form label {
        margin-bottom: 0;
    }
    .grid-form input, .grid-form select {
        width: 100%;
        box-sizing: border-box;
    }
    /* New Search Bar Styling */
    .search-bar {
        margin-bottom: 20px;
        padding: 15px;
        border: 1px solid #ccc;
        border-radius: 8px;
        background: #f9f9f9;
        display: flex;
        gap: 10px;
        align-items: center;
    }
    .search-bar input[type="text"] {
        flex-grow: 1;
        padding: 8px;
        border-radius: 4px;
        border: 1px solid #bdc3c7;
    }
    .search-bar button {
        padding: 8px 15px;
        background-color: #3498db;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
    }
    .search-bar button:hover {
        background-color: #2980b9;
    }
    .btn-delete { 
        background-color: #e74c3c; 
        color: white; 
        border: none; 
        border-radius: 4px; 
        cursor: pointer;
    }
    /* Separate list styling */
    .search-results-container {
        border: 2px solid #3498db;
        padding: 15px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
</style>

<div class="form-card">
    <h2 class="section-header">Submit New CV Application</h2>
    
    <?php if ($message): ?>
        <div class="message <?php echo $message_class; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <form method="POST" action="admin_dashboard.php?page=manage_cv_bank" enctype="multipart/form-data">
        <input type="hidden" name="submit_application" value="1">
        
        <div class="grid-form">
            <!-- Basic Details -->
            <div>
                <label for="applicant_name">Applicant's Name <span style="color:red;">*</span></label>
                <input type="text" id="applicant_name" name="applicant_name" required>
            </div>
            <div>
                <label for="desired_job_role">Desired Job Role <span style="color:red;">*</span></label>
                <input type="text" id="desired_job_role" name="desired_job_role" required>
            </div>

            <!-- Contact Information -->
            <div>
                <label for="email">Email <span style="color:red;">*</span></label>
                <input type="email" id="email" name="email" required>
            </div>
            <div>
                <label for="phone_number">Phone Number</label>
                <input type="text" id="phone_number" name="phone_number">
            </div>

            <!-- Education & Specialty -->
            <div>
                <label for="area_of_specialty">Area of Specialty</label>
                <input type="text" id="area_of_specialty" name="area_of_specialty">
            </div>
            <div>
                <label for="highest_degree_education">Highest Degree of Education</label>
                <select id="highest_degree_education" name="highest_degree_education">
                    <option value="">-- Select Degree --</option>
                    <option value="High School">High School</option>
                    <option value="Associate">Associate's Degree</option>
                    <option value="Bachelor">Bachelor's Degree</option>
                    <option value="Master">Master's Degree</option>
                    <option value="Doctorate">Doctorate/PhD</option>
                </select>
            </div>

            <div class="full-width">
                <label for="certification">Certifications (e.g., CISSP, PMP)</label>
                <input type="text" id="certification" name="certification">
            </div>

            <!-- File Uploads (PDF Only) -->
            <div>
                <label for="full_cv_file">Full CV (PDF Only, Max 5MB) <span style="color:red;">*</span></label>
                <input type="file" id="full_cv_file" name="full_cv_file" accept=".pdf" required>
            </div>
            <div>
                <label for="cover_letter_file">Cover Letter (PDF Only, Optional, Max 5MB)</label>
                <input type="file" id="cover_letter_file" name="cover_letter_file" accept=".pdf">
            </div>

            <div class="full-width" style="text-align: center; margin-top: 10px;">
                <button type="submit" class="btn-primary" style="padding: 10px 30px;">Submit Application</button>
            </div>
        </div>
    </form>
</div>

<!-- ==================================================================== -->
<!-- APPLICATION LIST DISPLAY SECTION -->
<!-- ==================================================================== -->

<div class="form-card data-container">
    <h2 class="section-header">CV Bank Applications</h2>
    
    <!-- NEW: Search Bar -->
    <form method="GET" action="admin_dashboard.php" class="search-bar">
        <input type="hidden" name="page" value="manage_cv_bank">
        <input type="text" name="search_query" placeholder="Search by Applicant Name or Job Role..." value="<?php echo htmlspecialchars($search_query); ?>">
        <button type="submit">Search</button>
        <?php if (!empty($search_query)): ?>
            <a href="admin_dashboard.php?page=manage_cv_bank" style="padding: 8px 15px; background-color: #e74c3c; color: white; border-radius: 4px; text-decoration: none;">Clear Search</a>
        <?php endif; ?>
    </form>

    <?php if (isset($message_fetch)): ?>
        <div class="message error"><?php echo htmlspecialchars($message_fetch); ?></div>
    <?php endif; ?>

    <!-- Conditional Display: Show Search Results FIRST -->
    <?php if (!empty($search_query) && !empty($search_results)): ?>
        <div class="search-results-container">
            <h3 style="margin-top: 0; color: #3498db;">Search Results (<?php echo count($search_results); ?> Found)</h3>
            <?php display_application_table($search_results); ?>
        </div>
        <h3 style="margin-top: 30px; border-bottom: 1px solid #eee; padding-bottom: 5px;">Full CV Bank List</h3>
    <?php elseif (!empty($search_query) && empty($search_results)): ?>
        <p class="message error">No results found for "<?php echo htmlspecialchars($search_query); ?>". Displaying full list below.</p>
        <h3 style="margin-top: 30px; border-bottom: 1px solid #eee; padding-bottom: 5px;">Full CV Bank List</h3>
    <?php endif; ?>

    <!-- Default Display: Full List -->
    <?php if (empty($search_query) || !empty($search_results) || (!empty($search_query) && empty($search_results))): ?>
        <?php if (!empty($all_applications)): ?>
            <?php display_application_table($all_applications); ?>
        <?php else: ?>
            <p>No applications found in the CV bank.</p>
        <?php endif; ?>
    <?php endif; ?>

</div>

<?php 
// Helper function to render the table (to avoid code duplication)
function display_application_table($applications) {
?>
    <table class="data-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Job Role</th>
                <th>Specialty</th>
                <th>Application Date</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($applications as $app): ?>
                <tr>
                    <td><?php echo htmlspecialchars($app['applicant_id']); ?></td>
                    <td><?php echo htmlspecialchars($app['applicant_name']); ?></td>
                    <td><?php echo htmlspecialchars($app['desired_job_role']); ?></td>
                    <td><?php echo htmlspecialchars($app['area_of_specialty'] ?? 'N/A'); ?></td>
                    <td><?php echo htmlspecialchars(substr($app['application_date'], 0, 10)); ?></td>
                    <td>
                        <!-- View CV Link -->
                        <a href="<?php echo htmlspecialchars($app['cv_file_path']); ?>" target="_blank" class="btn-primary" style="padding: 5px 10px; font-size: 12px; background-color: #2ecc71;">View CV</a>
                        
                        <!-- View Cover Letter Link (Only if path exists) -->
                        <?php if (!empty($app['cover_letter_file_path'])): ?>
                            <a href="<?php echo htmlspecialchars($app['cover_letter_file_path']); ?>" target="_blank" class="btn-primary" style="padding: 5px 10px; font-size: 12px; background-color: #3498db;">View CL</a>
                        <?php endif; ?>

                        <!-- Placeholder Delete Button -->
                        <button class="btn-delete" style="padding: 5px 10px; font-size: 12px;">Delete</button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php
}
?>
