<?php
require_once 'includes/auth.php';
require_once 'helpers.php';

check_auth();

$user = current_user();
$page_title = __('user_profile');

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $email = $_POST['email'] ?? '';
    $password = $_POST['password'] ?? '';
    $password_confirm = $_POST['password_confirm'] ?? '';
    
    $errors = [];
    
    if (empty($name)) {
        $errors[] = __('name_required');
    }
    
    if (empty($email)) {
        $errors[] = __('email_required');
    }
    
    // Check if email is taken by another user
    $stmt = $db->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
    $stmt->execute([$email, $user['id']]);
    if ($stmt->fetch()) {
        $errors[] = __('email_already_taken');
    }
    
    if (!empty($password)) {
        if (strlen($password) < 6) {
            $errors[] = __('password_min_length');
        }
        if ($password !== $password_confirm) {
            $errors[] = __('passwords_do_not_match');
        }
    }
    
    // Handle avatar upload
    $avatar_path = $user['avatar'];
    if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] === UPLOAD_ERR_OK) {
        $file_tmp = $_FILES['avatar']['tmp_name'];
        $file_name = $_FILES['avatar']['name'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        $allowed_exts = ['jpg', 'jpeg', 'png', 'gif'];
        
        if (!in_array($file_ext, $allowed_exts)) {
            $errors[] = __('invalid_file_type');
        } else {
            $upload_dir = 'assets/uploads/users/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $new_file_name = 'user_' . $user['id'] . '_' . time() . '.' . $file_ext;
            $destination = $upload_dir . $new_file_name;
            
            if (move_uploaded_file($file_tmp, $destination)) {
                $avatar_path = $destination;
            } else {
                $errors[] = __('upload_failed');
            }
        }
    }
    
    if (empty($errors)) {
        try {
            $sql = "UPDATE users SET name = ?, email = ?, avatar = ?";
            $params = [$name, $email, $avatar_path];
            
            if (!empty($password)) {
                $sql .= ", password = ?";
                $params[] = password_hash($password, PASSWORD_DEFAULT);
            }
            
            $sql .= " WHERE id = ?";
            $params[] = $user['id'];
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            
            // Update session cache
            unset($_SESSION['user_cache']);
            $user = current_user(); // Refresh user data
            
            $success_msg = __('profile_updated_successfully');
        } catch (Exception $e) {
            $errors[] = __('error_updating_profile') . ': ' . $e->getMessage();
        }
    }
}

require_once 'includes/layout/header.php';
require_once 'includes/pages/profile.php';
require_once 'includes/layout/footer.php';
