<?php
session_start();
require_once '../logic/db_config.php';

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

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'לא מחובר']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'שיטה לא חוקית']);
    exit();
}

$userId    = $_SESSION['user_id'];
$firstName = trim($_POST['first_name'] ?? '');
$lastName  = trim($_POST['last_name']  ?? '');
$email     = trim($_POST['email']      ?? '');
$phone     = trim($_POST['phone']      ?? '');
$city      = trim($_POST['city']       ?? '');
$street    = trim($_POST['street']     ?? '');
$houseNum  = trim($_POST['house_number'] ?? '');
$apartment = trim($_POST['apartment']  ?? '');

// ולידציה בסיסית
if (!$firstName || !$lastName || !$email) {
    echo json_encode(['success' => false, 'message' => 'שם ואימייל הם שדות חובה']);
    exit();
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => 'כתובת אימייל לא תקינה']);
    exit();
}

// טיפול בתמונת פרופיל (אופציונלי)
$pictureUpdate = '';
$pictureValue  = null;

if (!empty($_FILES['profile_picture']['name'])) {
    $file     = $_FILES['profile_picture'];
    $allowed  = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
    $finfo    = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mimeType, $allowed)) {
        echo json_encode(['success' => false, 'message' => 'סוג קובץ לא נתמך (JPEG/PNG/WEBP בלבד)']);
        exit();
    }
    if ($file['size'] > 3 * 1024 * 1024) { // מקסימום 3MB
        echo json_encode(['success' => false, 'message' => 'הקובץ גדול מדי (מקסימום 3MB)']);
        exit();
    }

    $ext      = pathinfo($file['name'], PATHINFO_EXTENSION);
    $fileName = 'profile_' . $userId . '_' . time() . '.' . $ext;
    $destPath = '../uploads/' . $fileName;

    if (!move_uploaded_file($file['tmp_name'], $destPath)) {
        echo json_encode(['success' => false, 'message' => 'שגיאה בשמירת התמונה']);
        exit();
    }

    $pictureValue  = 'uploads/' . $fileName;
    $pictureUpdate = ', profile_picture = ?';
}

// בניית כתובת מפורמטת
$formattedAddress = trim("$street $houseNum, $city");
if ($apartment) $formattedAddress .= " דירה $apartment";

// שמירה בDB
$sql  = "UPDATE users SET first_name=?, last_name=?, email=?, phone=?, city=?, street=?, house_number=?, apartment=?, formatted_address=?$pictureUpdate WHERE user_id=?";
$stmt = $conn->prepare($sql);

if ($pictureValue) {
    $stmt->bind_param("sssssssssi",
        $firstName, $lastName, $email, $phone,
        $city, $street, $houseNum, $apartment, $formattedAddress,
        $pictureValue, $userId
    );
    // bind עם 11 פרמטרים כולל התמונה
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssssssssssi",
        $firstName, $lastName, $email, $phone,
        $city, $street, $houseNum, $apartment, $formattedAddress,
        $pictureValue, $userId
    );
} else {
    $stmt->bind_param("sssssssssi",
        $firstName, $lastName, $email, $phone,
        $city, $street, $houseNum, $apartment, $formattedAddress,
        $userId
    );
}

if ($stmt->execute()) {
    // עדכון ה-Session
    $_SESSION['first_name']   = $firstName;
    $_SESSION['user_email']   = $email;
    $_SESSION['user_address'] = $formattedAddress;

    $response = ['success' => true, 'message' => 'הפרופיל עודכן בהצלחה'];
    if ($pictureValue) $response['profile_picture'] = $pictureValue;
    echo json_encode($response);
} else {
    error_log("update_profile error: " . $stmt->error);
    echo json_encode(['success' => false, 'message' => 'שגיאה בשמירת הנתונים']);
}
