<?php
header('Content-Type: application/json');
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/auth.php';

$response = [
    'success' => false,
    'message' => '',
    'user' => null,
    'profile' => null,
    'experiences' => [],
    'educations' => []
];

// Helper function to process profile image uploads (defined outside conditional block to avoid redeclaration)
function processImageUpload($fileInputName, $upload_dir, $prefix, $user_id) {
    if (isset($_FILES[$fileInputName]) && $_FILES[$fileInputName]['error'] === UPLOAD_ERR_OK) {
        $tmp_name = $_FILES[$fileInputName]['tmp_name'];
        $original_name = $_FILES[$fileInputName]['name'];
        $ext = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
        
        // Max file size: 2MB for profile images
        if ($_FILES[$fileInputName]['size'] > 2 * 1024 * 1024) return false;
        
        $allowed_exts = ['jpg', 'jpeg', 'png'];
        if (!in_array($ext, $allowed_exts)) return false;
        
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($finfo, $tmp_name);
        finfo_close($finfo);
        
        $allowed_mimes = ['image/jpeg', 'image/png'];
        if (!in_array($mime, $allowed_mimes)) return false;
        
        $filename = $prefix . '_' . $user_id . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
        if (move_uploaded_file($tmp_name, $upload_dir . '/' . $filename)) {
            return 'uploads/profiles/' . $filename;
        }
    }
    return false;
}

if (!isLoggedIn()) {
    $response['message'] = "Unauthorized.";
    echo json_encode($response);
    exit();
}

$user_id = $_SESSION['user_id'];

// Get User Profile Data helper
function fetchProfileData($pdo, $user_id, &$response) {
    try {
        $stmt = $pdo->prepare("SELECT id, username, email, role, headline, location, about_summary, skills, profile_picture_url, banner_picture_url FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $response['user'] = $stmt->fetch(PDO::FETCH_ASSOC);

        $role = $response['user']['role'];
        if ($role === 'speaker') {
            $stmt = $pdo->prepare("SELECT * FROM speaker_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } elseif ($role === 'organizer') {
            $stmt = $pdo->prepare("SELECT * FROM organizer_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        } elseif ($role === 'sponsor') {
            $stmt = $pdo->prepare("SELECT * FROM sponsor_profiles WHERE user_id = ?");
            $stmt->execute([$user_id]);
            $response['profile'] = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
        }

        $stmt = $pdo->prepare("SELECT * FROM user_experiences WHERE user_id = ? ORDER BY start_date DESC");
        $stmt->execute([$user_id]);
        $response['experiences'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

        $stmt = $pdo->prepare("SELECT * FROM user_educations WHERE user_id = ? ORDER BY start_date DESC");
        $stmt->execute([$user_id]);
        $response['educations'] = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
    } catch (PDOException $e) { }
}

fetchProfileData($pdo, $user_id, $response);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $response['message'] = "Security check failed (CSRF). Please try again.";
        echo json_encode($response);
        exit();
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'change_password') {
        $current_password = $_POST['current_password'] ?? '';
        $new_password = $_POST['new_password'] ?? '';
        $confirm_password = $_POST['confirm_password'] ?? '';
        
        if (empty($current_password) || empty($new_password) || empty($confirm_password)) {
            $response['message'] = "All password fields are required.";
        } elseif ($new_password !== $confirm_password) {
            $response['message'] = "New password and confirmation password do not match.";
        } elseif (strlen($new_password) < 6) {
            $response['message'] = "New password must be at least 6 characters long.";
        } else {
            try {
                $stmt = $pdo->prepare("SELECT password FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $hash = $stmt->fetchColumn();
                
                if (!password_verify($current_password, $hash)) {
                    $response['message'] = "Current password is incorrect.";
                } else {
                    $new_hash = password_hash($new_password, PASSWORD_DEFAULT);
                    $stmt_update = $pdo->prepare("UPDATE users SET password = ? WHERE id = ?");
                    $stmt_update->execute([$new_hash, $user_id]);
                    $response['success'] = true;
                    $response['message'] = "Password successfully changed.";
                }
            } catch (PDOException $e) {
                $response['message'] = "Database error: " . $e->getMessage();
            }
        }
    } elseif ($action === 'update_profile') {
        $email = trim($_POST['email'] ?? '');
        $headline = trim($_POST['headline'] ?? '');
        $location = trim($_POST['location'] ?? '');
        $about = trim($_POST['about_summary'] ?? '');
        $skills = trim($_POST['skills'] ?? '');
        
        if (empty($email)) {
            $response['message'] = "Email cannot be empty.";
        } else {
            try {
                $check_email = $pdo->prepare("SELECT COUNT(*) FROM users WHERE email = ? AND id != ?");
                $check_email->execute([$email, $user_id]);
                if ($check_email->fetchColumn() > 0) {
                    $response['message'] = "This email address is already in use.";
                } else {
                    $profile_picture_url = $response['user']['profile_picture_url'] ?? '';
                    $banner_picture_url = $response['user']['banner_picture_url'] ?? '';
                    
                    $upload_dir = __DIR__ . '/../uploads/profiles';
                    if (!is_dir($upload_dir)) {
                        mkdir($upload_dir, 0755, true);
                    }

                    $uploaded_avatar = processImageUpload('profile_picture', $upload_dir, 'avatar', $user_id);
                    if ($uploaded_avatar) $profile_picture_url = $uploaded_avatar;

                    $uploaded_banner = processImageUpload('banner_picture', $upload_dir, 'banner', $user_id);
                    if ($uploaded_banner) $banner_picture_url = $uploaded_banner;

                    $stmt = $pdo->prepare("UPDATE users SET email = ?, headline = ?, location = ?, about_summary = ?, skills = ?, profile_picture_url = ?, banner_picture_url = ? WHERE id = ?");
                    $stmt->execute([$email, $headline, $location, $about, $skills, $profile_picture_url, $banner_picture_url, $user_id]);
                    $_SESSION['email'] = $email;
                    
                    fetchProfileData($pdo, $user_id, $response);
                    $response['success'] = true;
                    $response['message'] = "Profile updated successfully.";
                }
            } catch (PDOException $e) {
                $response['message'] = "An unexpected error occurred. Please try again later.";
            }
        }
    } elseif ($action === 'add_experience') {
        $title = trim($_POST['title'] ?? '');
        $company = trim($_POST['company'] ?? '');
        $location = trim($_POST['location'] ?? '');
        $start_date = $_POST['start_date'] ?? '';
        $end_date = $_POST['end_date'] ?? null;
        $is_current = isset($_POST['is_current']) ? 1 : 0;
        $description = trim($_POST['description'] ?? '');
        
        if (empty($end_date) || $is_current) $end_date = null;
        
        if (!empty($title) && !empty($company) && !empty($start_date)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO user_experiences (user_id, title, company, location, start_date, end_date, is_current, description) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$user_id, $title, $company, $location, $start_date, $end_date, $is_current, $description]);
                
                fetchProfileData($pdo, $user_id, $response);
                $response['success'] = true;
                $response['message'] = "Experience added.";
            } catch (PDOException $e) {
                $response['message'] = "An unexpected error occurred. Please try again later.";
            }
        } else {
            $response['message'] = "Title, Company, and Start Date are required.";
        }
    } elseif ($action === 'add_education') {
        $school = trim($_POST['school'] ?? '');
        $degree = trim($_POST['degree'] ?? '');
        $field = trim($_POST['field_of_study'] ?? '');
        $start_date = $_POST['start_date'] ?? null;
        $end_date = $_POST['end_date'] ?? null;
        $description = trim($_POST['description'] ?? '');
        
        if (empty($start_date)) $start_date = null;
        if (empty($end_date)) $end_date = null;
        
        if (!empty($school)) {
            try {
                $stmt = $pdo->prepare("INSERT INTO user_educations (user_id, school, degree, field_of_study, start_date, end_date, description) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$user_id, $school, $degree, $field, $start_date, $end_date, $description]);
                
                fetchProfileData($pdo, $user_id, $response);
                $response['success'] = true;
                $response['message'] = "Education added.";
            } catch (PDOException $e) {
                $response['message'] = "Database error: " . $e->getMessage();
            }
        } else {
            $response['message'] = "School is required.";
        }
    } elseif ($action === 'delete_exp') {
        $id = (int)($_POST['id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM user_experiences WHERE id = ? AND user_id = ?")->execute([$id, $user_id]);
            fetchProfileData($pdo, $user_id, $response);
            $response['success'] = true;
            $response['message'] = "Experience removed.";
        } catch (PDOException $e) { }
    } elseif ($action === 'delete_edu') {
        $id = (int)($_POST['id'] ?? 0);
        try {
            $pdo->prepare("DELETE FROM user_educations WHERE id = ? AND user_id = ?")->execute([$id, $user_id]);
            fetchProfileData($pdo, $user_id, $response);
            $response['success'] = true;
            $response['message'] = "Education removed.";
        } catch (PDOException $e) { }
    } elseif ($action === 'update_role') {
        $role = $response['user']['role'];
        try {
            if ($role === 'speaker') {
                $full_name = trim($_POST['full_name'] ?? '');
                $bio = trim($_POST['bio'] ?? '');
                $expertise = trim($_POST['expertise'] ?? '');
                $organization = trim($_POST['organization'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM speaker_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO speaker_profiles (user_id, full_name, bio, expertise, organization) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $full_name, $bio, $expertise, $organization]);
                } else {
                    $stmt = $pdo->prepare("UPDATE speaker_profiles SET full_name = ?, bio = ?, expertise = ?, organization = ? WHERE user_id = ?");
                    $stmt->execute([$full_name, $bio, $expertise, $organization, $user_id]);
                }
            } elseif ($role === 'organizer') {
                $full_name = trim($_POST['full_name'] ?? '');
                $phone = trim($_POST['phone'] ?? '');
                $company = trim($_POST['company'] ?? '');
                $department = trim($_POST['department'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM organizer_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO organizer_profiles (user_id, full_name, phone, company, department) VALUES (?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $full_name, $phone, $company, $department]);
                } else {
                    $stmt = $pdo->prepare("UPDATE organizer_profiles SET full_name = ?, phone = ?, company = ?, department = ? WHERE user_id = ?");
                    $stmt->execute([$full_name, $phone, $company, $department, $user_id]);
                }
            } elseif ($role === 'sponsor') {
                $company_name = trim($_POST['company_name'] ?? '');
                $website_url = trim($_POST['website_url'] ?? '');
                $description = trim($_POST['description'] ?? '');
                
                $check = $pdo->prepare("SELECT COUNT(*) FROM sponsor_profiles WHERE user_id = ?");
                $check->execute([$user_id]);
                if ($check->fetchColumn() == 0) {
                    $stmt = $pdo->prepare("INSERT INTO sponsor_profiles (user_id, company_name, website_url, description) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$user_id, $company_name, $website_url, $description]);
                } else {
                    $stmt = $pdo->prepare("UPDATE sponsor_profiles SET company_name = ?, website_url = ?, description = ? WHERE user_id = ?");
                    $stmt->execute([$company_name, $website_url, $description, $user_id]);
                }
            }
            fetchProfileData($pdo, $user_id, $response);
            $response['success'] = true;
            $response['message'] = "Role details updated.";
        } catch (PDOException $e) {
            $response['message'] = "An unexpected error occurred. Please try again later.";
        }
    }
} else {
    // GET requests return profile
    $response['success'] = true;
}

echo json_encode($response);
