<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';

$response = ["success" => false, "message" => "Unknown error"];

$input = file_get_contents("php://input");
$data = json_decode($input, true);

if ($data === null) {
    $response["message"] = "JSON decode failed";
    $response["error"] = json_last_error_msg();
    echo json_encode($response);
    exit;
}

// === Utility function to remove content in parentheses ===
function removeParenthesesContent($text) {
    return trim(preg_replace('/\s*\([^)]*\)/', '', $text));
}

// === Group flat advice strings by condition ===
function groupAdviceByCondition($flatAdviceArray) {
    $grouped = [];
    foreach ($flatAdviceArray as $entry) {
        if (strpos($entry, ' - ') !== false) {
            [$condition, $advice] = explode(' - ', $entry, 2);
            $conditionClean = trim($condition);
            $adviceClean = trim($advice);
            if (!isset($grouped[$conditionClean])) {
                $grouped[$conditionClean] = [];
            }
            $grouped[$conditionClean][] = $adviceClean;
        }
    }
    $result = [];
    foreach ($grouped as $condition => $advices) {
        $result[] = [
            "condition" => $condition,
            "advice" => $advices
        ];
    }
    return $result;
}

// === Group flat impact strings by condition ===
function groupImpactByCondition($flatImpactArray) {
    $grouped = [];
    foreach ($flatImpactArray as $entry) {
        if (strpos($entry, ' - ') !== false) {
            [$condition, $impact] = explode(' - ', $entry, 2);
            $conditionClean = trim($condition);
            $impactClean = trim($impact);
            if (!isset($grouped[$conditionClean])) {
                $grouped[$conditionClean] = [];
            }
            $grouped[$conditionClean][] = $impactClean;
        }
    }
    $result = [];
    foreach ($grouped as $condition => $impacts) {
        $result[] = [
            "condition" => $condition,
            "impact" => $impacts
        ];
    }
    return $result;
}

// === Format weather advice (multi-grouped) ===
function formatAdvisoryWithoutNepali($advisories) {
    $html = "<ul>";
    foreach ($advisories as $group) {
        $condition = removeParenthesesContent($group["condition"]);
        $html .= "<li><strong>" . htmlspecialchars($condition) . "</strong><ul>";
        foreach ($group["advice"] as $adviceItem) {
            $cleanAdvice = removeParenthesesContent($adviceItem);
            $html .= "<li>" . htmlspecialchars($cleanAdvice) . "</li>";
        }
        $html .= "</ul></li>";
    }
    $html .= "</ul>";
    return $html;
}

// === Format weather impact (multi-grouped) ===
function formatImpactWithoutNepali($impacts) {
    $html = "<ul>";
    foreach ($impacts as $group) {
        $condition = removeParenthesesContent($group["condition"]);
        $html .= "<li><strong>" . htmlspecialchars($condition) . "</strong><ul>";
        foreach ($group["impact"] as $impactItem) {
            $cleanImpact = removeParenthesesContent($impactItem);
            $html .= "<li>" . htmlspecialchars($cleanImpact) . "</li>";
        }
        $html .= "</ul></li>";
    }
    $html .= "</ul>";
    return $html;
}

// === Extract & Format Data ===
$likelihood      = $data["likelihood"] ?? "";
$affectContinue  = $data["affectContinue"] ?? "";
$distribution    = $data["distribution"] ?? "";
$activityTime    = $data["activityTime"] ?? "";
$warningCode     = $data["warningCode"] ?? "";
$validity        = $data["validity"] ?? "";
$warning_message = $data["emailMessage"] ?? "";
$emailRecipients = ["srimanta.imd@gmail.com"];

$districts       = json_encode($data["districts"] ?? []);
$weatherAdviceRaw = $data["weatherAdvice"] ?? [];
$weatherImpactRaw = $data["weatherImpact"] ?? [];

$weatherAdvice   = json_encode($weatherAdviceRaw);
$weatherImpact   = json_encode($weatherImpactRaw);

// === Group flat advice and impact arrays by condition before formatting ===
$groupedAdvice = groupAdviceByCondition($weatherAdviceRaw);
$groupedImpact = groupImpactByCondition($weatherImpactRaw);

$formattedAdvice = formatAdvisoryWithoutNepali($groupedAdvice);
$formattedImpact = formatImpactWithoutNepali($groupedImpact);

// Save for debug
file_put_contents("formatted_advice.html", $formattedAdvice);
file_put_contents("formatted_impact.html", $formattedImpact);

// === Validate expectedTime ===
try {
    $dt = new DateTime($data["expectedTime"]);
    $expectedTime = $dt->format("Y-m-d H:i:s");
} catch (Exception $e) {
    $response["message"] = "Invalid expectedTime format";
    $response["error"] = $e->getMessage();
    echo json_encode($response);
    exit;
}

// === Check original PDF ===
$originalFile = 'uploads/Nowcast_Report.pdf';
if (!file_exists($originalFile)) {
    $response["message"] = "File not found: $originalFile";
    echo json_encode($response);
    exit;
}

// === Compress PDF using Ghostscript (Windows path) ===
$currentDateTime = date("Y-m-d_H-i-s");
$compressedPdfPath = 'uploads/Nowcast_Report_' . $currentDateTime . '_compressed.pdf';
$gsPath = 'C:\\Program Files\\gs\\gs10.05.1\\bin\\gswin64c.exe';

$cmd = "\"$gsPath\" -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook " .
       "-dNOPAUSE -dQUIET -dBATCH -sOutputFile=" . escapeshellarg($compressedPdfPath) . " " .
       escapeshellarg($originalFile);

exec($cmd . " 2>&1", $output, $return_var);

if ($return_var !== 0 || !file_exists($compressedPdfPath)) {
    $response["success"] = false;
    $response["message"] = "PDF compression failed or compressed file not found";
    $response["command"] = $cmd;
    $response["ghostscript_output"] = $output;
    echo json_encode($response);
    exit;
}

// Delete original PDF after compression
unlink($originalFile);

// === Send Email ===
$mail = new PHPMailer(true);
try {
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'drms.kolkata@gmail.com';
    $mail->Password = 'epzp mgef bbez nqqp'; // App password
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('drms.kolkata@gmail.com', 'Nowcast Warning');
    $mail->addAddress('dhiraj.nitmz@gmail.com');
    $mail->addAddress('mcgangtok101@gmail.com');

    foreach ($emailRecipients as $email) {
        $mail->addBCC($email);
    }

    $mail->isHTML(true);
    $mail->Subject = 'Nowcast Weather Warning [' . strtoupper($warningCode) . ']';

    $warningCodeColorMap = [
        "YELLOW" => "#ffff99",
        "ORANGE" => "#ffcc66",
        "RED"    => "#ff6666"
    ];

    $headerColor = $warningCodeColorMap[strtoupper($warningCode)] ?? "#cccccc";
$districtsArray = $data["districts"] ?? [];
$districtsStr = strtoupper(implode(", ", $districtsArray));
    // Build the HTML table
$tableHtml = "
<table border='1' cellpadding='8' cellspacing='0' style='border-collapse: collapse; width: 100%; font-family: Arial, sans-serif;'>
    <thead>
        <tr style='background-color: $headerColor;'>
            <th colspan='2' style='text-align: left; font-size: 18px;'>Warning Code: " . strtoupper($warningCode) . "</th>
        </tr>
    </thead>
    <tbody>
        <tr><td><strong>Likelihood</strong></td><td>" . strtoupper($likelihood) . "</td></tr>
        <tr><td><strong>Distribution</strong></td><td>" . strtoupper($distribution) . "</td></tr>
        <tr><td><strong>Affect/Continue</strong></td><td>" . strtoupper($affectContinue) . "</td></tr>
        <tr><td><strong>Activity Time</strong></td><td>$activityTime hours</td></tr>
        <tr><td><strong>Expected Time</strong></td><td>$expectedTime</td></tr>
        <tr><td><strong>Validity</strong></td><td>$validity hours</td></tr>
        <tr><td><strong>Districts</strong></td><td>$districtsStr</td></tr>
        <tr><td><strong>Advisories</strong></td><td>$formattedAdvice</td></tr>
        <tr><td><strong>Impacts</strong></td><td>$formattedImpact</td></tr>
    </tbody>
</table>
";

    $mail->Body = "
        <p>Respected Sir/Madam,</p>
        <p>" . nl2br(htmlspecialchars($warning_message)) . "</p>
        $tableHtml 
        <br>
        <p>Regards,<br>
        <strong>Meteorological Centre, Gangtok</strong><br>
        India Meteorological Department</p>
    ";

    $mail->addAttachment($compressedPdfPath);
    $mail->send();

    $response["success"] = true;
    $response["message"] = "Email sent with compressed PDF and data inserted successfully";

    // === Insert into DB ===
    $conn = new mysqli("localhost", "root", "root123", "nowcast_db");
    if ($conn->connect_error) {
        $response["message"] = "DB connection failed: " . $conn->connect_error;
        echo json_encode($response);
        exit;
    }

    $stmt = $conn->prepare("INSERT INTO `nowcast_reports` 
        (`likelihood`, `affect_continue`, `distribution`, `activity_time`, `expected_time`, 
         `warning_code`, `validity`, `districts`, `weather_advice`, `weather_impact`, `created_at`, `warning_message`) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP(), ?)");

    if (!$stmt) {
        $response["message"] = "Prepare failed: " . $conn->error;
        echo json_encode($response);
        exit;
    }

    $stmt->bind_param(
        "sssssssssss",
        $likelihood,
        $affectContinue,
        $distribution,
        $activityTime,
        $expectedTime,
        $warningCode,
        $validity,
        $districts,
        $weatherAdvice,
        $weatherImpact,
        $warning_message
    );

    if (!$stmt->execute()) {
        $response["message"] = "Insert failed: " . $stmt->error;
    }

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    $response["message"] = "Email sending failed";
    $response["error"] = $e->getMessage();
}

echo json_encode($response);
exit;
