<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
require("emailBody.php");
// Load PHPMailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Make sure path is correct if using Composer

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

if ($data === null) {
    echo json_encode([
        "success" => false,
        "message" => "JSON decode failed",
        "error" => json_last_error_msg(),
        "raw_input" => $input
    ]);
    exit;
}

$emailRecipients=["dutyroomairkolkata@gmail.com","cs-westbengal@nic.in","ps.dmd-wb@nic.in","rnukolkata@gmail.com","ddnewskol@gmail.com","telecommail19@gmail.com",
"kolkatarmc@gmail.com"];
// Extract & sanitize form fields
$likelihood = $data["likelihood"] ?? "";
$affectContinue = $data["affectContinue"] ?? "";
$distribution = $data["distribution"] ?? "";
$activityTime = $data["activityTime"] ?? "";
$warningCode = $data["warningCode"] ?? "";
$validity = $data["validity"] ?? "";
$districts = json_encode($data["districts"] ?? []);
$weatherAdvice = json_encode($data["weatherAdvice"] ?? []);
$weatherImpact = json_encode($data["weatherImpact"] ?? []);
$warning_message = $data["emailMessage"] ?? "";
$emailRecipients = $emailRecipients; // e.g., ["user1@example.com", "user2@example.com"]

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

// === SEND EMAIL === //
$mail = new PHPMailer(true);
try {
    // SMTP Settings
    $mail->isSMTP();
    $mail->Host = 'smtp.gmail.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'issdkolkata@gmail.com'; // Replace with your Gmail
    $mail->Password = 'lcyn lptn rbpa efzi';   // Use App Password (not regular Gmail password)
    $mail->SMTPSecure = 'tls';
    $mail->Port = 587;

    $mail->setFrom('issdkolkata@gmail.com', 'Nowcast Warning');
    foreach ($emailRecipients as $email) {
        $mail->addAddress($email);
    }

    $mail->isHTML(true);
    $mail->Subject = 'Nowcast Weather Warning for'.$districts.',['.strtoupper($warningCode).'] Warning';
    $mail->Body = "
    <p>Respected Sir/Madam,</p>
    
    <p>" . nl2br($warning_message) . "</p>
    
    <br><br>
    <p>
        Regards,<br>
        <strong>प्रादेशिक मौसम पूर्वानुमान केंद्र, कोलकाता / Regional Weather Forecasting Centre, Kolkata</strong><br>
        प्रादेशिक मौसम केंद्र, कोलकाता / Regional Meteorological Centre, Kolkata<br>
        भारत मौसम विज्ञान विभाग / India Meteorological Department<br>
        अलीपुर, कोलकाता-700027 / Alipore, Kolkata-700027
    </p>
    ";
    

    $mail->send();

    // === Only Insert to DB if Email is Sent === //
    $servername = "localhost";
    $username = "root";
    $password = "altostratus";
    $dbname = "smfi_db";
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) {
        echo json_encode(["success" => false, "message" => "DB connection failed: " . $conn->connect_error]);
        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) {
        echo json_encode(["success" => false, "message" => "Prepare failed: " . $conn->error]);
        exit;
    }

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

    if ($stmt->execute()) {
        echo json_encode(["success" => true, "message" => "Email sent and data inserted successfully"]);
    } else {
        echo json_encode(["success" => false, "message" => "Insert failed: " . $stmt->error]);
    }

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

} catch (Exception $e) {
    echo json_encode(["success" => false, "message" => "Email sending failed", "error" => $mail->ErrorInfo]);
}
?>
