<?php

session_start();

require '../../config.php';
require '../admin_config.php';
require '../functions.php';
require '../views/header.view.php';

if (isset($_SESSION['user_email'])){

$connect = connect();
if(!$connect){
    header('Location: ./error.php');
}

$check_access = check_access($connect);

if ($check_access['user_role'] == 1 || $check_access['user_role'] == 2){
    
    // Handle form submission
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'update_profile') {
        
        $user_id = $_SESSION['user_id'];
        $user_bio = cleardata($_POST['user_bio']);
        $user_facebook = cleardata($_POST['user_facebook']);
        $user_twitter = cleardata($_POST['user_twitter']);
        $user_instagram = cleardata($_POST['user_instagram']);
        $user_linkedin = cleardata($_POST['user_linkedin']);
        $user_website = cleardata($_POST['user_website']);
        
        // Handle avatar upload
        $avatar_filename = null;
        if (isset($_FILES['user_avatar']) && $_FILES['user_avatar']['error'] == 0) {
            $allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
            $file_type = $_FILES['user_avatar']['type'];
            
            if (in_array($file_type, $allowed_types)) {
                $file_extension = pathinfo($_FILES['user_avatar']['name'], PATHINFO_EXTENSION);
                $avatar_filename = 'avatar_' . $user_id . '_' . time() . '.' . $file_extension;
                $upload_path = '../../images/' . $avatar_filename;
                
                if (move_uploaded_file($_FILES['user_avatar']['tmp_name'], $upload_path)) {
                    // Delete old avatar if it's not the default
                    $old_avatar_stmt = $connect->prepare("SELECT user_avatar FROM users WHERE user_id = :id");
                    $old_avatar_stmt->execute([':id' => $user_id]);
                    $old_avatar = $old_avatar_stmt->fetchColumn();
                    
                    if ($old_avatar && $old_avatar != 'avatar.png' && file_exists('../../images/' . $old_avatar)) {
                        unlink('../../images/' . $old_avatar);
                    }
                } else {
                    $error = "Failed to upload avatar image.";
                }
            } else {
                $error = "Invalid file type. Please upload JPG, PNG, GIF, or WebP image.";
            }
        }
        
        // Update profile
        if ($avatar_filename) {
            $stmt = $connect->prepare("UPDATE users SET 
                user_bio = :bio,
                user_facebook = :facebook,
                user_twitter = :twitter,
                user_instagram = :instagram,
                user_linkedin = :linkedin,
                user_website = :website,
                user_avatar = :avatar
                WHERE user_id = :id");
            
            $stmt->execute([
                ':bio' => $user_bio,
                ':facebook' => $user_facebook,
                ':twitter' => $user_twitter,
                ':instagram' => $user_instagram,
                ':linkedin' => $user_linkedin,
                ':website' => $user_website,
                ':avatar' => $avatar_filename,
                ':id' => $user_id
            ]);
        } else {
            $stmt = $connect->prepare("UPDATE users SET 
                user_bio = :bio,
                user_facebook = :facebook,
                user_twitter = :twitter,
                user_instagram = :instagram,
                user_linkedin = :linkedin,
                user_website = :website
                WHERE user_id = :id");
            
            $stmt->execute([
                ':bio' => $user_bio,
                ':facebook' => $user_facebook,
                ':twitter' => $user_twitter,
                ':instagram' => $user_instagram,
                ':linkedin' => $user_linkedin,
                ':website' => $user_website,
                ':id' => $user_id
            ]);
        }
        
        if (!isset($error)) {
            $success = "Author profile updated successfully!";
        }
    }
    
    // Get current user data
    $user_id = $_SESSION['user_id'];
    $stmt = $connect->prepare("SELECT * FROM users WHERE user_id = :id");
    $stmt->execute([':id' => $user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
    require '../views/author_profile.view.php';
	
}else{
	header('Location:'.SITE_URL);
}

require '../views/footer.view.php';

}else{
	header('Location: ./login.php');	
}

?>
