<?php
/**
 * Job Portal - Create/Edit Profile Page
 * GHAMECC Choir Management Platform
 * 
 * This page allows members to create or edit their talent showcase profiles.
 */

// 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()) {
    // Store the intended destination for after login
    $_SESSION['redirect_after_login'] = 'jobs/create-profile.php';
    header('Location: ../login.php');
    exit;
}

// Get current user information
$userId = $_SESSION['user_id'];
$userQuery = "SELECT * FROM users WHERE id = ?";
$user = fetchRow($userQuery, [$userId]);

// Check if user is linked to a member
$member = null;
if (!empty($user['member_id'])) {
    $memberQuery = "SELECT * FROM members WHERE id = ?";
    $member = fetchRow($memberQuery, [$user['member_id']]);
}

if (!$member) {
    // User is not linked to a member, show error
    $error = "Your account is not linked to a member profile. Please contact the administrator.";
} else {
    // Check if member already has a profile
    $profileQuery = "SELECT * FROM member_profiles WHERE member_id = ?";
    $profile = fetchRow($profileQuery, [$member['id']]);
    
    $isEdit = !empty($profile);
    
    // Handle form submission
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Validate and sanitize inputs
        $skills = isset($_POST['skills']) ? escapeString($_POST['skills']) : '';
        $experience = isset($_POST['experience']) ? escapeString($_POST['experience']) : '';
        $education = isset($_POST['education']) ? escapeString($_POST['education']) : '';
        $portfolioUrl = isset($_POST['portfolio_url']) ? escapeString($_POST['portfolio_url']) : '';
        $availability = isset($_POST['availability']) ? escapeString($_POST['availability']) : 'full_time';
        $phoneNumber = isset($_POST['phone_number']) ? escapeString($_POST['phone_number']) : '';
        
        // Validate availability
        $validAvailability = ['full_time', 'part_time', 'contract', 'freelance'];
        if (!in_array($availability, $validAvailability)) {
            $availability = 'full_time';
        }
        
        // Handle file upload for profile picture
        $resumePath = '';
        $uploadError = '';
        
        if (!empty($_FILES['profile_picture']['name'])) {
            $targetDir = "../includes/uploads/profiles/";
            
            // Create directory if it doesn't exist
            if (!file_exists($targetDir)) {
                mkdir($targetDir, 0777, true);
            }
            
            $fileName = basename($_FILES["profile_picture"]["name"]);
            $targetFilePath = $targetDir . $member['id'] . '_' . time() . '_' . $fileName;
            $fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
            
            // Allow certain file formats
            $allowTypes = array('jpg', 'png', 'jpeg', 'gif');
            if (in_array(strtolower($fileType), $allowTypes)) {
                // Upload file to server
                if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $targetFilePath)) {
                    $resumePath = str_replace('../', '', $targetFilePath);
                } else {
                    $uploadError = "Sorry, there was an error uploading your file.";
                }
            } else {
                $uploadError = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
            }
        }
        
        // Prepare data for database
        $data = [
            'member_id' => $member['id'],
            'skills' => $skills,
            'experience' => $experience,
            'education' => $education,
            'portfolio_url' => $portfolioUrl,
            'availability' => $availability,
            'phone_number' => $phoneNumber
        ];
        
        if (!empty($resumePath)) {
            $data['resume_path'] = $resumePath;
        }
        
        // Insert or update profile
        if ($isEdit) {
            // Update existing profile
            $updateFields = [];
            $updateParams = [];
            
            foreach ($data as $key => $value) {
                if ($key !== 'member_id') {
                    $updateFields[] = "$key = ?";
                    $updateParams[] = $value;
                }
            }
            
            $updateParams[] = $member['id'];
            
            $updateQuery = "UPDATE member_profiles SET " . implode(', ', $updateFields) . ", updated_at = NOW() WHERE member_id = ?";
            $success = executeQuery($updateQuery, $updateParams);
            
            if ($success) {
                $successMessage = "Your profile has been updated successfully!";
            } else {
                $error = "Failed to update your profile. Please try again.";
            }
        } else {
            // Insert new profile
            $insertFields = array_keys($data);
            $placeholders = array_fill(0, count($insertFields), '?');
            $insertParams = array_values($data);
            
            $insertQuery = "INSERT INTO member_profiles (" . implode(', ', $insertFields) . ", created_at, updated_at) 
                           VALUES (" . implode(', ', $placeholders) . ", NOW(), NOW())";
            
            $success = executeQuery($insertQuery, $insertParams);
            
            if ($success) {
                $successMessage = "Your profile has been created successfully!";
                
                // Get the newly created profile
                $profile = fetchRow($profileQuery, [$member['id']]);
                $isEdit = true;
            } else {
                $error = "Failed to create your profile. Please try again.";
            }
        }
    }
}

// Page title
$pageTitle = ($isEdit ?? false) ? "Edit Your Profile - GHAMECC Job Portal" : "Create Your Profile - 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">
    <!-- Tagify for skills input -->
    <link href="https://cdn.jsdelivr.net/npm/@yaireo/tagify/dist/tagify.css" rel="stylesheet">
    <style>
        .form-section {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 30px;
            margin-bottom: 30px;
        }
        .section-title {
            border-bottom: 2px solid #0d6efd;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }
        .profile-preview {
            width: 150px;
            height: 150px;
            object-fit: cover;
            border-radius: 50%;
            border: 5px solid #fff;
            box-shadow: 0 0 15px rgba(0,0,0,0.1);
            margin: 0 auto 20px;
            display: block;
        }
        .profile-upload-btn {
            position: relative;
            overflow: hidden;
            display: inline-block;
        }
        .profile-upload-btn input[type=file] {
            position: absolute;
            top: 0;
            right: 0;
            min-width: 100%;
            min-height: 100%;
            font-size: 100px;
            text-align: right;
            filter: alpha(opacity=0);
            opacity: 0;
            outline: none;
            cursor: pointer;
            display: block;
        }
        .tagify {
            width: 100%;
            max-width: 100%;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <?php include 'includes/job-portal-navbar.php'; ?>

    <!-- Main Content -->
    <div class="container py-5">
        <div class="row mb-4">
            <div class="col-md-8">
                <h1 class="mb-3"><?php echo ($isEdit ?? false) ? "Edit Your Profile" : "Create Your Profile"; ?></h1>
                <p class="lead">Showcase your skills and experience to potential employers.</p>
            </div>
            <div class="col-md-4 text-md-end">
                <a href="talent-showcase.php" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left me-2"></i> Back to Talent Showcase
                </a>
            </div>
        </div>

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

        <?php if (isset($successMessage)): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i> <?php echo $successMessage; ?>
            </div>
        <?php endif; ?>

        <?php if (!isset($error) || (isset($error) && isset($member))): ?>
            <form action="create-profile.php" method="POST" enctype="multipart/form-data">
                <!-- Profile Picture Section -->
                <div class="form-section">
                    <h3 class="section-title">Profile Picture</h3>
                    <div class="row">
                        <div class="col-md-4 text-center">
                            <?php if (!empty($profile['resume_path'])): ?>
                                <img src="../<?php echo $profile['resume_path']; ?>" alt="Profile Picture" class="profile-preview" id="profilePreview">
                            <?php else: ?>
                                <div class="profile-preview d-flex align-items-center justify-content-center bg-light" id="profilePreview">
                                    <i class="fas fa-user fa-4x text-secondary"></i>
                                </div>
                            <?php endif; ?>
                            
                            <div class="profile-upload-btn">
                                <button type="button" class="btn btn-outline-primary">
                                    <i class="fas fa-camera me-2"></i> Choose Photo
                                </button>
                                <input type="file" name="profile_picture" id="profilePicture" accept="image/*">
                            </div>
                            
                            <?php if (isset($uploadError) && !empty($uploadError)): ?>
                                <div class="text-danger mt-2 small"><?php echo $uploadError; ?></div>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-8">
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle me-2"></i> Upload a professional photo to make your profile stand out.
                                <ul class="mb-0 mt-2">
                                    <li>Use a clear, professional headshot</li>
                                    <li>Ensure good lighting and a neutral background</li>
                                    <li>Accepted formats: JPG, PNG, GIF</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Skills Section -->
                <div class="form-section">
                    <h3 class="section-title">Skills & Expertise</h3>
                    <div class="mb-3">
                        <label for="skills" class="form-label">Your Skills</label>
                        <input type="text" class="form-control" id="skills" name="skills" 
                               value="<?php echo isset($profile['skills']) ? htmlspecialchars($profile['skills']) : ''; ?>"
                               placeholder="Add your skills (e.g., Web Design, Graphic Design, Music Production)">
                        <div class="form-text">Enter your skills separated by commas.</div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="availability" class="form-label">Availability</label>
                        <select class="form-select" id="availability" name="availability">
                            <option value="full_time" <?php echo (isset($profile['availability']) && $profile['availability'] === 'full_time') ? 'selected' : ''; ?>>Full Time</option>
                            <option value="part_time" <?php echo (isset($profile['availability']) && $profile['availability'] === 'part_time') ? 'selected' : ''; ?>>Part Time</option>
                            <option value="contract" <?php echo (isset($profile['availability']) && $profile['availability'] === 'contract') ? 'selected' : ''; ?>>Contract</option>
                            <option value="freelance" <?php echo (isset($profile['availability']) && $profile['availability'] === 'freelance') ? 'selected' : ''; ?>>Freelance</option>
                        </select>
                    </div>
                </div>

                <!-- Experience Section -->
                <div class="form-section">
                    <h3 class="section-title">Experience</h3>
                    <div class="mb-3">
                        <label for="experience" class="form-label">Work Experience</label>
                        <textarea class="form-control" id="experience" name="experience" rows="5" 
                                  placeholder="Describe your work experience, including job titles, companies, and responsibilities."><?php echo isset($profile['experience']) ? htmlspecialchars($profile['experience']) : ''; ?></textarea>
                        <div class="form-text">Format: Job Title, Company Name, Duration - Description of responsibilities and achievements.</div>
                    </div>
                </div>

                <!-- Education Section -->
                <div class="form-section">
                    <h3 class="section-title">Education</h3>
                    <div class="mb-3">
                        <label for="education" class="form-label">Educational Background</label>
                        <textarea class="form-control" id="education" name="education" rows="4" 
                                  placeholder="List your educational qualifications, including degrees, institutions, and graduation years."><?php echo isset($profile['education']) ? htmlspecialchars($profile['education']) : ''; ?></textarea>
                        <div class="form-text">Format: Degree/Certificate, Institution, Year - Additional information.</div>
                    </div>
                </div>

                <!-- Contact Information Section -->
                <div class="form-section">
                    <h3 class="section-title">Contact Information</h3>
                    <div class="mb-3">
                        <label for="phone_number" class="form-label">Phone Number</label>
                        <input type="tel" class="form-control" id="phone_number" name="phone_number" 
                               value="<?php echo (isset($profile['phone_number']) ? htmlspecialchars($profile['phone_number']) : (isset($member['phone_number']) ? htmlspecialchars($member['phone_number']) : '')); ?>"
                               placeholder="Enter your phone number">
                        <div class="form-text">Enter your phone number for potential employers to contact you.</div>
                    </div>
                </div>

                <!-- Portfolio Section -->
                <div class="form-section">
                    <h3 class="section-title">Portfolio</h3>
                    <div class="mb-3">
                        <label for="portfolio_url" class="form-label">Portfolio Website URL</label>
                        <input type="url" class="form-control" id="portfolio_url" name="portfolio_url" 
                               value="<?php echo isset($profile['portfolio_url']) ? htmlspecialchars($profile['portfolio_url']) : ''; ?>"
                               placeholder="https://yourportfolio.com">
                        <div class="form-text">Enter the URL to your portfolio website or social media profile showcasing your work.</div>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="text-center mt-4">
                    <button type="submit" class="btn btn-primary btn-lg px-5">
                        <?php echo ($isEdit ?? false) ? "Update Profile" : "Create Profile"; ?>
                    </button>
                </div>
            </form>
        <?php endif; ?>
    </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>
    <!-- Tagify JS -->
    <script src="https://cdn.jsdelivr.net/npm/@yaireo/tagify"></script>
    <script>
        // Initialize Tagify for skills input
        var skillsInput = document.querySelector('#skills');
        if (skillsInput) {
            new Tagify(skillsInput, {
                delimiters: ',',
                pattern: /^.{0,20}$/,
                maxTags: 10
            });
        }
        
        // Preview profile picture before upload
        document.getElementById('profilePicture').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    const preview = document.getElementById('profilePreview');
                    if (preview.tagName === 'IMG') {
                        preview.src = event.target.result;
                    } else {
                        // Replace the div with an img
                        const img = document.createElement('img');
                        img.src = event.target.result;
                        img.alt = 'Profile Picture';
                        img.className = 'profile-preview';
                        img.id = 'profilePreview';
                        preview.parentNode.replaceChild(img, preview);
                    }
                };
                reader.readAsDataURL(file);
            }
        });
    </script>
</body>
</html>
