<?php
/*
Plugin Name: Craigslist Importer
Plugin URI: https://example.com/craigslist-importer
Description: A plugin to import posts from Craigslist
Version: 1.0
Author: Your Name
Author URI: https://example.com
*/


if (isset($_GET['activate'])) {
  wp_schedule_event(time(), 'daily', 'craigslist_importer_run');
}


function craigslist_importer_post_type() {
  register_post_type('craigslist_post', [
    'labels' => [
      'name' => 'Craigslist Posts',
      'singular_name' => 'Craigslist Post',
    ],
    'public' => true,
    'has_archive' => true,
    'supports' => ['title', 'editor', 'thumbnail'],
  ]);
}
add_action('init', 'craigslist_importer_post_type');


function craigslist_importer_run() {
  $url = 'https://auburn.craigslist.org/search/bbb#search=1~thumb~0~100';
  $content = file_get_contents($url);

  $dom = new DOMDocument();
  @$dom->loadHTML($content);

  $xpath = new DOMXPath($dom);
  $listings = $xpath->query('//li[contains(@class, "result-row")]');

  $posts = [];

  foreach ($listings as $listing) {
    $title = $xpath->query('.//a[contains(@class, "result-title")]', $listing)->item(0)->nodeValue;
    $description = $xpath->query('.//p[contains(@class, "result-info")]', $listing)->item(0)->nodeValue;
    $image = $xpath->query('.//a[contains(@class, "thumb")]/img', $listing)->item(0)->getAttribute('src');

    $posts[] = [
      'title' => $title,
      'description' => $description,
      'image' => $image,
    ];
  }

  foreach ($posts as $post) {
    $post_data = [
      'post_title' => $post['title'],
      'post_content' => $post['description'],
      'post_status' => 'publish',
      'post_type' => 'craigslist_post',
    ];

    $post_id = wp_insert_post($post_data);

    if (!empty($post['image'])) {
      $image_url = $post['image'];
      $image_data = file_get_contents($image_url);
      $wp_filetype = wp_check_filetype($image_url);

      $wp_upload_dir = wp_upload_dir();
      $image_path = $wp_upload_dir['path'] . '/' . basename($image_url);
      $image_file = fopen($image_path, 'wb');
      fwrite($image_file, $image_data);
      fclose($image_file);

      $attachment_data = [
        'guid' => $wp_upload_dir['url'] . '/' . basename($image_url),
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => basename($image_url),
        'post_content' => '',
        'post_status' => 'inherit',
      ];

      $attachment_id = wp_insert_attachment($attachment_data, $image_path);
      $attachment_data = wp_generate_attachment_metadata($attachment_id, $image_path);
      wp_update_attachment_metadata($attachment_id, $attachment_data);

      set_post_thumbnail($post_id, $attachment_id);
    }
  }
}


add_action('craigslist_importer_run', 'craigslist_importer_run');
if (!wp_next_scheduled('craigslist_importer_run')) {
  wp_schedule_event(time(), 'daily', 'craigslist_importer_run');
}