<?php

//includes/actions-email.php

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

function asana_automator_email_on_section_entry($config, $token, $task) {
    $log_file = WP_CONTENT_DIR . '/custom-debug.log';

    // 🚨 TEST ENTRY: Confirm the handler is being called
    file_put_contents($log_file, "🚨 TEST ENTRY: Handler was called\n", FILE_APPEND);

    // 🚨 RAW TASK DUMP: Log the entire incoming task
    file_put_contents($log_file, "🚨 RAW TASK: " . print_r($task, true) . "\n", FILE_APPEND);

    $email_gid        = trim($config['email_field_gid'] ?? '');
    $first_gid        = trim($config['first_name'] ?? '');
    $last_gid         = trim($config['last_name'] ?? '');
    $marker_label     = trim($config['marker_label'] ?? '');
    $project_gid      = trim($config['project_gid'] ?? '');
    $completion_state = trim($config['completion_state'] ?? 'any');
    $task_gid         = $task['gid'] ?? '';

    if (!$email_gid || !$task_gid || !$marker_label) {
        file_put_contents($log_file, "⚠️ Missing required config values — skipping\n", FILE_APPEND);
        return;
    }

    $is_completed = $task['completed'] ?? false;
    if ($completion_state === 'complete' && !$is_completed) return;
    if ($completion_state === 'incomplete' && $is_completed) return;

    // Check if marker comment already exists
    $stories_response = wp_remote_get("https://app.asana.com/api/1.0/tasks/{$task_gid}/stories", [
        'headers' => ['Authorization' => 'Bearer ' . $token],
    ]);

    if (is_wp_error($stories_response)) {
        file_put_contents($log_file, "❌ Failed to fetch stories: " . $stories_response->get_error_message() . "\n", FILE_APPEND);
        return;
    }

    $stories_data = json_decode(wp_remote_retrieve_body($stories_response), true);
    if (!empty($stories_data['data'])) {
        foreach ($stories_data['data'] as $story) {
            if (strpos($story['text'], "EMAIL SENT: {$marker_label}") !== false) {
                file_put_contents($log_file, "⏭ Marker already found for {$marker_label}, skipping task {$task_gid}.\n", FILE_APPEND);
                return;
            }
        }
    }

    // Extract email and name
    $email = '';
    $first = '';
    $last  = '';

    file_put_contents($log_file, "🔍 Configured email_field_gid: {$email_gid}, first_name_gid: {$first_gid}, last_name_gid: {$last_gid}\n", FILE_APPEND);

    foreach ($task['custom_fields'] ?? [] as $field) {
        file_put_contents($log_file, "🔍 Field dump: " . print_r($field, true) . "\n", FILE_APPEND);
        if ($field['gid'] === $email_gid) $email = $field['text_value'] ?? '';
        if ($field['gid'] === $first_gid) $first = $field['text_value'] ?? '';
        if ($field['gid'] === $last_gid)  $last  = $field['text_value'] ?? '';
    }

    file_put_contents($log_file, "🔍 Extracted email: '{$email}', first: '{$first}', last: '{$last}'\n", FILE_APPEND);

    if ($email && is_email($email)) {
        $fullName = trim("$first $last");

        $section_names_list = [];
        foreach ($task['memberships'] ?? [] as $m) {
            if (!empty($m['project']['gid']) && $m['project']['gid'] === $project_gid) {
                if (!empty($m['section']['name'])) {
                    $section_names_list[] = $m['section']['name'];
                }
            }
        }
        $section_names = implode(', ', $section_names_list);

        $assignee_name = $task['assignee']['name'] ?? '(unassigned)';
        $due_date      = $task['due_on'] ?? '(no due date)';
        $created_at    = $task['created_at'] ?? '';
        $modified_at   = $task['modified_at'] ?? '';
        $project_name  = $task['projects'][0]['name'] ?? '(unknown project)';

        $subject_template = $config['email_subject_template'] ?? "🛎️ Update: {task_name}";
        $body_template    = $config['email_body_template'] ?? "Hi {full_name},\n\nTask {task_name} has been updated.\n\n{task_link}";

        $replacements = [
            '{task_name}'      => $task['name'],
            '{task_link}'      => "https://app.asana.com/0/{$task_gid}",
            '{full_name}'      => $fullName ?: 'there',
            '{assignee_name}'  => $assignee_name,
            '{due_date}'       => $due_date,
            '{created_at}'     => $created_at,
            '{modified_at}'    => $modified_at,
            '{project_name}'   => $project_name,
            '{section_names}'  => $section_names,
        ];

        $subject = str_replace(array_keys($replacements), array_values($replacements), $subject_template);
        $body    = str_replace(array_keys($replacements), array_values($replacements), $body_template);

        // Render a styled HTML email using the existing submission template
        $task_name      = $task['name'] ?? '';
        $request_number = $task['gid'] ?? '';
        $comms_link     = "https://app.asana.com/0/{$task_gid}";
        $fields_html    = '';

        // Prepare the template variables expected by submission-template.php
        $subject_tpl = (string) $subject;
        if (function_exists('wp_kses_post')) {
            $body_tpl = wp_kses_post(nl2br(esc_html((string)$body)));
        } else {
            $body_tpl = nl2br(htmlspecialchars((string)$body, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'));
        }

        ob_start();
        @include plugin_dir_path(__FILE__) . '../../../admin/emails/submission-template.php';
        $html_body = ob_get_clean();

        $headers = function_exists('afb_get_email_headers') ? afb_get_email_headers() : ['Content-Type: text/html; charset=UTF-8'];
        $mail_result = wp_mail($email, sanitize_text_field((string)$subject), $html_body, $headers);

        $marker_text = $mail_result
            ? "EMAIL SENT: {$marker_label}"
            : "Email failed for marker: {$marker_label}";

        file_put_contents($log_file, "📧 Email to {$email}: " . ($mail_result ? 'SUCCESS' : 'FAIL') . "\n", FILE_APPEND);

        $response = wp_remote_post("https://app.asana.com/api/1.0/tasks/{$task_gid}/stories", [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
                'Content-Type'  => 'application/json',
                'Asana-Disable' => 'notifications',
            ],
            'body' => json_encode(['data' => ['text' => $marker_text]]),
        ]);

        if (is_wp_error($response)) {
            file_put_contents($log_file, "❌ Failed to post marker for task {$task_gid}: " . $response->get_error_message() . "\n", FILE_APPEND);
        } else {
            $code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            file_put_contents($log_file, "✅ Marker post response for task {$task_gid}: HTTP {$code} - {$body}\n", FILE_APPEND);
        }

    } else {
        file_put_contents($log_file, "🚫 Skipping task {$task_gid}, invalid or missing email.\n", FILE_APPEND);

        $response = wp_remote_post("https://app.asana.com/api/1.0/tasks/{$task_gid}/stories", [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
                'Content-Type'  => 'application/json',
                'Asana-Disable' => 'notifications',
            ],
            'body' => json_encode(['data' => ['text' => "🚫 Invalid or missing email. Skipping."]]),
        ]);

        if (is_wp_error($response)) {
            file_put_contents($log_file, "❌ Failed to post invalid-email marker for task {$task_gid}: " . $response->get_error_message() . "\n", FILE_APPEND);
        } else {
            $code = wp_remote_retrieve_response_code($response);
            $body = wp_remote_retrieve_body($response);
            file_put_contents($log_file, "✅ Invalid-email marker post response for task {$task_gid}: HTTP {$code} - {$body}\n", FILE_APPEND);
        }
    }
}
