<?php
/**
 * MTC - Bait Service
 * Generation and download of bait ZIP files.
 *
 * @package My Trail Camera
 * @since 8.2.0
 */

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

class Mtcam_Bait_Service {

    /**
     * Handle bait ZIP download — called from admin_init (before HTML output)
     */
    public function handle_download() {
        if (!isset($_POST['action']) || $_POST['action'] !== 'generate_bait' || !isset($_POST['cam_id'])) {
            return;
        }
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'my-trail-camera'), '', 403);
        }

        $cam_id = strtoupper(sanitize_text_field(wp_unslash($_POST['cam_id'])));
        check_admin_referer('mtcam_generate_bait_' . $cam_id);

        $cameras_data = mtcam_get_cameras();
        if (!isset($cameras_data[$cam_id])) {
            wp_die(esc_html__('Camera not found.', 'my-trail-camera'), '', 404);
        }

        $cam = $cameras_data[$cam_id];
        $cam_name = $cam['name'] ?? $cam_id;
        $zip_path = $this->generate_zip($cam_id, $cam_name, $cam);

        // Track bait generation date on the camera record
        $cameras_data[$cam_id]['bait_generated'] = wp_date('Y-m-d');
        mtcam_save_camera($cam_id, $cameras_data[$cam_id]);

        if (!$zip_path || !file_exists($zip_path)) {
            wp_safe_redirect(admin_url('admin.php?page=mtcam-dashboard&bait_error=1'));
            exit;
        }

        // Stream ZIP directly to browser and delete temp file
        global $wp_filesystem;
        require_once ABSPATH . 'wp-admin/includes/file.php';
        WP_Filesystem();

        $download_name = 'mtcam-bait-' . sanitize_file_name( $cam_id ) . '.zip';
        $contents      = $wp_filesystem->get_contents( $zip_path );

        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="' . $download_name . '"');
        header('Content-Length: ' . strlen( $contents ));
        header('Cache-Control: no-cache, must-revalidate');

        echo $contents; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary ZIP data
        wp_delete_file($zip_path);
        exit;
    }

    /**
     * Generate bait ZIP for existing camera using the bait-builder.
     *
     * @param string $cam_id      Camera device ID.
     * @param string $cam_name    Human-readable name.
     * @param array  $cam         Full camera data array.
     * @return string|false Path to ZIP or false on failure.
     */
    public function generate_zip($cam_id, $cam_name, $cam = array()) {
        $track_url = esc_url_raw( rest_url( 'mtcam/v1/log' ) );
        $extra_url = '';

        // Load camera profile for realistic bait content.
        $profile = array();
        $profile_id = $cam['profile'] ?? 'custom';
        if ( $profile_id !== 'custom' && function_exists( 'mtcam_get_camera_profile' ) ) {
            $profile = mtcam_get_camera_profile( $profile_id );
        }

        $zip_path = mtcam_bait_build_zip( $cam_id, $cam_name, $track_url, $extra_url, $profile );

        // Save generated file tokens to DB for API verification.
        $tokens = mtcam_bait_get_generated_tokens();
        if ( ! empty( $tokens ) ) {
            mtcam_save_file_tokens( $cam_id, $tokens );
        }

        return $zip_path;
    }
}
