<?php
include("script/condb.php");
session_start();

header('Content-Type: text/html; charset=utf-8');

// Ensure project_ref is provided
if (!isset($_GET['project_ref'])) {
    echo "<script>
            alert('No project reference provided.');
            window.parent.closeModal();
          </script>";
    exit;
}

$ref = $_GET['project_ref'];
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
    $con->begin_transaction();

    $pidTables = [
        'basetypecal',
        'columnbased',
        'columntype-cal',
        'concrete',
        'foundation_equipment',
        'foundation_labourer',
        'foundation_materials',
        'mortalblockcal',
        'plankandwoodreport'
    ];

    foreach ($pidTables as $table) {
        $stmt = $con->prepare("DELETE FROM `$table` WHERE PID = ?");
        $stmt->bind_param("s", $ref);
        $stmt->execute();
        $stmt->close();
    }

    $stmt = $con->prepare("DELETE FROM upline_app_project_info WHERE project_ref = ?");
    $stmt->bind_param("s", $ref);
    $stmt->execute();
    $affected = $stmt->affected_rows;
    $stmt->close();

    if ($affected === 0) {
        $con->rollback();
        echo "<script>
                alert('Project not found. Nothing was deleted.');
                window.parent.closeModal();
              </script>";
        exit;
    }

    $con->commit();
    echo "<script>
            alert('Project and all related records deleted successfully.');
            window.parent.closeModal();
            window.parent.location.reload();
          </script>";
    exit;

} catch (Exception $e) {
    $con->rollback();
    $error = addslashes($e->getMessage());
    echo "<script>
            alert('Error deleting project: {$error}');
            window.parent.closeModal();
          </script>";
    exit;
}
?>
