<?php
// app/controllers/article-generator/postCreation/image-handler.php

if (!defined('ABSPATH')) {
  exit;
}

/**
 * This file depends on WordPress core functionality.
 * The following functions and constants are defined by WordPress and will be available at runtime:
 * Constants:
 * - ABSPATH: Base path to WordPress installation
 * 
 * Functions:
 * - download_url: Download a file to a temporary location
 * - is_wp_error: Check if a variable is a WordPress error
 * - wp_delete_file: Delete a file (WordPress alternative to unlink)
 * - media_handle_sideload: Handle file upload from URL
 * - update_post_meta: Update post metadata
 * - wp_update_post: Update a post in the database
 * 
 * These functions are included from WordPress core files which are loaded in this file
 * or are available globally in the WordPress environment.
 */

/**
 * Downloads an image and attaches it to the WordPress media library.
 *
 * @param string $image_url URL of the image.
 * @param string $post_title Title for the attachment (alt text, etc.).
 * @param int $user_id User ID for the attachment.
 * @return int|false Attachment ID or false on failure.
 */
function content_craft_ai_download_and_attach_image($image_url, $post_title, $user_id)
{
  // Need to require these files for media handling, but only if not already defined
  if (!function_exists('media_handle_sideload')) {
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';
  }

  // Download file to temp location
  $tmp = download_url($image_url);
  if (is_wp_error($tmp)) {
    // Use WordPress function for file deletion
    if (file_exists($tmp)) {
      wp_delete_file($tmp);
    }
    // error_log("Content Craft AI: Image Handler - Image download failed for {$image_url}: " . $tmp->get_error_message());
    return false;
  }

  $file_array = [];
  // Try to get a proper file name with extension
  preg_match('/[^\\/]+\.(jpe?g|png|gif|webp|avif|heic|heif|tiff?|bmp|svg)/i', $image_url, $matches);
  $file_name = basename($matches[0] ?? 'image.jpg'); // Default to image.jpg if regex fails

  $file_array['name'] = $file_name;
  $file_array['tmp_name'] = $tmp;

  // Upload image to media library
  $attachment_id = media_handle_sideload($file_array, 0, $post_title); // 0 for post_id means not attached to any specific post yet

  if (is_wp_error($attachment_id)) {
    // Use WordPress function for file deletion
    if (file_exists($file_array['tmp_name'])) {
      wp_delete_file($file_array['tmp_name']);
    }
    // error_log("Content Craft AI: Image Handler - Image sideload failed for {$file_name}: " . $attachment_id->get_error_message());
    return false;
  }

  // Update alt text and title for the attachment
  update_post_meta($attachment_id, '_wp_attachment_image_alt', $post_title);
  wp_update_post(['ID' => $attachment_id, 'post_title' => $post_title]);
  // It's good practice to also set the post_author for the attachment if user_id is available
  if ($user_id) {
    wp_update_post(['ID' => $attachment_id, 'post_author' => $user_id]);
  }

  // error_log("Content Craft AI: Image Handler - Successfully attached image ID {$attachment_id} for URL: {$image_url}");
  return $attachment_id;
}
