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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not logged in']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$customer_id = $_SESSION['user_id'];
$user_name = trim($input['user_name'] ?? '');
$user_email = trim($input['email'] ?? trim($input['user_email'] ?? ''));
$phone = trim($input['phone'] ?? '');
$city = trim($input['city'] ?? '');
$bio = trim($input['bio'] ?? '');
$address = trim($input['address'] ?? '');

// At least one field must be provided
if (empty($user_name) && empty($user_email) && empty($phone) && empty($city) && empty($bio) && empty($address)) {
    echo json_encode(['success' => false, 'message' => 'No data to update']);
    exit;
}

try {
    // Ensure users table has all required columns
    $conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS phone VARCHAR(20) AFTER email");
    $conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS address TEXT AFTER phone");
    $conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS city VARCHAR(100) AFTER address");
    $conn->query("ALTER TABLE users ADD COLUMN IF NOT EXISTS bio TEXT AFTER city");

    $updates = [];
    $params = [];
    $types = '';

    if (!empty($user_name)) {
        $updates[] = "user_name = ?";
        $params[] = $user_name;
        $types .= 's';
    }
    if (!empty($user_email)) {
        $updates[] = "email = ?";
        $params[] = $user_email;
        $types .= 's';
    }
    if (!empty($phone)) {
        $updates[] = "phone = ?";
        $params[] = $phone;
        $types .= 's';
    }
    if (!empty($city)) {
        $updates[] = "city = ?";
        $params[] = $city;
        $types .= 's';
    }
    if (!empty($bio)) {
        $updates[] = "bio = ?";
        $params[] = $bio;
        $types .= 's';
    }
    if (!empty($address)) {
        $updates[] = "address = ?";
        $params[] = $address;
        $types .= 's';
    }

    $params[] = $customer_id;
    $types .= 'i';

    $query = "UPDATE users SET " . implode(", ", $updates) . " WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $result = $stmt->execute();
    $stmt->close();

    if ($result) {
        // Update session
        if (!empty($user_name)) $_SESSION['user_name'] = $user_name;
        if (!empty($user_email)) $_SESSION['user_email'] = $user_email;

        echo json_encode(['success' => true, 'message' => 'Profile updated successfully']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to update profile']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

