<?php
/**
 * Job Portal - Post Job Page
 * GHAMECC Choir Management Platform
 * 
 * This page allows members to post new job opportunities.
 */

// Include database connection and functions
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';

// Check if user is logged in
if (!isLoggedIn()) {
    $_SESSION['redirect_after_login'] = 'jobs/post-job.php';
    header('Location: ../login.php');
    exit;
}

// Get current user information from job portal users
$userId = $_SESSION['user_id'];
$userQuery = "SELECT jpu.*, m.* FROM job_portal_users jpu LEFT JOIN members m ON jpu.member_id = m.id WHERE jpu.id = ?";
$user = fetchRow($userQuery, [$userId]);

if (!$user || empty($user['member_id'])) {
    $error = "Your account is not linked to a member profile. Please contact the administrator.";
}

// Get user's society information
$userSociety = null;
if (!isset($error) && !empty($user['society_id'])) {
    $userSociety = fetchRow("SELECT s.*, c.name as circuit_name, d.name as diocese_name 
                            FROM societies s 
                            JOIN circuits c ON s.circuit_id = c.id 
                            JOIN dioceses d ON c.diocese_id = d.id 
                            WHERE s.id = ?", [$user['society_id']]);
}

// Initialize variables
$errors = [];
$success = false;
$formData = [
    'title' => '',
    'description' => '',
    'requirements' => '',
    'location' => '',
    'salary_range' => '',
    'company_name' => '',
    'contact_email' => $user['email'] ?? '',
    'contact_phone' => $user['contact_number'] ?? '',
    'deadline' => '',
    'category_id' => '',
    'society_id' => $user['society_id'] ?? ''
];

// Get job categories for dropdown
$categories = fetchRows("SELECT * FROM job_categories ORDER BY name ASC");

// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate form data
    $formData = [
        'title' => isset($_POST['title']) ? escapeString($_POST['title']) : '',
        'description' => isset($_POST['description']) ? trim($_POST['description']) : '',
        'requirements' => isset($_POST['requirements']) ? trim($_POST['requirements']) : '',
        'location' => isset($_POST['location']) ? escapeString($_POST['location']) : '',
        'salary_range' => isset($_POST['salary_range']) ? escapeString($_POST['salary_range']) : '',
        'company_name' => isset($_POST['company_name']) ? escapeString($_POST['company_name']) : '',
        'contact_email' => isset($_POST['contact_email']) ? escapeString($_POST['contact_email']) : '',
        'contact_phone' => isset($_POST['contact_phone']) ? escapeString($_POST['contact_phone']) : '',
        'deadline' => isset($_POST['deadline']) ? escapeString($_POST['deadline']) : '',
        'category_id' => isset($_POST['category_id']) ? (int)$_POST['category_id'] : 0,
        'society_id' => isset($_POST['society_id']) ? (int)$_POST['society_id'] : ''
    ];
    
    // Validate required fields
    if (empty($formData['title'])) {
        $errors[] = 'Job title is required';
    }
    
    if (empty($formData['description'])) {
        $errors[] = 'Job description is required';
    }
    
    if (empty($formData['location'])) {
        $errors[] = 'Job location is required';
    }
    
    if (empty($formData['company_name'])) {
        $errors[] = 'Company name is required';
    }
    
    if (empty($formData['contact_email'])) {
        $errors[] = 'Contact email is required';
    } elseif (!filter_var($formData['contact_email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Please enter a valid email address';
    }
    
    if (empty($formData['contact_phone'])) {
        $errors[] = 'Contact phone is required';
    }
    
    if (empty($formData['deadline'])) {
        $errors[] = 'Application deadline is required';
    } elseif (strtotime($formData['deadline']) < strtotime(date('Y-m-d'))) {
        $errors[] = 'Deadline cannot be in the past';
    }
    
    if ($formData['category_id'] <= 0) {
        $errors[] = 'Please select a job category';
    }
    
    // If no errors, insert job into database
    if (empty($errors)) {
        // Get member ID if logged in
        $memberId = null;
        if (isset($_SESSION['user_id'])) {
            // Check if user is linked to a member
            $memberQuery = "SELECT member_id FROM job_portal_users WHERE id = ?";
            $memberResult = fetchRow($memberQuery, [$_SESSION['user_id']]);
            if ($memberResult && !empty($memberResult['member_id'])) {
                $memberId = $memberResult['member_id'];
            }
        }
        
        // Validate society_id exists if provided
        $societyId = null;
        if (!empty($formData['society_id'])) {
            $societyCheck = fetchRow("SELECT id FROM societies WHERE id = ?", [$formData['society_id']]);
            if ($societyCheck) {
                $societyId = $formData['society_id'];
            }
        }
        
        // Insert job into database
        $insertQuery = "INSERT INTO jobs (
            title, description, requirements, location, salary_range, 
            company_name, contact_email, contact_phone, deadline, 
            member_id, posted_by_user_id, category_id, society_id, status
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')";
        
        $insertParams = [
            $formData['title'],
            $formData['description'],
            $formData['requirements'],
            $formData['location'],
            $formData['salary_range'],
            $formData['company_name'],
            $formData['contact_email'],
            $formData['contact_phone'],
            $formData['deadline'],
            $memberId,
            $_SESSION['user_id'], // Add the job portal user ID
            $formData['category_id'],
            $societyId
        ];
        
        $result = executeQuery($insertQuery, $insertParams);
        
        if ($result) {
            $jobId = getLastInsertId();
            
            // Handle file uploads if any
            if (!empty($_FILES['job_media']['name'][0])) {
                $uploadDir = '../uploads/jobs/' . $jobId . '/';
                
                // Create directory if it doesn't exist
                if (!file_exists($uploadDir)) {
                    mkdir($uploadDir, 0777, true);
                }
                
                // Process each uploaded file
                $fileCount = count($_FILES['job_media']['name']);
                
                for ($i = 0; $i < $fileCount; $i++) {
                    if ($_FILES['job_media']['error'][$i] === UPLOAD_ERR_OK) {
                        $tmpName = $_FILES['job_media']['tmp_name'][$i];
                        $fileName = basename($_FILES['job_media']['name'][$i]);
                        $fileSize = $_FILES['job_media']['size'][$i];
                        $fileType = $_FILES['job_media']['type'][$i];
                        
                        // Generate unique filename
                        $uniqueName = uniqid() . '_' . $fileName;
                        $filePath = $uploadDir . $uniqueName;
                        
                        // Move uploaded file
                        if (move_uploaded_file($tmpName, $filePath)) {
                            // Determine media type
                            $mediaType = 'document';
                            if (strpos($fileType, 'image/') === 0) {
                                $mediaType = 'image';
                            } elseif (strpos($fileType, 'video/') === 0) {
                                $mediaType = 'video';
                            }
                            
                            // Insert media record
                            $mediaQuery = "INSERT INTO job_media (
                                job_id, media_type, file_path, file_name, file_size
                            ) VALUES (?, ?, ?, ?, ?)";
                            
                            executeQuery($mediaQuery, [
                                $jobId,
                                $mediaType,
                                'uploads/jobs/' . $jobId . '/' . $uniqueName,
                                $fileName,
                                $fileSize
                            ]);
                        }
                    }
                }
            }
            
            $success = true;
            
            // Reset form data after successful submission
            $formData = [
                'title' => '',
                'description' => '',
                'requirements' => '',
                'location' => '',
                'salary_range' => '',
                'company_name' => '',
                'contact_email' => $user['email'] ?? '',
                'contact_phone' => $user['contact_number'] ?? '',
                'deadline' => '',
                'category_id' => '',
                'society_id' => $user['society_id'] ?? ''
            ];
        } else {
            $errors[] = 'Failed to post job. Please try again.';
        }
    }
}

// Page title
$pageTitle = "Post a Job - GHAMECC Job Portal";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Summernote WYSIWYG Editor -->
    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.css" rel="stylesheet">
    <style>
        .form-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 0 15px rgba(0,0,0,0.05);
        }
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/job-portal-navbar.php'; ?>

    <!-- Main Content -->
    <div class="container py-5">
        <div class="row">
            <div class="col-lg-8 mx-auto">
                <h1 class="mb-4">Post a Job</h1>
                
                <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i> Your job has been posted successfully!
                    <div class="mt-2">
                        <a href="index.php" class="btn btn-sm btn-primary">View All Jobs</a>
                        <a href="post-job.php" class="btn btn-sm btn-outline-primary">Post Another Job</a>
                    </div>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                        <li><?php echo $error; ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
                <?php endif; ?>
                
                <?php if (!$success): ?>
                <form action="post-job.php" method="POST" enctype="multipart/form-data">
                    <!-- Job Details Section -->
                    <div class="form-section">
                        <h3 class="mb-4">Job Details</h3>
                        
                        <div class="mb-3">
                            <label for="title" class="form-label required-field">Job Title</label>
                            <input type="text" class="form-control" id="title" name="title" value="<?php echo htmlspecialchars($formData['title']); ?>" required>
                            <div class="form-text">Enter a clear and concise title for the job.</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="category_id" class="form-label required-field">Job Category</label>
                            <select class="form-select" id="category_id" name="category_id" required>
                                <option value="">Select a category</option>
                                <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>" <?php echo ($formData['category_id'] == $category['id']) ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($category['name']); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label for="description" class="form-label required-field">Job Description</label>
                            <textarea class="form-control summernote" id="description" name="description" rows="6" required><?php echo htmlspecialchars($formData['description']); ?></textarea>
                            <div class="form-text">Provide a detailed description of the job responsibilities.</div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="requirements" class="form-label">Requirements</label>
                            <textarea class="form-control summernote" id="requirements" name="requirements" rows="4"><?php echo htmlspecialchars($formData['requirements']); ?></textarea>
                            <div class="form-text">List the skills, qualifications, and experience required for this job.</div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="location" class="form-label required-field">Location</label>
                                <input type="text" class="form-control" id="location" name="location" value="<?php echo htmlspecialchars($formData['location']); ?>" required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="salary_range" class="form-label">Salary Range</label>
                                <input type="text" class="form-control" id="salary_range" name="salary_range" value="<?php echo htmlspecialchars($formData['salary_range']); ?>" placeholder="e.g., GH₵1,000 - GH₵2,000">
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label for="deadline" class="form-label required-field">Application Deadline</label>
                            <input type="date" class="form-control" id="deadline" name="deadline" value="<?php echo htmlspecialchars($formData['deadline']); ?>" required>
                        </div>
                        
                        <?php if ($userSociety): ?>
                        <div class="mb-3">
                            <label class="form-label">Society</label>
                            <div class="form-control-plaintext bg-light p-3 rounded">
                                <i class="fas fa-church me-2"></i>
                                <strong><?php echo htmlspecialchars($userSociety['name']); ?></strong>
                                <br>
                                <small class="text-muted">
                                    <?php echo htmlspecialchars($userSociety['circuit_name'] . ', ' . $userSociety['diocese_name']); ?>
                                </small>
                            </div>
                            <div class="form-text">This job will be posted under your society.</div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <!-- Contact Information Section -->
                    <div class="form-section">
                        <h3 class="mb-4">Contact Information</h3>
                        
                        <div class="mb-3">
                            <label for="company_name" class="form-label required-field">Company/Organization Name</label>
                            <input type="text" class="form-control" id="company_name" name="company_name" value="<?php echo htmlspecialchars($formData['company_name']); ?>" required>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="contact_email" class="form-label required-field">Contact Email</label>
                                <input type="email" class="form-control" id="contact_email" name="contact_email" value="<?php echo htmlspecialchars($formData['contact_email']); ?>" required>
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label for="contact_phone" class="form-label required-field">Contact Phone</label>
                                <input type="tel" class="form-control" id="contact_phone" name="contact_phone" value="<?php echo htmlspecialchars($formData['contact_phone']); ?>" required>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Media Upload Section -->
                    <div class="form-section">
                        <h3 class="mb-4">Media Files</h3>
                        
                        <div class="mb-3">
                            <label for="job_media" class="form-label">Upload Images, Videos, or Documents</label>
                            <input type="file" class="form-control" id="job_media" name="job_media[]" multiple>
                            <div class="form-text">You can upload multiple files. Maximum size per file: 5MB.</div>
                        </div>
                    </div>
                    
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-primary btn-lg">Post Job</button>
                        <a href="index.php" class="btn btn-outline-secondary">Cancel</a>
                    </div>
                </form>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="bg-dark text-white py-4 mt-5">
        <div class="container">
            <div class="row">
                <div class="col-md-4 mb-3">
                    <h5>GHAMECC Job Portal</h5>
                    <p>A platform for Ghana Methodist Church Choir members to find and post job opportunities.</p>
                </div>
                <div class="col-md-4 mb-3">
                    <h5>Quick Links</h5>
                    <ul class="list-unstyled">
                        <li><a href="index.php" class="text-white">Home</a></li>
                        <li><a href="post-job.php" class="text-white">Post a Job</a></li>
                        <li><a href="talent-showcase.php" class="text-white">Talent Showcase</a></li>
                        <li><a href="about.php" class="text-white">About</a></li>
                    </ul>
                </div>
                <div class="col-md-4 mb-3">
                    <h5>Contact</h5>
                    <address>
                        <p><i class="fas fa-envelope me-2"></i> info@ghamecc.org</p>
                        <p><i class="fas fa-phone me-2"></i> +233 XX XXX XXXX</p>
                    </address>
                </div>
            </div>
            <hr>
            <div class="text-center">
                <p>&copy; <?php echo date('Y'); ?> GHAMECC Job Portal. All rights reserved.</p>
            </div>
        </div>
    </footer>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- Summernote JS -->
    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.18/dist/summernote-bs4.min.js"></script>
    <script>
        $(document).ready(function() {
            $('.summernote').summernote({
                placeholder: 'Start typing here...',
                height: 200,
                toolbar: [
                    ['style', ['bold', 'italic', 'underline', 'clear']],
                    ['font', ['strikethrough']],
                    ['para', ['ul', 'ol']],
                    ['insert', ['link']]
                ]
            });
        });
    </script>
</body>
</html>
