<?php
header('Content-Type: application/json');
include '../connection.php';

$response = array();

// Check if required fields are set
if (!isset($_POST['user_id'])) {
    $response['success'] = false;
    $response['message'] = 'Missing user_id';
    echo json_encode($response);
    exit;
}

$user_id    = intval($_POST['user_id']);
$nick_name  = $_POST['nick_name'] ?? '';
$country    = $_POST['country'] ?? '';
$gender     = $_POST['gender'] ?? '';
$address    = $_POST['address'] ?? '';

$image_path = null;

// Handle image upload if provided
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
    $targetDir = "../profile_images/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $fileTmpPath = $_FILES['profile_image']['tmp_name'];
    $fileName    = time() . "_" . basename($_FILES['profile_image']['name']);
    $targetFile  = $targetDir . $fileName;

    if (move_uploaded_file($fileTmpPath, $targetFile)) {
        $image_path = $targetFile;
    } else {
        $response['success'] = false;
        $response['message'] = 'Failed to upload image';
        echo json_encode($response);
        exit;
    }
}

// Check if profile exists
$checkProfile = $conn->prepare("SELECT id FROM tbl_profile WHERE user_id = ?");
$checkProfile->bind_param("i", $user_id);
$checkProfile->execute();
$checkProfile->store_result();

if ($checkProfile->num_rows > 0) {
    // Update existing profile
    $sql = "UPDATE tbl_profile SET nick_name=?, country=?, gender=?, address=?";
    if ($image_path) {
        $sql .= ", profile_image=?";
    }
    $sql .= " WHERE user_id=?";
    
    if ($image_path) {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssi", $nick_name, $country, $gender, $address, $fileName, $user_id);
    } else {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssi", $nick_name, $country, $gender, $address, $user_id);
    }
} else {
    // Insert new profile
    $sql = "INSERT INTO tbl_profile (user_id, nick_name, country, gender, address, profile_image) 
            VALUES (?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("isssss", $user_id, $nick_name, $country, $gender, $address, $fileName);
}

// Execute profile query
if ($stmt->execute()) {
    $response['success'] = true;
    $response['message'] = 'Profile updated successfully';
} else {
    $response['success'] = false;
    $response['message'] = 'Failed to update profile: ' . $stmt->error;
}

echo json_encode($response);




/*
header('Content-Type: application/json');
include '../connection.php';

$response = array();

// Check if required fields are set
if (!isset($_POST['user_id'])) {
    $response['success'] = false;
    $response['message'] = 'Missing user_id';
    echo json_encode($response);
    exit;
}

$user_id       = intval($_POST['user_id']);
$nick_name     = $_POST['nick_name'] ?? '';
$country       = $_POST['country'] ?? '';
$gender        = $_POST['gender'] ?? '';
$address       = $_POST['address'] ?? '';

$image_path = null;

// Handle image upload if provided
if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] === UPLOAD_ERR_OK) {
    $targetDir = "../profile_images/";
    if (!file_exists($targetDir)) {
        mkdir($targetDir, 0777, true);
    }

    $fileTmpPath = $_FILES['profile_image']['tmp_name'];
    $fileName    = time() . "_" . basename($_FILES['profile_image']['name']);
    $targetFile  = $targetDir . $fileName;

    if (move_uploaded_file($fileTmpPath, $targetFile)) {
        $image_path = $targetFile;
    } else {
        $response['success'] = false;
        $response['message'] = 'Failed to upload image';
        echo json_encode($response);
        exit;
    }
}

// Check if profile exists
$checkProfile = $conn->prepare("SELECT id FROM tbl_profile WHERE user_id = ?");
$checkProfile->bind_param("i", $user_id);
$checkProfile->execute();
$checkProfile->store_result();

if ($checkProfile->num_rows > 0) {
    // Update existing profile
    $sql = "UPDATE tbl_profile SET nick_name=?, country=?, gender=?, address=?";
    if ($image_path) {
        $sql .= ", profile_image=?";
    }
    $sql .= " WHERE user_id=?";
    
    if ($image_path) {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssi", $nick_name, $country, $gender, $address, $image_path, $user_id);
    } else {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssi", $nick_name, $country, $gender, $address, $user_id);
    }
} else {
    // Insert new profile
    $sql = "INSERT INTO tbl_profile (user_id, nick_name, country, gender, address, profile_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("isssss", $user_id, $nick_name, $country, $gender, $address, $image_path);
}

// Execute profile query
/*
if ($stmt->execute()) {
    // Also update main credentials table (name + email)
    $cred_stmt = $conn->prepare("UPDATE tblcred SET email=? WHERE userid=?");
    $cred_stmt->bind_param("si", $email, $user_id);
    $cred_stmt->execute();

    $response['success'] = true;
    $response['message'] = 'Profile updated successfully';
} else {
    $response['success'] = false;
    $response['message'] = 'Failed to update profile';
}

echo json_encode($response);*/
