<?php
// cancel_report.php

require_once('../../../' . $_REQUEST['tenant'] . '/config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $master_report_id = $_POST['master_report_id'] ?? null;
    $tenant = $_POST['tenant'] ?? null;

    // Check if master_report_id is provided
    if (empty($master_report_id)) {
        echo json_encode(['success' => false, 'message' => 'Missing master_report_id.']);
        exit;
    }

    // 1. Delete all rows for this master_report_id from the database
    $deleteQuery = "DELETE FROM elec_report WHERE master_report_id = ?";
    $stmt = $con->prepare($deleteQuery);
    $stmt->bind_param("s", $master_report_id);
    if ($stmt->execute()) {
        // 2. Delete all images related to this master_report_id
        $imagesFolder = "../../../" . $tenant . "/images/report_images/";
        $pattern = $imagesFolder . $master_report_id . "_*.jpg";
        $files = glob($pattern);

        foreach ($files as $file) {
            if (is_file($file)) {
                unlink($file); // Delete the file
            }
        }

        echo json_encode(['success' => true, 'message' => 'Report and associated data deleted successfully.']);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to delete report data.']);
    }
    $stmt->close();
}
exit;
?>