<?php
include 'db.php';

$action = $_POST['action'] ?? '';

function sendNotificationEmail($subject, $message){
    $to = "giantplusmw@gmail.com";
    $headers = "From: cloud@gianterp.space\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";

    mail($to, $subject, $message, $headers);
}

if($action === 'add' || $action === 'edit'){
    $id = intval($_POST['edit_id'] ?? 0);
    $material_id = intval($_POST['material_id']);
    $meal_type = $_POST['meal_type'];
    $qty = floatval($_POST['qty_per_people']);
    $people = intval($_POST['people_count']);

    // get material name
    $res = $conn->query("SELECT name FROM products WHERE id=$material_id");
    $row = $res->fetch_assoc();
    $material_name = $row['name'] ?? '';

    if($id){ // update
        $conn->query("UPDATE meal_parameters SET material_id=$material_id, meal_type='$meal_type', qty_per_people=$qty, people_count=$people WHERE id=$id");
        echo "Parameter updated successfully";

        // Send email
        $subject = "Meal Parameter Edited";
        $message = "<p>Meal Parameter Edited:</p>
                    <ul>
                        <li>Material: $material_name</li>
                        <li>Meal Type: $meal_type</li>
                        <li>Qty per Person: $qty</li>
                        <li>Number of Guests: $people</li>
                    </ul>";
        sendNotificationEmail($subject, $message);

    } else { // add
        $conn->query("INSERT INTO meal_parameters (material_id, meal_type, qty_per_people, people_count) VALUES ($material_id, '$meal_type', $qty, $people)");
        echo "Parameter added successfully";
    }
}

if($action === 'remove'){
    $id = intval($_POST['id']);

    // fetch details before deletion
    $res = $conn->query("SELECT mp.*, p.name AS material_name FROM meal_parameters mp JOIN products p ON mp.material_id=p.id WHERE mp.id=$id");
    $row = $res->fetch_assoc();

    if($row){
        $conn->query("DELETE FROM meal_parameters WHERE id=$id");
        echo "Parameter removed successfully";

        // Send email
        $subject = "Meal Parameter Deleted";
        $message = "<p>Meal Parameter Deleted:</p>
                    <ul>
                        <li>Material: {$row['material_name']}</li>
                        <li>Meal Type: {$row['meal_type']}</li>
                        <li>Qty per Person: {$row['qty_per_people']}</li>
                        <li>Number of Guests: {$row['people_count']}</li>
                    </ul>";
        sendNotificationEmail($subject, $message);
    } else {
        echo "Parameter not found";
    }
}

if($action === 'list'){
    $res = $conn->query("SELECT mp.*, p.name AS material_name FROM meal_parameters mp JOIN products p ON mp.material_id=p.id ORDER BY mp.id ASC");
    $data = [];
    while($row = $res->fetch_assoc()){
        $data[] = $row;
    }
    echo json_encode($data);
}
?>