<?php
/*
 * CWC Event Showcase email endpoint.
 * Preview: teamAxaXLCombinedEmail.php?preview=1&team_id=33&team=HCL
 * Preview mode renders only; it never calls SES.
 */
function cwcShowcaseJson($url)
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 12,
        CURLOPT_CONNECTTIMEOUT => 5,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_HTTPHEADER => ['Accept: application/json'],
    ]);
    $raw = curl_exec($ch);
    // curl_close() is deprecated on PHP 8.5 and has no effect on PHP 8+.
    unset($ch);
    $decoded = json_decode((string)$raw, true);
    return is_array($decoded) ? $decoded : [];
}

$isPreview = isset($_GET['preview']) && $_GET['preview'] === '1';
if (!$isPreview) {
    header('Content-Type: application/json; charset=UTF-8');
    if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
        http_response_code(405);
        echo json_encode(['status_code' => 405, 'message' => 'POST required']);
        exit;
    }
    $isMultipart = stripos((string)($_SERVER['CONTENT_TYPE'] ?? ''), 'multipart/form-data') !== false;
    $request = $isMultipart ? $_POST : json_decode(file_get_contents('php://input'), true);
    if (!is_array($request)) $request = [];
    if ($isMultipart && !$request && (int)($_SERVER['CONTENT_LENGTH'] ?? 0) > 0) {
        http_response_code(413);
        echo json_encode(['status_code' => 413, 'message' => 'PDF upload was rejected by the email server. Increase its upload limit.']);
        exit;
    }
    $teamId = trim((string)($request['team_id'] ?? ''));
    $toEmail = trim((string)($request['email'] ?? $request['to_email'] ?? ''));
    if ($teamId === '' || !ctype_digit($teamId) || !filter_var($toEmail, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo json_encode(['status_code' => 400, 'message' => 'Valid team_id and recipient email are required']);
        exit;
    }
    $upload = $_FILES['team_pdf'] ?? null;
    if (!$isMultipart || !is_array($upload) || (int)($upload['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
        http_response_code(400);
        echo json_encode(['status_code' => 400, 'message' => 'This team’s PDF is required. Select it before sending.']);
        exit;
    }
    $teamPdfPath = (string)($upload['tmp_name'] ?? '');
    $teamPdfSize = (int)($upload['size'] ?? 0);
    $teamPdfName = (string)($upload['name'] ?? '');
    if ($teamPdfSize < 5 || $teamPdfSize > 15 * 1024 * 1024
        || !preg_match('/\.pdf$/i', $teamPdfName)
        || !is_uploaded_file($teamPdfPath)
        || file_get_contents($teamPdfPath, false, null, 0, 5) !== '%PDF-') {
        http_response_code(400);
        echo json_encode(['status_code' => 400, 'message' => 'Team PDF must be a valid PDF of 15 MB or less.']);
        exit;
    }
    $teamPdfName = preg_replace('/[^A-Za-z0-9._ -]/', '_', basename($teamPdfName));
} else {
    header('Content-Type: text/html; charset=UTF-8');
    $request = [];
    $teamId = trim((string)($_GET['team_id'] ?? '33'));
    if (!ctype_digit($teamId)) $teamId = '33';
}

$profile = [];
$profileRows = [];
$teamRecord = [];
$cityName = '';
$sectorName = '';
$profileJson = cwcShowcaseJson('https://procorporateleague.com/pcl_rest/api/v12/teams/' . rawurlencode($teamId) . '/ai-profile');
$profileRows = is_array($profileJson['data'] ?? null) ? $profileJson['data'] : [];
$profile = $profileRows[0] ?? [];
if (!$isPreview) {
    $mapJson = cwcShowcaseJson('https://www.procorporateleague.com/pcl_rest/api/v9/old-team-map-data/getAll');
    foreach (($mapJson['results'] ?? []) as $row) {
        if ((string)($row['team_id'] ?? '') === $teamId) { $teamRecord = $row; break; }
    }
    $citiesJson = cwcShowcaseJson('https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllCities');
    foreach (($citiesJson['results'] ?? []) as $row) {
        if ((string)($row['id'] ?? '') === (string)($teamRecord['city'] ?? '')) { $cityName = (string)($row['city_name'] ?? ''); break; }
    }
    $sectorsJson = cwcShowcaseJson('https://www.procorporateleague.com/pcl_rest/api/v9/corporate/getAllSectors');
    foreach (($sectorsJson['results'] ?? []) as $row) {
        if ((string)($row['id'] ?? '') === (string)($teamRecord['sector'] ?? '')) { $sectorName = (string)($row['name'] ?? $row['sector_name'] ?? ''); break; }
    }
}

$teamName = trim((string)($isPreview
    ? ($profile['team_name'] ?? $_GET['team'] ?? 'HCL')
    : ($profile['team_name'] ?? $teamRecord['team_name'] ?? '')));
if (!$isPreview && $teamName === '') {
    http_response_code(422);
    echo json_encode(['status_code' => 422, 'message' => 'Team name could not be found for this team ID']);
    exit;
}
if ($teamName === '') $teamName = 'Your Team';
$cityName = trim((string)($isPreview
    ? ($_GET['city'] ?? 'Delhi NCR')
    : ($cityName !== '' ? $cityName : ($teamRecord['city_name'] ?? ''))));
$sectorName = trim((string)($isPreview
    ? ($_GET['sector'] ?? 'Information Technology')
    : ($sectorName !== '' ? $sectorName : ($teamRecord['sector_name'] ?? ''))));
// The legacy team map has incorrect classifications for these teams.
// Correct only the email copy; do not mutate the shared database records.
if ($teamId === '2009') $sectorName = 'Insurance';
if ($teamId === '33') {
    $cityName = 'Delhi NCR';
    $sectorName = 'Information Technology';
}
$safeTeam = htmlspecialchars($teamName, ENT_QUOTES, 'UTF-8');
$safeCity = htmlspecialchars($cityName !== '' ? $cityName : 'your city', ENT_QUOTES, 'UTF-8');
$safeSector = htmlspecialchars($sectorName !== '' ? $sectorName : 'your sector', ENT_QUOTES, 'UTF-8');
$teamLogoUrl = 'https://www.procorporateleague.com/wp-includes/images/team/' . rawurlencode($teamId) . '.png';
$dashboardUrl = 'https://www.procorporateleague.com/ai/corporate-cricket-team-ai-analysis/pcl-ai-corporate-team-profile.php?team_id=' . rawurlencode($teamId) . '&team_name=' . rawurlencode($teamName);
$imageBase = $isPreview
    ? (is_dir(__DIR__ . '/assets') ? 'assets/' : '../assets/')
    : 'https://wplspeedqueen.com/email_api/assets/';
$subject = 'Congratulations ' . $teamName . '! Shortlisted for Corporate World Cup™️ Founding 8';

try {
    ob_start();
    require __DIR__ . '/teamAxaXLCombinedTemplate.php';
    $html = ob_get_clean();
} catch (Throwable $error) {
    if (ob_get_level() > 0) ob_end_clean();
    http_response_code(500);
    if ($isPreview) {
        echo htmlspecialchars($error->getMessage(), ENT_QUOTES, 'UTF-8');
    } else {
        echo json_encode(['status_code' => 500, 'message' => $error->getMessage()]);
    }
    exit;
}

if ($isPreview) { echo $html; exit; }

$cc = ['sachin.gupta@corporateworldcup.com', 'info@corporateworldcup.com'];
$requestCc = $request['cc'] ?? [];
if (is_string($requestCc)) $requestCc = json_decode($requestCc, true);
if (!is_array($requestCc)) $requestCc = [];
foreach ($requestCc as $row) {
    $address = trim((string)($row['email'] ?? ''));
    if (filter_var($address, FILTER_VALIDATE_EMAIL)) $cc[] = $address;
}
foreach ([__DIR__ . '/cwc_emails.php', __DIR__ . '/../_api/cwc_emails.php'] as $mailerFile) {
    if (is_file($mailerFile)) { require_once $mailerFile; break; }
}
if (!class_exists('CwcEmailer')) {
    http_response_code(500);
    echo json_encode(['status_code' => 500, 'message' => 'SES mailer missing; upload cwc_emails.php beside this endpoint']);
    exit;
}
try {
    $attachmentFiles = [
        [$teamPdfName, $teamPdfPath],
    ];
    $attachments = [];
    $encodedSize = 0;
    foreach ($attachmentFiles as [$attachmentName, $attachmentPath]) {
        if (!is_readable($attachmentPath)) {
            throw new RuntimeException('Required PDF attachment is missing or unreadable: ' . $attachmentName);
        }
        $attachmentSize = filesize($attachmentPath);
        if ($attachmentSize === false || $attachmentSize <= 0 || $attachmentSize > 30000000) {
            throw new RuntimeException('Required PDF attachment is empty or too large: ' . $attachmentName);
        }
        $base64Bytes = 4 * (int)ceil($attachmentSize / 3);
        $encodedSize += $base64Bytes + 2 * (int)ceil($base64Bytes / 76);
        if ($encodedSize + strlen($html) + 1048576 > 40 * 1024 * 1024) {
            throw new RuntimeException('Team PDF attachment is too large for a single SES email');
        }
        $attachmentContent = file_get_contents($attachmentPath);
        if ($attachmentContent === false || strncmp($attachmentContent, '%PDF-', 5) !== 0) {
            throw new RuntimeException('Required PDF attachment is invalid: ' . $attachmentName);
        }
        $attachments[] = [
            'filename' => $attachmentName,
            'mime' => 'application/pdf',
            'content_base64' => base64_encode($attachmentContent),
        ];
        unset($attachmentContent);
    }
    $mailer = new CwcEmailer();
    if (!method_exists($mailer, 'sendCustomExactCc')) {
        throw new RuntimeException('Updated SES mailer is required for the Event Showcase CC list');
    }
    $result = $mailer->sendCustomExactCc([$toEmail], $cc, $subject, $html, trim(preg_replace('/\s+/', ' ', strip_tags($html))), $attachments);
    if (empty($result['success'])) throw new RuntimeException((string)($result['error'] ?? 'Email send failed'));
    echo json_encode(['status_code' => 200, 'status' => 'success', 'message' => 'CWC Event Showcase sent successfully']);
} catch (Throwable $error) {
    http_response_code(502);
    echo json_encode(['status_code' => 502, 'status' => 'error', 'message' => $error->getMessage()]);
}
