<?php
header('Content-Type: application/json');

require_once __DIR__ . '\..\config\config.php';
require_once __DIR__ . '\..\vendor\autoload.php';
require_once 'cron\mailer.php';

try {
    $input = json_decode(file_get_contents('php://input'), true);
    $budget = $input['budget'] ?? null;
    $loggedUserId = $input['loggedUserId'] ?? null;
    $clientId = $input['clientId'] ?? null;
    $clientName = $input['clientName'] ?? null;

    if (!$budget || !$loggedUserId || !$clientId) {
        throw new Exception("Missing parameters");
    }

    // Fetch employee, RM, and HOD info
    $sql = "
        SELECT 
            e.name AS emp_name, e.email AS emp_email,
            rm.name AS rm_name, rm.email AS rm_email,
            hod.name AS hod_name, hod.email AS hod_email
        FROM employee e
        LEFT JOIN employee rm ON rm.emp_id = e.rm_id
        LEFT JOIN department d ON d.dept_id = e.dept_id
        LEFT JOIN employee hod ON hod.emp_id = d.dept_head
        WHERE e.emp_id = ?
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $loggedUserId);
    $stmt->execute();
    $result = $stmt->get_result();
    $emp = $result->fetch_assoc();

    if (!$emp) {
        throw new Exception("Employee not found");
    }

    // Prepare email data
    $emp_name = $emp['emp_name'];
    $rm_name = $emp['rm_name'];
    $hod_name = $emp['hod_name'];

    // Include the email template
    include '../includes/email_templates/budget_change.php'; // $html is created inside

    $subject = "High Alert - Budget Update - $clientName ($emp_name)";

    // Send mail
    $mail = getMailer();
    if (!empty($emp['rm_email']))
        $mail->addAddress($emp['rm_email'], $rm_name);
    if (!empty($emp['hod_email']))
        $mail->addAddress($emp['hod_email'], $hod_name);
    $mail->Subject = $subject;
    $mail->Body = $html;
    $mail->isHTML(true);
    $mail->send();

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}