<?php
session_start();
include('../includes/config.php');

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$user_id = $_SESSION['user_id'];

$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone_number = trim($_POST['phone_number'] ?? '');
$password = $_POST['password'] ?? '';
$cropped_image = $_POST['cropped_image'] ?? '';

if (empty($first_name) || empty($last_name) || empty($email)) {
    echo json_encode(['success' => false, 'message' => 'First name, last name, and email are required.']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'Invalid email format.']);
    exit;
}

$stmt = $conn->prepare("SELECT id FROM users WHERE email = ? AND id != ?");
$stmt->bind_param("si", $email, $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'Email already in use by another account.']);
    exit;
}
$stmt->close();

$profile_picture_filename = null;
if (!empty($cropped_image)) {
    if (preg_match('/^data:image\/(\w+);base64,/', $cropped_image, $type)) {
        $cropped_image = substr($cropped_image, strpos($cropped_image, ',') + 1);
        $type = strtolower($type[1]);

        if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid image type.']);
            exit;
        }

        $cropped_image = base64_decode($cropped_image);
        if ($cropped_image === false) {
            echo json_encode(['success' => false, 'message' => 'Base64 decode failed.']);
            exit;
        }

        $profile_picture_filename = 'profile_' . $user_id . '_' . time() . '.' . $type;
        $upload_path = __DIR__ . '/../uploads/' . $profile_picture_filename;

        if (!file_put_contents($upload_path, $cropped_image)) {
            echo json_encode(['success' => false, 'message' => 'Failed to save profile picture.']);
            exit;
        }

        $stmt = $conn->prepare("SELECT profile_picture FROM users WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();

        if ($result && $result['profile_picture'] && $result['profile_picture'] !== 'default.png') {
            $old_file = __DIR__ . '/../uploads/' . $result['profile_picture'];
            if (file_exists($old_file)) {
                @unlink($old_file);
            }
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid image data format.']);
        exit;
    }
}

if (!empty($password)) {
    $password_hash = password_hash($password, PASSWORD_DEFAULT);
    if ($profile_picture_filename) {
        $sql = "UPDATE users SET first_name=?, last_name=?, email=?, phone_number=?, password=?, profile_picture=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssssi", $first_name, $last_name, $email, $phone_number, $password_hash, $profile_picture_filename, $user_id);
    } else {
        $sql = "UPDATE users SET first_name=?, last_name=?, email=?, phone_number=?, password=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssi", $first_name, $last_name, $email, $phone_number, $password_hash, $user_id);
    }
} else {
    if ($profile_picture_filename) {
        $sql = "UPDATE users SET first_name=?, last_name=?, email=?, phone_number=?, profile_picture=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sssssi", $first_name, $last_name, $email, $phone_number, $profile_picture_filename, $user_id);
    } else {
        $sql = "UPDATE users SET first_name=?, last_name=?, email=?, phone_number=? WHERE id=?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ssssi", $first_name, $last_name, $email, $phone_number, $user_id);
    }
}

if ($stmt->execute()) {
    echo json_encode(['success' => true, 'message' => 'Profile updated successfully.']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to update profile.']);
}

$stmt->close();
$conn->close();
exit;
