<?php
/**
 * Optional, privacy-first retention worker. It never deletes financial or
 * appointment timing records; it removes customer identifiers and reference
 * photos only after the business-selected retention period.
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class YATOON_Data_Retention {
    const HOOK = 'yatoon_apply_data_retention';

    public static function init() {
        add_action( self::HOOK, array( __CLASS__, 'run' ) );
        if ( ! wp_next_scheduled( self::HOOK ) ) {
            wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', self::HOOK );
        }
    }

    /** Retention is opt-in: a new install keeps its existing behavior. */
    public static function run() {
        if ( '1' !== (string) get_option( 'yatoon_retention_enabled', '0' ) ) { return; }
        global $wpdb;
        $months = max( 3, min( 120, absint( get_option( 'yatoon_retention_months', 24 ) ) ) );
        $cutoff = gmdate( 'Y-m-d H:i:s', strtotime( '-' . $months . ' months' ) );
        $table = $wpdb->prefix . 'yatoon_bookings';
        // Work in small batches. Future and active appointments are never touched.
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT id, design_attachment_id FROM {$table}
             WHERE end_time < %s AND status IN ('completed','cancelled','canceled','no_show')
               AND customer_email <> '' ORDER BY id ASC LIMIT 100", $cutoff )
        );
        foreach ( (array) $rows as $row ) {
            if ( ! empty( $row->design_attachment_id ) ) { wp_delete_attachment( absint( $row->design_attachment_id ), true ); }
            $wpdb->update( $table, array(
                'customer_name' => __( 'Removed customer', 'yatoon-booking-system' ), 'customer_email' => '', 'customer_phone' => '', 'notes' => '',
                'design_attachment_id' => null, 'design_image_url' => null, 'design_upload_token' => null,
            ), array( 'id' => absint( $row->id ) ), array( '%s','%s','%s','%s','%d','%s','%s' ), array( '%d' ) );
        }
        update_option( 'yatoon_retention_last_run', current_time( 'mysql', true ), false );
    }
}
