<?php
session_start();

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

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

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

require_once '../config/db.php';

$conn = $connection;

if ($conn->connect_error) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed'
    ]);
    exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : '';
$user_id = $_SESSION['user_id'];

if ($action === 'update_profile') {
    $email = isset($_POST['email']) ? trim($_POST['email']) : '';
    $phone = isset($_POST['phone']) ? trim($_POST['phone']) : '';
    $current_password = isset($_POST['current_password']) ? $_POST['current_password'] : '';
    $new_password = isset($_POST['new_password']) ? $_POST['new_password'] : '';

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

    // Get current user data
    $user_query = $conn->prepare("SELECT password FROM users WHERE id = ?");
    $user_query->bind_param('i', $user_id);
    $user_query->execute();
    $user_result = $user_query->get_result();
    $user = $user_result->fetch_assoc();
    $user_query->close();

    if (!$user) {
        echo json_encode(['success' => false, 'message' => 'User not found']);
        exit;
    }

    // If changing password, verify current password
    if ($new_password) {
        if (!$current_password) {
            echo json_encode(['success' => false, 'message' => 'Current password is required to set a new password']);
            exit;
        }

        if (!password_verify($current_password, $user['password'])) {
            echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
            exit;
        }

        if (strlen($new_password) < 6) {
            echo json_encode(['success' => false, 'message' => 'New password must be at least 6 characters']);
            exit;
        }
    }

    // Update profile
    if ($new_password) {
        $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
        $update_query = $conn->prepare("UPDATE users SET email = ?, phone = ?, password = ? WHERE id = ?");
        $update_query->bind_param('sssi', $email, $phone, $hashed_password, $user_id);
    } else {
        $update_query = $conn->prepare("UPDATE users SET email = ?, phone = ? WHERE id = ?");
        $update_query->bind_param('ssi', $email, $phone, $user_id);
    }

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

    $update_query->close();

} else {
    // Legacy code: handle JSON input for backward compatibility
    $input = json_decode(file_get_contents('php://input'), true);

    $name = trim($input['name'] ?? '');
    $phone = trim($input['phone'] ?? '');
    $address = trim($input['address'] ?? '');

    // Validation
    if (empty($name) || strlen($name) < 2) {
        echo json_encode([
            'success' => false,
            'message' => 'Name is required (at least 2 characters)'
        ]);
        exit;
    }

    if (empty($phone) || strlen(preg_replace('/\D/', '', $phone)) < 10) {
        echo json_encode([
            'success' => false,
            'message' => 'Please enter a valid phone number'
        ]);
        exit;
    }

    try {
        $update_stmt = $conn->prepare("UPDATE users SET name = ?, phone = ? WHERE id = ?");
        
        if (!$update_stmt) {
            throw new Exception("Prepare failed: " . $conn->error);
        }
        
        $update_stmt->bind_param("ssi", $name, $phone, $user_id);
        
        if ($update_stmt->execute()) {
            $_SESSION['name'] = $name;
            
            echo json_encode([
                'success' => true,
                'message' => 'Profile updated successfully'
            ]);
        } else {
            throw new Exception("Error updating profile: " . $update_stmt->error);
        }
        
    } catch (Exception $e) {
        echo json_encode([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
}

$conn->close();
?>

