<?php
define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

// Include helpers if not already included
if (!function_exists('setFlashMessage')) {
    function setFlashMessage($message, $type = 'success') {
        if (!isset($_SESSION)) {
            session_start();
        }
        $_SESSION['flash_message'] = [
            'message' => $message,
            'type' => $type
        ];
    }
}

require_once __DIR__ . '/../classes/Profile.php';

requireLogin();

$pageTitle = 'Edit Profile';
$currentUserId = getUserId();

// Get database connection
$database = \App\Database::getInstance();
$db = $database->getConnection();
$profile = new \App\Profile($db);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = [
        'full_name' => $_POST['full_name'] ?? '',
        'email' => $_POST['email'] ?? '',
        'bio' => $_POST['bio'] ?? '',
        'tagline' => $_POST['tagline'] ?? '',
        'about_me' => $_POST['about_me'] ?? '',
        'date_of_birth' => $_POST['date_of_birth'] ?? null,
        'gender' => $_POST['gender'] ?? null,
        'occupation' => $_POST['occupation'] ?? '',
        'education_level' => $_POST['education_level'] ?? null,
        'website' => $_POST['website'] ?? '',
        'secondary_phone' => $_POST['secondary_phone'] ?? '',
        'whatsapp_number' => $_POST['whatsapp_number'] ?? '',
        'facebook_url' => $_POST['facebook_url'] ?? '',
        'twitter_url' => $_POST['twitter_url'] ?? '',
        'instagram_url' => $_POST['instagram_url'] ?? '',
        'linkedin_url' => $_POST['linkedin_url'] ?? '',
        'region_id' => !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
        'district_id' => !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null,
        'subcounty_id' => !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null,
        'parish_id' => !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null,
        'village_id' => !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null,
        'skills' => isset($_POST['skills']) ? explode(',', $_POST['skills']) : [],
        'interests' => isset($_POST['interests']) ? explode(',', $_POST['interests']) : [],
    ];
    
    $result = $profile->updateProfile($currentUserId, $data);
    
    if ($result['success']) {
        setFlashMessage('Profile updated successfully!', 'success');
        header('Location: ' . APP_URL . '/profile/');
        exit;
    } else {
        $error_message = $result['message'];
    }
}

// Get current profile data
$userData = $profile->getProfile($currentUserId, $currentUserId);

// Get location data for dropdowns
$stmt = $db->query("SELECT * FROM regions ORDER BY region_name");
$regions = $stmt->fetchAll(PDO::FETCH_ASSOC);

include_once __DIR__ . '/../includes/meta.php';
include_once __DIR__ . '/../includes/header.php';
?>

<style>
.edit-profile-page {
    background: #f0f2f5;
    min-height: calc(100vh - 120px);
    padding: 20px 0;
}

.edit-form-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    padding: 30px;
    margin-bottom: 20px;
}

.section-title {
    font-size: 20px;
    font-weight: 700;
    color: #1c1e21;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 2px solid #f0f2f5;
}

.form-group {
    margin-bottom: 20px;
}

.form-label {
    display: block;
    font-size: 14px;
    font-weight: 600;
    color: #1c1e21;
    margin-bottom: 8px;
}

.form-control {
    width: 100%;
    padding: 12px 16px;
    border: 1px solid #e4e6eb;
    border-radius: 8px;
    font-size: 15px;
    transition: all 0.2s;
}

.form-control:focus {
    outline: none;
    border-color: #1877f2;
    box-shadow: 0 0 0 3px rgba(24, 119, 242, 0.1);
}

textarea.form-control {
    resize: vertical;
    min-height: 100px;
}

.btn-primary {
    background: linear-gradient(135deg, #1877f2 0%, #0c5ca5 100%);
    color: #fff;
    padding: 12px 32px;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(24, 119, 242, 0.4);
}

.btn-secondary {
    background: #e4e6eb;
    color: #1c1e21;
    padding: 12px 32px;
    border-radius: 8px;
    font-size: 15px;
    font-weight: 600;
    border: none;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-block;
}

.btn-secondary:hover {
    background: #d8dadf;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}

.form-help {
    font-size: 13px;
    color: #65676b;
    margin-top: 4px;
}

.tags-input {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    padding: 8px;
    border: 1px solid #e4e6eb;
    border-radius: 8px;
    min-height: 48px;
}

.tag-item {
    background: #e7f3ff;
    color: #1877f2;
    padding: 6px 12px;
    border-radius: 16px;
    font-size: 13px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 6px;
}

.tag-remove {
    cursor: pointer;
    font-weight: 700;
}

.tag-input {
    border: none;
    outline: none;
    flex: 1;
    min-width: 120px;
    padding: 8px;
}
</style>

<div class="edit-profile-page">
    <div class="container" style="max-width: 900px;">
        
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="h3 mb-0"><i class="bi bi-person-circle text-primary me-2"></i>Edit Profile</h1>
            <a href="<?php echo APP_URL; ?>/profile/" class="btn-secondary">
                <i class="bi bi-arrow-left me-2"></i>Back to Profile
            </a>
        </div>
        
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="bi bi-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error_message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <form method="POST" action="">
            
            <!-- Basic Information -->
            <div class="edit-form-card">
                <h2 class="section-title"><i class="bi bi-person-fill text-primary me-2"></i>Basic Information</h2>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Full Name *</label>
                        <input type="text" name="full_name" class="form-control" 
                               value="<?php echo htmlspecialchars($userData['full_name'] ?? ''); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" 
                               value="<?php echo htmlspecialchars($userData['email'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Tagline</label>
                    <input type="text" name="tagline" class="form-control" 
                           placeholder="Professional headline (e.g., Experienced Coffee Farmer)"
                           value="<?php echo htmlspecialchars($userData['tagline'] ?? ''); ?>">
                    <div class="form-help">A short description that appears under your name</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Bio</label>
                    <input type="text" name="bio" class="form-control" 
                           placeholder="Short bio (e.g., Passionate about sustainable farming)"
                           value="<?php echo htmlspecialchars($userData['bio'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label">About Me</label>
                    <textarea name="about_me" class="form-control" 
                              placeholder="Tell us more about yourself..."><?php echo htmlspecialchars($userData['about_me'] ?? ''); ?></textarea>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Date of Birth</label>
                        <input type="date" name="date_of_birth" class="form-control" 
                               value="<?php echo htmlspecialchars($userData['date_of_birth'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Gender</label>
                        <select name="gender" class="form-control">
                            <option value="">Select Gender</option>
                            <option value="male" <?php echo ($userData['gender'] ?? '') === 'male' ? 'selected' : ''; ?>>Male</option>
                            <option value="female" <?php echo ($userData['gender'] ?? '') === 'female' ? 'selected' : ''; ?>>Female</option>
                            <option value="other" <?php echo ($userData['gender'] ?? '') === 'other' ? 'selected' : ''; ?>>Other</option>
                            <option value="prefer_not_to_say" <?php echo ($userData['gender'] ?? '') === 'prefer_not_to_say' ? 'selected' : ''; ?>>Prefer not to say</option>
                        </select>
                    </div>
                </div>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Occupation</label>
                        <input type="text" name="occupation" class="form-control" 
                               placeholder="e.g., Farmer, Agricultural Officer"
                               value="<?php echo htmlspecialchars($userData['occupation'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Education Level</label>
                        <select name="education_level" class="form-control">
                            <option value="">Select Level</option>
                            <option value="primary" <?php echo ($userData['education_level'] ?? '') === 'primary' ? 'selected' : ''; ?>>Primary</option>
                            <option value="secondary" <?php echo ($userData['education_level'] ?? '') === 'secondary' ? 'selected' : ''; ?>>Secondary</option>
                            <option value="certificate" <?php echo ($userData['education_level'] ?? '') === 'certificate' ? 'selected' : ''; ?>>Certificate</option>
                            <option value="diploma" <?php echo ($userData['education_level'] ?? '') === 'diploma' ? 'selected' : ''; ?>>Diploma</option>
                            <option value="degree" <?php echo ($userData['education_level'] ?? '') === 'degree' ? 'selected' : ''; ?>>Degree</option>
                            <option value="masters" <?php echo ($userData['education_level'] ?? '') === 'masters' ? 'selected' : ''; ?>>Masters</option>
                            <option value="phd" <?php echo ($userData['education_level'] ?? '') === 'phd' ? 'selected' : ''; ?>>PhD</option>
                        </select>
                    </div>
                </div>
            </div>
            
            <!-- Contact Information -->
            <div class="edit-form-card">
                <h2 class="section-title"><i class="bi bi-telephone-fill text-success me-2"></i>Contact Information</h2>
                
                <div class="form-row">
                    <div class="form-group">
                        <label class="form-label">Secondary Phone</label>
                        <input type="tel" name="secondary_phone" class="form-control" 
                               placeholder="0700000000"
                               value="<?php echo htmlspecialchars($userData['secondary_phone'] ?? ''); ?>">
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">WhatsApp Number</label>
                        <input type="tel" name="whatsapp_number" class="form-control" 
                               placeholder="0700000000"
                               value="<?php echo htmlspecialchars($userData['whatsapp_number'] ?? ''); ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Website</label>
                    <input type="url" name="website" class="form-control" 
                           placeholder="https://example.com"
                           value="<?php echo htmlspecialchars($userData['website'] ?? ''); ?>">
                </div>
            </div>
            
            <!-- Social Media -->
            <div class="edit-form-card">
                <h2 class="section-title"><i class="bi bi-share-fill text-info me-2"></i>Social Media</h2>
                
                <div class="form-group">
                    <label class="form-label"><i class="bi bi-facebook text-primary me-2"></i>Facebook</label>
                    <input type="url" name="facebook_url" class="form-control" 
                           placeholder="https://facebook.com/username"
                           value="<?php echo htmlspecialchars($userData['facebook_url'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label"><i class="bi bi-twitter text-info me-2"></i>Twitter</label>
                    <input type="url" name="twitter_url" class="form-control" 
                           placeholder="https://twitter.com/username"
                           value="<?php echo htmlspecialchars($userData['twitter_url'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label"><i class="bi bi-instagram text-danger me-2"></i>Instagram</label>
                    <input type="url" name="instagram_url" class="form-control" 
                           placeholder="https://instagram.com/username"
                           value="<?php echo htmlspecialchars($userData['instagram_url'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label class="form-label"><i class="bi bi-linkedin text-primary me-2"></i>LinkedIn</label>
                    <input type="url" name="linkedin_url" class="form-control" 
                           placeholder="https://linkedin.com/in/username"
                           value="<?php echo htmlspecialchars($userData['linkedin_url'] ?? ''); ?>">
                </div>
            </div>
            
            <!-- Skills & Interests -->
            <div class="edit-form-card">
                <h2 class="section-title"><i class="bi bi-lightbulb-fill text-warning me-2"></i>Skills & Interests</h2>
                
                <div class="form-group">
                    <label class="form-label">Skills</label>
                    <input type="text" name="skills" class="form-control" 
                           placeholder="Enter skills separated by commas (e.g., Coffee Farming, Soil Management)"
                           value="<?php echo htmlspecialchars(implode(', ', $userData['skills'] ?? [])); ?>">
                    <div class="form-help">Separate skills with commas</div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Interests</label>
                    <input type="text" name="interests" class="form-control" 
                           placeholder="Enter interests separated by commas (e.g., Organic Farming, Beekeeping)"
                           value="<?php echo htmlspecialchars(implode(', ', $userData['interests'] ?? [])); ?>">
                    <div class="form-help">Separate interests with commas</div>
                </div>
            </div>
            
            <!-- Actions -->
            <div class="d-flex justify-content-end gap-3">
                <a href="<?php echo APP_URL; ?>/profile/" class="btn-secondary">Cancel</a>
                <button type="submit" class="btn-primary">
                    <i class="bi bi-check-circle me-2"></i>Save Changes
                </button>
            </div>
            
        </form>
        
    </div>
</div>

<?php
include_once __DIR__ . '/../includes/footer.php';
include_once __DIR__ . '/../includes/bottom-nav.php';
?>