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

require("emailBody.php"); // Include any required email body setup
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php'; // Make sure path is correct if using Composer

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

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

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

// 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 = ["dutyroomairkolkata@gmail.com","cs-westbengal@nic.in","ps.dmd-wb@nic.in","rnukolkata@gmail.com","ddnewskol@gmail.com","telecommail19@gmail.com","kolkatarmc@gmail.com","sourish.bondyopadhyay@gmail.com"];

// Validate expectedTime format
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;
}

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

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

    // Attach PDF file
    $filePath = 'uploads/Nowcast_Report.pdf';
    if (!file_exists($filePath)) {
        $response["message"] = "File not found: $filePath";
        echo json_encode($response);
        exit;
    }
    $mail->addAttachment($filePath);

    // Email body
    $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();

    // Rename file after email
    $currentDateTime = date("Y-m-d_H-i-s");
    $newFilePath = 'uploads/Nowcast_Report_' . $currentDateTime . '.pdf';
    if (!rename($filePath, $newFilePath)) {
        $response["message"] = "Email sent, but failed to rename file";
        echo json_encode($response);
        exit;
    }

    // === Insert to DB === //
    $conn = new mysqli("localhost", "root", "altostratus", "smfi_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["success"] = true;
        $response["message"] = "Email sent, file renamed, and data inserted successfully";
    } else {
        $response["message"] = "Insert failed: " . $stmt->error;
    }

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

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

echo json_encode($response);
?>
