<?php
$page_title = "Profile Settings";
require_once '../config/config.php';

require_once '../includes/user_auth.php';
require_once '../includes/functions.php';




$db = Database::getInstance()->connect();
if (!$auth->isLoggedIn()) {
    header("Location: ../login.php");
    exit();
}
$user_id = $auth->getCurrentUserId();

// Get user data
$user_stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$user = $user_stmt->fetch();

if (!$user) {
    $_SESSION['error'] = "User not found";
    header('Location: dashboard.php');
    exit();
}

// Handle profile update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    $full_name = trim($_POST['full_name']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);
    $country = trim($_POST['country']);
    $city = trim($_POST['city']);
    $address = trim($_POST['address']);
    $date_of_birth = trim($_POST['date_of_birth']);

    $errors = [];

    // Validation
    if (empty($full_name)) {
        $errors[] = "Full name is required";
    }

    if (empty($email)) {
        $errors[] = "Email is required";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "Invalid email format";
    } elseif ($email !== $user['email']) {
        // Check if email is already taken
        $email_check = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
        $email_check->execute([$email, $user_id]);
        if ($email_check->rowCount() > 0) {
            $errors[] = "Email is already taken";
        }
    }

    if (empty($errors)) {
        try {
            $update_stmt = $db->prepare("
                UPDATE users SET
                    full_name = ?,
                    email = ?,
                    phone = ?,
                    country = ?,
                    city = ?,
                    address = ?,
                    date_of_birth = ?,
                    updated_at = NOW()
                WHERE id = ?
            ");

            $result = $update_stmt->execute([
                $full_name,
                $email,
                $phone,
                $country,
                $city,
                $address,
                $date_of_birth ? $date_of_birth : null,
                $user_id
            ]);

            if ($result) {
                $_SESSION['success'] = "Profile updated successfully";
                // Update session email if changed
                if ($email !== $user['email']) {
                    $_SESSION['email'] = $email;
                }
                // Refresh user data
                $user_stmt->execute([$user_id]);
                $user = $user_stmt->fetch();
            } else {
                $_SESSION['error'] = "Failed to update profile";
            }
        } catch (Exception $e) {
            $_SESSION['error'] = "An error occurred while updating profile";
        }
    } else {
        $_SESSION['error'] = implode("<br>", $errors);
    }

    header('Location: profile.php');
    exit();
}

// Handle profile picture upload
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_picture'])) {
    if (isset($_FILES['profile_picture']) && $_FILES['profile_picture']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['profile_picture'];
        $allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
        $max_size = 5 * 1024 * 1024; // 5MB

        if (!in_array($file['type'], $allowed_types)) {
            $_SESSION['error'] = "Invalid file type. Only JPG, PNG, and GIF are allowed.";
        } elseif ($file['size'] > $max_size) {
            $_SESSION['error'] = "File size too large. Maximum size is 5MB.";
        } else {
            // Create uploads directory if it doesn't exist
            $upload_dir = '../uploads/profile/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }

            // Generate unique filename
            $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
            $filename = 'profile_' . $user_id . '_' . time() . '.' . $extension;
            $filepath = $upload_dir . $filename;

            if (move_uploaded_file($file['tmp_name'], $filepath)) {
                // Delete old profile picture if exists
                if (!empty($user['profile_picture']) && file_exists('../uploads/profile/' . $user['profile_picture'])) {
                    unlink('../uploads/profile/' . $user['profile_picture']);
                }

                // Update database
                $update_pic = $db->prepare("UPDATE users SET profile_picture = ?, updated_at = NOW() WHERE id = ?");
                $update_pic->execute([$filename, $user_id]);

                $_SESSION['success'] = "Profile picture updated successfully";
                $user['profile_picture'] = $filename;
            } else {
                $_SESSION['error'] = "Failed to upload profile picture";
            }
        }
    } else {
        $_SESSION['error'] = "Please select a valid image file";
    }

    header('Location: profile.php');
    exit();
}

// Get countries for dropdown
$countries = [
    'United States', 'United Kingdom', 'Canada', 'Australia', 'Germany', 'France', 'Italy', 'Spain',
    'Netherlands', 'Belgium', 'Switzerland', 'Austria', 'Sweden', 'Norway', 'Denmark', 'Finland',
    'Japan', 'South Korea', 'Singapore', 'Hong Kong', 'India', 'China', 'Brazil', 'Mexico',
    'Argentina', 'Chile', 'Colombia', 'Peru', 'South Africa', 'Nigeria', 'Egypt', 'Turkey',
    'Russia', 'Poland', 'Czech Republic', 'Hungary', 'Greece', 'Portugal', 'Ireland', 'New Zealand'
];
?>

<?php require_once '../includes/header_user.php'; ?>

<div class="max-w-4xl mx-auto">
    <div class="bg-white rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-6">
            <h1 class="text-2xl font-bold text-gray-800">Profile Settings</h1>
            <a href="dashboard.php" class="text-purple-600 hover:text-purple-700">
                <i class="fas fa-arrow-left mr-2"></i>Back to Dashboard
            </a>
        </div>

        <!-- Profile Picture Section -->
        <div class="mb-8">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">Profile Picture</h2>
            <div class="flex items-center space-x-6">
                <div class="relative">
                    <div class="w-24 h-24 bg-gradient-to-r from-purple-600 to-blue-600 rounded-full flex items-center justify-center text-white text-2xl font-bold">
                        <?php if (!empty($user['profile_picture']) && file_exists('../uploads/profile/' . $user['profile_picture'])): ?>
                            <img src="../uploads/profile/<?php echo htmlspecialchars($user['profile_picture']); ?>" alt="Profile Picture" class="w-24 h-24 rounded-full object-cover">
                        <?php else: ?>
                            <?php echo strtoupper(substr($user['username'], 0, 1)); ?>
                        <?php endif; ?>
                    </div>
                    <form method="POST" enctype="multipart/form-data" class="absolute -bottom-2 -right-2">
                        <label for="profile_picture" class="w-8 h-8 bg-purple-600 hover:bg-purple-700 rounded-full flex items-center justify-center cursor-pointer transition-colors">
                            <i class="fas fa-camera text-white text-sm"></i>
                            <input type="file" id="profile_picture" name="profile_picture" accept="image/*" class="hidden" onchange="this.form.submit()">
                        </label>
                        <input type="hidden" name="upload_picture" value="1">
                    </form>
                </div>
                <div>
                    <h3 class="text-lg font-medium text-gray-800"><?php echo htmlspecialchars($user['username']); ?></h3>
                    <p class="text-gray-600">Member since <?php echo date('F Y', strtotime($user['created_at'])); ?></p>
                    <p class="text-sm text-gray-500 mt-1">Click the camera icon to update your profile picture</p>
                </div>
            </div>
        </div>

        <!-- Profile Information Form -->
        <form method="POST" class="space-y-6">
            <h2 class="text-lg font-semibold text-gray-800">Personal Information</h2>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Username (Read-only) -->
                <div>
                    <label for="username" class="block text-sm font-medium text-gray-700 mb-2">Username</label>
                    <input type="text" id="username" value="<?php echo htmlspecialchars($user['username']); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md bg-gray-50 text-gray-600" readonly>
                    <p class="text-xs text-gray-500 mt-1">Username cannot be changed</p>
                </div>

                <!-- Email -->
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-2">Email Address</label>
                    <input type="email" id="email" name="email" value="<?php echo htmlspecialchars($user['email']); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" required>
                </div>

                <!-- Full Name -->
                <div>
                    <label for="full_name" class="block text-sm font-medium text-gray-700 mb-2">Full Name</label>
                    <input type="text" id="full_name" name="full_name" value="<?php echo htmlspecialchars($user['full_name'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="Enter your full name">
                </div>

                <!-- Phone -->
                <div>
                    <label for="phone" class="block text-sm font-medium text-gray-700 mb-2">Phone Number</label>
                    <input type="tel" id="phone" name="phone" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="+1 (555) 123-4567">
                </div>

                <!-- Date of Birth -->
                <div>
                    <label for="date_of_birth" class="block text-sm font-medium text-gray-700 mb-2">Date of Birth</label>
                    <input type="date" id="date_of_birth" name="date_of_birth" value="<?php echo htmlspecialchars($user['date_of_birth'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                </div>

                <!-- Country -->
                <div>
                    <label for="country" class="block text-sm font-medium text-gray-700 mb-2">Country</label>
                    <select id="country" name="country" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500">
                        <option value="">Select Country</option>
                        <?php foreach ($countries as $country_option): ?>
                            <option value="<?php echo htmlspecialchars($country_option); ?>" <?php echo ($user['country'] ?? '') === $country_option ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($country_option); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <!-- Address Information -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- City -->
                <div>
                    <label for="city" class="block text-sm font-medium text-gray-700 mb-2">City</label>
                    <input type="text" id="city" name="city" value="<?php echo htmlspecialchars($user['city'] ?? ''); ?>" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="Enter your city">
                </div>

                <!-- Address -->
                <div class="md:col-span-2">
                    <label for="address" class="block text-sm font-medium text-gray-700 mb-2">Address</label>
                    <textarea id="address" name="address" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-purple-500 focus:border-purple-500" placeholder="Enter your full address"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
                </div>
            </div>

            <!-- Account Status -->
            <div class="bg-gray-50 rounded-lg p-4">
                <h3 class="text-md font-medium text-gray-800 mb-3">Account Status</h3>
                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div class="flex items-center space-x-2">
                        <div class="w-3 h-3 rounded-full <?php echo $user['account_status'] === 'active' ? 'bg-green-500' : 'bg-red-500'; ?>"></div>
                        <span class="text-sm text-gray-600">Account Status:</span>
                        <span class="text-sm font-medium <?php echo $user['account_status'] === 'active' ? 'text-green-600' : 'text-red-600'; ?>">
                            <?php echo ucfirst($user['account_status']); ?>
                        </span>
                    </div>

                    <div class="flex items-center space-x-2">
                        <div class="w-3 h-3 rounded-full <?php echo $user['kyc_status'] === 'verified' ? 'bg-green-500' : ($user['kyc_status'] === 'pending' ? 'bg-yellow-500' : 'bg-red-500'); ?>"></div>
                        <span class="text-sm text-gray-600">KYC Status:</span>
                        <span class="text-sm font-medium <?php echo $user['kyc_status'] === 'verified' ? 'text-green-600' : ($user['kyc_status'] === 'pending' ? 'text-yellow-600' : 'text-red-600'); ?>">
                            <?php echo ucfirst($user['kyc_status']); ?>
                        </span>
                    </div>

                    <div class="flex items-center space-x-2">
                        <span class="text-sm text-gray-600">Member Since:</span>
                        <span class="text-sm font-medium text-gray-800"><?php echo date('M j, Y', strtotime($user['created_at'])); ?></span>
                    </div>
                </div>
            </div>

            <!-- Submit Button -->
            <div class="flex justify-end">
                <button type="submit" name="update_profile" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2 rounded-md font-medium transition-colors">
                    <i class="fas fa-save mr-2"></i>Update Profile
                </button>
            </div>
        </form>

        <!-- KYC Verification Section -->
        <?php if ($user['kyc_status'] !== 'verified'): ?>
        <div class="mt-8 border-t pt-8">
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-6">
                <div class="flex items-start">
                    <div class="flex-shrink-0">
                        <i class="fas fa-exclamation-triangle text-yellow-400 text-xl"></i>
                    </div>
                    <div class="ml-3">
                        <h3 class="text-sm font-medium text-yellow-800">KYC Verification Required</h3>
                        <div class="mt-2 text-sm text-yellow-700">
                            <p>To unlock full platform features including withdrawals, you need to complete KYC verification.</p>
                        </div>
                        <div class="mt-4">
                            <div class="-mx-2 -my-1.5 flex">
                                <a href="verify-email.php" class="bg-yellow-100 px-3 py-2 rounded-md text-sm font-medium text-yellow-800 hover:bg-yellow-200 transition-colors">
                                    <i class="fas fa-envelope mr-1"></i>Verify Email First
                                </a>
                                <a href="support.php" class="ml-3 bg-yellow-100 px-3 py-2 rounded-md text-sm font-medium text-yellow-800 hover:bg-yellow-200 transition-colors">
                                    <i class="fas fa-headset mr-1"></i>Contact Support
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
// Profile picture preview
document.getElementById('profile_picture').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            // Could add preview functionality here
        };
        reader.readAsDataURL(file);
    }
});

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const email = document.getElementById('email').value;
    const fullName = document.getElementById('full_name').value;

    if (!email || !validateEmail(email)) {
        e.preventDefault();
        showNotification('Please enter a valid email address', 'error');
        return false;
    }

    if (!fullName.trim()) {
        e.preventDefault();
        showNotification('Please enter your full name', 'error');
        return false;
    }
});
</script>

<?php require_once '../includes/footer.php'; ?>
