<?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' => 'User not logged in'
    ]);
    exit;
}

$response = [
    'success' => false,
    'message' => '',
    'avatarUrl' => ''
];

try {
    // Check if file was uploaded
    if (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('No file uploaded or upload error');
    }

    $file = $_FILES['avatar'];
    $user_id = $_SESSION['user_id'];

    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (!in_array($mime_type, $allowed_types)) {
        throw new Exception('Invalid file type. Only images allowed.');
    }

    // Validate file size (max 5MB)
    if ($file['size'] > 5 * 1024 * 1024) {
        throw new Exception('File size exceeds 5MB limit');
    }

    // Create uploads directory if it doesn't exist
    $upload_dir = __DIR__ . '/../uploads/avatars/';
    if (!is_dir($upload_dir)) {
        if (!mkdir($upload_dir, 0755, true)) {
            throw new Exception('Failed to create upload directory');
        }
    }

    // Generate unique filename
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = 'avatar_' . $user_id . '_' . time() . '.' . $extension;
    $filepath = $upload_dir . $filename;

    // Move uploaded file
    if (!move_uploaded_file($file['tmp_name'], $filepath)) {
        throw new Exception('Failed to save file');
    }

    // Database connection
    $host = 'localhost';
    $db = 'zemaraim_interior';
    $db_user = 'zemaraim';
    $db_password = '8wwxk]-X3Kx]CJ]5';

    $connection = new mysqli($host, $db_user, $db_password, $db);
    
    if ($connection->connect_error) {
        unlink($filepath);
        throw new Exception('Database connection failed');
    }

    // Update user avatar in database
    $stmt = $connection->prepare("UPDATE users SET avatar = ? WHERE id = ?");
    if (!$stmt) {
        unlink($filepath);
        throw new Exception('Database statement failed');
    }

    $stmt->bind_param("si", $filename, $user_id);
    
    if (!$stmt->execute()) {
        unlink($filepath);
        throw new Exception('Failed to update database');
    }

    $stmt->close();
    $connection->close();

    // Return success with avatar URL
    $avatar_url = 'uploads/avatars/' . $filename;
    
    $response['success'] = true;
    $response['message'] = 'Profile photo updated successfully';
    $response['avatarUrl'] = $avatar_url;

} catch (Exception $e) {
    $response['success'] = false;
    $response['message'] = $e->getMessage();
}

echo json_encode($response);
?>
