<?php

// ✅ ERROR REPORTING (REMOVE DISPLAY IN PRODUCTION)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Content-Type: application/json");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/autoload.php';
require_once __DIR__ . '/EmailTrackingApiClient.php';

/**
 * Track OTP email event through ProCorporateLeague V15 API.
 * DB insert happens on PCL server only.
 */
function pclCurrentRequestUrl()
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? '';
    $uri    = $_SERVER['REQUEST_URI'] ?? ($_SERVER['SCRIPT_NAME'] ?? '');
    return trim($host . $uri) !== '' ? ($scheme . '://' . $host . $uri) : '';
}

function pclPublicScriptUrl()
{
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? '';
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    return trim($host . $script) !== '' ? ($scheme . '://' . $host . $script) : '';
}

/**
 * Track OTP email event through ProCorporateLeague V15 API.
 *
 * IMPORTANT:
 * - Do NOT hardcode module_key/submodule_key here.
 * - Do NOT hardcode parent_project/parent_page_name here.
 * - Controller should resolve module/submodule/business mapping from DB using:
 *   active_file_name, server_full_path, current_email_url, calling_file_url.
 */
function trackOtpEmailEvent($status, $message, array $context = [])
{
    $email  = $context['email'] ?? '';
    $mobile = $context['mobile'] ?? '';
    $leadId = $context['lead_id'] ?? null;
    $name   = $context['name'] ?? 'Subscriber';
    $otp    = $context['otp'] ?? '';

    $currentEmailUrl = pclCurrentRequestUrl();        // actual called URL: sendOtp.php endpoint
    $directEmailUrl  = pclPublicScriptUrl();          // public URL of this email API file
    $callingFileUrl  = $context['calling_file_url']
        ?? $context['calling_page_url']
        ?? $context['parent_page_url']
        ?? $context['source_url']
        ?? ($_SERVER['HTTP_REFERER'] ?? null);        // source/admin/client page if available

    $fullEmailHtml = $context['full_email_html'] ?? '';
    $fullEmailText = $context['full_email_text'] ?? (
        !empty($fullEmailHtml)
            ? trim(preg_replace('/\s+/', ' ', strip_tags($fullEmailHtml)))
            : ''
    );

    $responseJson = $context['response_json'] ?? null;

    $basePayload = [
        // Technical mapping keys only. Controller resolves business mapping from DB.
        'active_file_name'     => basename(__FILE__),
        'email_file'           => basename(__FILE__),
        'template_file'        => basename(__FILE__),

        // Entity and recipient info
        'lead_id'              => $leadId,
        'team_id'              => $context['team_id'] ?? null,
        'user_id'              => $context['user_id'] ?? null,

        'recipient_email'      => $email,
        'recipient_name'       => $name,
        'recipient_mobile'     => $mobile,
        'email'                => $email,
        'mobile'               => $mobile,
        'otp'                  => $otp,
        'otp_purpose'          => $context['otp_purpose'] ?? 'send_otp',

        // Email content
        'subject'              => $context['subject'] ?? 'Your OTP Code',
        'preheader'            => $context['preheader'] ?? '',
        'full_email_html'      => $fullEmailHtml,
        'full_email_text'      => $fullEmailText,
        'html_length'          => !empty($fullEmailHtml) ? strlen($fullEmailHtml) : 0,

        // OTP emails usually have no attachments
        'attachment_urls'      => '',
        'attachments_json'     => json_encode([], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        'attachment_count'     => 0,

        // URL/file audit fields
        'current_email_url'    => $currentEmailUrl,
        'direct_email_url'     => $directEmailUrl,
        'calling_file_url'     => $callingFileUrl,
        'public_calling_url'   => $currentEmailUrl,
        'calling_page_url'     => $callingFileUrl,
        'parent_page_url'      => $callingFileUrl,
        'source_url'           => $callingFileUrl,
        'server_full_path'     => __FILE__,
        'server_file_path'     => __FILE__,
        'request_uri'          => $_SERVER['REQUEST_URI'] ?? '',
        'script_name'          => $_SERVER['SCRIPT_NAME'] ?? basename(__FILE__),

        // Status/audit fields
        'status'               => $status,
        'delivery_status'      => $status,
        'message'              => $message,
        'error_message'        => ($status === 'failed' || $status === 'error') ? $message : null,
        'provider_message_id'  => $context['provider_message_id'] ?? null,

        // Generic journey hints only, not module mapping
        'send_type'            => 'otp',
        'journey_type'         => 'otp_verification',
        'journey_stage'        => $status === 'sent' ? 'otp_sent' : 'otp_failed',
        'customer_key'         => $mobile ?: $email,
        'customer_type'        => $context['customer_type'] ?? 'unknown',

        // Full request/response audit
        'request_payload_json' => json_encode([
            'name'      => $name,
            'email'     => $email,
            'mobile'    => $mobile,
            'lead_id'   => $leadId,
            'team_id'   => $context['team_id'] ?? null,
            'user_id'   => $context['user_id'] ?? null,
            'otp_masked'=> $otp !== '' ? '******' : '',
            'source_ip' => $_SERVER['REMOTE_ADDR'] ?? null,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        'payload_json'         => json_encode([
            'name'      => $name,
            'email'     => $email,
            'mobile'    => $mobile,
            'lead_id'   => $leadId,
            'team_id'   => $context['team_id'] ?? null,
            'user_id'   => $context['user_id'] ?? null,
            'otp_masked'=> $otp !== '' ? '******' : '',
            'source_ip' => $_SERVER['REMOTE_ADDR'] ?? null,
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        'response_json'        => is_array($responseJson)
            ? json_encode($responseJson, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)
            : $responseJson,
    ];

    /*
     * Track both:
     * 1) OTP analytics table via /email/track/otp
     * 2) Email send log audit via /email/track/legacy-call
     *
     * The controller will resolve module/submodule dynamically from DB using active_file_name=sendOtp.php.
     */
    $otpTracking    = EmailTrackingApiClient::trackOtp($basePayload);
    $legacyTracking = EmailTrackingApiClient::trackLegacy($basePayload);

    return [
        'tracking_status' => (
            ($otpTracking['tracking_status'] ?? '') === 'success'
            || ($legacyTracking['tracking_status'] ?? '') === 'success'
        ) ? 'success' : 'failed',
        'otp_endpoint'    => $otpTracking,
        'legacy_endpoint' => $legacyTracking,
    ];
}

// ✅ GET JSON INPUT
$rawInput = file_get_contents("php://input");
$data = json_decode($rawInput, true);
if (!is_array($data)) {
    $data = [];
}

$name    = trim($data['name'] ?? 'Subscriber');
$email   = trim($data['email'] ?? '');
$mobile  = trim($data['mobile'] ?? ($data['phone'] ?? ''));
$otp     = trim($data['otp'] ?? '');
$lead_id = $data['lead_id'] ?? ($data['leadId'] ?? null);
$team_id = $data['team_id'] ?? null;
$user_id = $data['user_id'] ?? null;

$trackingContext = [
    'name'      => $name,
    'email'     => $email,
    'mobile'    => $mobile,
    'otp'       => $otp,
    'lead_id'   => $lead_id,
    'team_id'   => $team_id,
    'user_id'   => $user_id,

    // Optional source page URL sent by frontend/admin page.
    // If not sent, tracking will fallback to HTTP_REFERER.
    'calling_file_url' => $data['calling_file_url']
        ?? $data['calling_page_url']
        ?? $data['parent_page_url']
        ?? $data['source_url']
        ?? null,
    'calling_page_url' => $data['calling_page_url']
        ?? $data['calling_file_url']
        ?? $data['parent_page_url']
        ?? $data['source_url']
        ?? null,
];

// ✅ VALIDATION
if (empty($email) || empty($otp)) {
    $response = [
        "status_code" => 400,
        "status" => "failed",
        "message" => "Email and OTP are required"
    ];

    trackOtpEmailEvent('failed', $response['message'], array_merge($trackingContext, [
        'response_json' => $response,
    ]));

    echo json_encode($response);
    exit;
}

if (strlen($otp) != 6 || !is_numeric($otp)) {
    $response = [
        "status_code" => 400,
        "status" => "failed",
        "message" => "OTP must be 6 digit numeric"
    ];

    trackOtpEmailEvent('failed', $response['message'], array_merge($trackingContext, [
        'response_json' => $response,
    ]));

    echo json_encode($response);
    exit;
}

/* ===============================
   🎯 OTP CONTENT TEMPLATE
================================ */
function sendOtpContent($name, $otp) {
    $safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
    $safeOtp  = htmlspecialchars($otp, ENT_QUOTES, 'UTF-8');

    return "
    <h2 style='margin-top:0;'>Hi {$safeName},</h2>

    <p>Your One Time Password (OTP) is:</p>

    <h1 style='text-align:center;color:#6b4db6;margin:20px 0;'>{$safeOtp}</h1>

    <p>This OTP is valid for 5 minutes.</p>
    ";
}

/* ===============================
   🎨 COMMON EMAIL TEMPLATE
================================ */
function getCommonTemplate($content){
    return "
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Email</title>
</head>

<body style='margin:0;padding:0;background:#f4f6f8;font-family:Arial,Helvetica,sans-serif;'>

<table width='100%' cellpadding='0' cellspacing='0' style='background:#f4f6f8;padding:30px 0;'>

<tr>
<td align='center'>

<table width='600' cellpadding='0' cellspacing='0'
style='background:#ffffff;border-radius:8px;overflow:hidden;'>

<tr>
<td align='center' style='padding:30px;background:#6b4db6;color:#ffffff;'>

<img src='https://procorporateleague.com/Imp_PCL_Logo_Black.png'
style='max-width:170px;width:100%;height:auto;display:block;margin:auto;'>

<h1 style='margin:0;font-size:26px;'>Pro Corporate League</h1>

<p style='margin:8px 0 0;font-size:14px;'>
The biggest corporate cricket league worldwide
</p>

</td>
</tr>

<tr>
<td style='padding:30px 25px;color:#333;'>

{$content}

</td>
</tr>

<tr>
<td align='center' style='padding:15px;font-size:12px;color:#888;'>

© ".date("Y")." Pro Corporate League

</td>
</tr>

</table>

</td>
</tr>

</table>

</body>
</html>
";
}

/* ===============================
   📧 SEND MAIL
================================ */

$mail = new PHPMailer(true);

try {

    // 🔧 SMTP SETTINGS
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'sachin.gupta@procorporateleague.com';
    $mail->Password   = 'mwhqomapdbzzvjeb'; // ⚠️ Move this to server config/env in production
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;

    // 📤 SENDER & RECEIVER
    $mail->setFrom('sachin.gupta@procorporateleague.com', 'Pro Corporate League');
    $mail->addAddress($email, $name);

    // 📄 EMAIL SETTINGS
    $mail->isHTML(true);
    $mail->Subject = "Your OTP Code";

    // ✅ FINAL TEMPLATE FLOW
    $content = sendOtpContent($name, $otp);
    $finalHtml = getCommonTemplate($content);
    $mail->Body = $finalHtml;

    // 🚀 SEND
    $mail->send();

    $response = [
        "status_code" => 200,
        "status" => "success",
        "message" => "OTP sent to your email address",
        "otp" => $otp // ⚠️ Keep only if your existing frontend depends on it. Remove later in production.
    ];

    $trackingResult = trackOtpEmailEvent('sent', $response['message'], array_merge($trackingContext, [
        'response_json' => $response,
        'full_email_html' => $finalHtml,
    ]));

    if (isset($data['debug_tracking']) && (int)$data['debug_tracking'] === 1) {
        $response['tracking'] = $trackingResult;
    }

    echo json_encode($response);

} catch (Exception $e) {

    $response = [
        "status_code" => 500,
        "status" => "error",
        "message" => $mail->ErrorInfo
    ];

    trackOtpEmailEvent('failed', $response['message'], array_merge($trackingContext, [
        'response_json' => $response,
    ]));

    echo json_encode($response);
}
