<?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 trackOtpEmailEvent($status, $message, array $context = [])
{
    $email  = $context['email'] ?? '';
    $mobile = $context['mobile'] ?? '';
    $leadId = $context['lead_id'] ?? null;
    $name   = $context['name'] ?? 'Subscriber';
    $otp    = $context['otp'] ?? '';

    return EmailTrackingApiClient::log([
        'module'             => 'otp',
        'submodule'          => 'send_otp',
        'module_key'         => 'otp',
        'submodule_key'      => 'send_otp',

        'lead_id'            => $leadId,
        'team_id'            => $context['team_id'] ?? null,
        'user_id'            => $context['user_id'] ?? null,

        'recipient_email'    => $email,
        'recipient_name'     => $name,
        'recipient_mobile'   => $mobile,

        'subject'            => 'Your OTP Code',
        'status'             => $status,
        'message'            => $message,
        'error_message'      => ($status === 'failed' || $status === 'error') ? $message : null,

        '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',

        'source_type'        => 'legacy_wpl_email_api',
        'source_key'         => 'sendOtp.php',
        'direct_email_url'   => 'https://wplspeedqueen.com/email_api/sendOtp.php',
        'calling_page_url'   => $context['calling_page_url'] ?? ($_SERVER['HTTP_REFERER'] ?? null),
        'parent_domain'      => 'wplspeedqueen.com',
        'parent_project'     => 'WPL Speed Queen Email API',
        'parent_page_name'   => 'sendOtp.php',
        'parent_page_url'    => 'https://wplspeedqueen.com/email_api/sendOtp.php',
        'server_file_path'   => __FILE__,

        'payload_json'       => [
            'name'       => $name,
            'email'      => $email,
            'mobile'     => $mobile,
            'lead_id'    => $leadId,
            'otp'        => $otp, // masked inside EmailTrackingApiClient
            'source_ip'  => $_SERVER['REMOTE_ADDR'] ?? null,
        ],
        'response_json'      => $context['response_json'] ?? null,
    ]);
}

// ✅ 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,
    'calling_page_url' => $data['calling_page_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);
}
