<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
session_start();
include('script/condb.php');
include('script/uom_converter.php'); // ✅ Make sure this file exists

$PID = $_GET['xd'] ?? $_POST['PID'] ?? null;

// ✅ 1. Get project default UOM
$projQuery = mysqli_query($con, "SELECT default_uom FROM upline_app_project_info WHERE project_ref='$PID'");
$projData = mysqli_fetch_assoc($projQuery);
$projectUOM = $projData['default_uom'] ?? 'm'; // fallback to meters

if (isset($_POST["check1"])) {

    //------------------------9"-------------------------------------------
    $is44 = "SELECT * FROM upline_app_blocksettings WHERE ID='2'";
    $ise44 = mysqli_query($con, $is44);
    while ($rec44 = mysqli_fetch_array($ise44)) {
        $blockame = $rec44['Block_name']; 
        $labourprice = $rec44['Up_Labours'];
		$boqprice=$rec44['BOQprice'];
    }

    //------------------------6"-------------------------------------------
    $is45 = "SELECT * FROM upline_app_blocksettings WHERE ID='4'";
    $ise45 = mysqli_query($con, $is45);
    while ($rec45 = mysqli_fetch_array($ise45)) {
        $blockame6 = $rec45['Block_name']; 
        $labourprice6 = $rec45['Up_Labours'];
		$boqprice2=$rec45['BOQprice'];
    }

    //------------------------5"-------------------------------------------
    $is46 = "SELECT * FROM upline_app_blocksettings WHERE ID='5'";
    $ise46 = mysqli_query($con, $is46);
    while ($rec46 = mysqli_fetch_array($ise46)) {
        $blockame5 = $rec46['Block_name']; 
        $labourprice5 = $rec46['Up_Labours'];
		$boqprice3=$rec46['BOQprice'];
    }

    //------------------------4"-------------------------------------------
    $is47 = "SELECT * FROM upline_app_blocksettings WHERE ID='6'";
    $ise47 = mysqli_query($con, $is47);
    while ($rec47 = mysqli_fetch_array($ise47)) {
        $blockame4 = $rec47['Block_name']; 
        $labourprice4 = $rec47['Up_Labours'];
		$boqprice4=$rec47['BOQprice'];
    }

    // ✅ 2. Capture form values
    $A_3 = $_POST['extwalls'];
    $blocktype1 = $_POST['ddselect'];
    $A_5 = $_POST['length'];
    $A_11 = $_POST['course'];
    $A_7 = $_POST['height'];
    $A_3A = $_POST['intwalls'];
    $A_6A = $_POST['length2'];
    $A_12A = $_POST['course2'];
    $A_8A = $_POST['height2'];
    $otherwalls = $_POST['otherwalls'];
    $A_6 = $_POST['length3'];
    $A_12 = $_POST['course3'];
    $A_8 = $_POST['height3'];
    $blocktype2 = $_POST['amigo'];
    $blocktype3 = $_POST['amadi'];

    // ✅ 3. Convert all dimensional inputs into default UOM
    $A_5  = convertUOM($A_5, 'm', $projectUOM);
    $A_7  = convertUOM($A_7, 'm', $projectUOM);
    $A_6A = convertUOM($A_6A, 'm', $projectUOM);
    $A_8A = convertUOM($A_8A, 'm', $projectUOM);
    $A_6  = convertUOM($A_6, 'm', $projectUOM);
    $A_8  = convertUOM($A_8, 'm', $projectUOM);

    // ✅ Rest of your original variables
    $M36 = 0.11875;
    $A_NH_1 = 0.25;
    $A_NH_5 = 0.11875;
    $inblck9 = 400;
    $inblck6 = 350;
    $inblck5 = 320;
    $inblck4 = 350;
    $unitprice = '';
    $unitprice1 = '';
    $unitprice2 = '';
    $blocktype1a = 'Laying of ' . $blocktype1;
    $blocktype2a = 'Laying of ' . $blocktype2;
    $blocktype3a = 'Laying of ' . $blocktype3;

    //--------------------unit price------------------
    if ($blocktype1 == '9 inches Hollow Block') {
        $unitprice = $inblck9;
		$bqpm =$boqprice;
    } elseif ($blocktype1 == '6 inches Solid Block' || $blocktype1 == '6 inches Hollow Block') {
        $unitprice = $inblck6;
		$bqpm =$boqprice2;
    } elseif ($blocktype1 == '5 inches Solid Block') {
        $unitprice = $inblck5;
		$bqpm=$boqprice3;
    } elseif ($blocktype1 == '4 inches Hollow Block') {
        $unitprice = $inblck4;
		$bqpm=$boqprice4;
    }

    //------------two-------------
    if ($blocktype2 == '9 inches Hollow Block') {
        $unitprice1 = $inblck9;
		$bqpm2=$boqprice;
    } elseif ($blocktype2 == '6 inches Solid Block' || $blocktype1 == '6 inches Hollow Block') {
        $unitprice1 = $inblck6;
		$bqpm2=$boqprice2;
    } elseif ($blocktype2 == '5 inches Solid Block') {
        $unitprice1 = $inblck5;
		$bqpm2=$boqprice3;
    } elseif ($blocktype2 == '4 inches Hollow Block') {
        $unitprice1 = $inblck4;
		$bqpm2=$boqprice4;
    }

    //------------three-------------
    if ($blocktype3 == '9 inches Hollow Block') {
        $unitprice2 = $inblck9;
		$bqpm3=$boqprice;
    } elseif ($blocktype3 == '6 inches Solid Block' || $blocktype1 == '6 inches Hollow Block') {
        $unitprice2 = $inblck6;
		$bqpm3 =$boqprice2;
    } elseif ($blocktype3 == '5 inches Solid Block') {
        $unitprice2 = $inblck5;
		$bqpm3=$boqprice3;
    } elseif ($blocktype3 == '4 inches Hollow Block') {
        $unitprice2 = $inblck4;
		$bqpm3=$boqprice4;
    }

    //-----------------external wall calculations----------------------
    $hl = $A_5 * $A_7;
    $hl2 = $hl / $M36;
    $extrwallcal = $hl2;
    $coeextrwallcal2 = number_format($extrwallcal, 0);

    $boqextrwallcal = number_format($A_5 * $A_7, 0);
    if ($blocktype1 == '9 inches Hollow Block') {
        $totalblockCOE = $coeextrwallcal2 * $inblck9;
        $totalblockBOQ = $boqextrwallcal * $boqprice;
        $coelabourtotal = $labourprice * $coeextrwallcal2;
        $boqlabourtotal = $labourprice * $boqextrwallcal;
    } elseif ($blocktype1 == '6 inches Solid Block' || $blocktype1 == '6 inches Hollow Block') {
        $totalblockCOE = $coeextrwallcal2 * $inblck6;
        $totalblockBOQ = $boqextrwallcal * $boqprice2;
        $coelabourtotal = $labourprice5 * $coeextrwallcal2;
        $boqlabourtotal = $labourprice5 * $boqextrwallcal2;
    } elseif ($blocktype1 == '5 inches Solid Block') {
        $totalblockCOE = $coeextrwallcal2 * $inblck5;
        $totalblockBOQ = $boqextrwallcal * $boqprice3;
        $coelabourtotal = $coeextrwallcal2 * $labourprice5;
        $boqlabourtotal = $boqextrwallcal * $labourprice5;
    } elseif ($blocktype1 == '4 inches Hollow Block') {
        $totalblockCOE = $coeextrwallcal2 * $inblck4;
        $totalblockBOQ = $boqextrwallcal * $boqprice4;
        $coelabourtotal = $labourprice4 * $coeextrwallcal2;
        $boqlabourtotal = $labourprice4 * $boqextrwallcal;
    }

    //-----------------internal wall calculations----------------------
    $hlin = $A_6A * $A_8A;
    $hlin2 = $hlin / $M36;
    $intwallcal = number_format($hlin2, 0);
    $boqintwallcal = number_format($A_6A * $A_8A, 0);

    if ($blocktype2 == '9 inches Hollow Block') {
        $totalblockCOE1 = $intwallcal * $inblck9;
        $totalblockBOQ1 = $boqintwallcal * $boqprice;
        $coelabourtotal = $labourprice * $intwallcal;
        $boqlabourtotal = $labourprice * $boqintwallcal;
    } elseif ($blocktype2 == '6 inches Solid Block' || $blocktype2 == '6 inches Hollow Block') {
        $totalblockCOE1 = $intwallcal * $inblck6;
        $totalblockBOQ1 = $boqintwallcal * $boqprice2;
        $coelabourtotal1 = $labourprice5 * $intwallcal;
        $boqlabourtotal1 = $labourprice5 * $boqintwallcal;
    } elseif ($blocktype2 == '5 inches Solid Block') {
        $totalblockCOE1 = $intwallcal * $inblck5;
        $totalblockBOQ1 = $boqintwallcal * $boqprice3;
        $coelabourtotal1 = $intwallcal * $labourprice5;
        $boqlabourtotal1 = $boqintwallcal * $labourprice5;
    } elseif ($blocktype2 == '4 inches Hollow Block') {
        $totalblockCOE = $intwallcal * $inblck4;
        $totalblockBOQ = $boqintwallcal * $boqprice4;
        $coelabourtotal1 = $labourprice4 * $intwallcal;
        $boqlabourtotal1 = $labourprice4 * $boqintwallcal;
    }

    //-----------------other wall calculations----------------------
    $hloth = $A_6 * $A_8;
    $hloth2 = $hloth / $M36;
    $othwallcal = number_format($hloth2, 0);
    $boqothwallcal = number_format($A_6 * $A_8, 0);

    if ($blocktype3 == '9 inches Hollow Block') {
        $totalblockCOE2 = $othwallcal * $inblck9;
        $totalblockBOQ2 = $boqothwallcal * $boqprice;
        $coelabourtotal2 = $labourprice * $othwallcal;
        $boqlabourtotal2 = $labourprice * $boqothwallcal;
    } elseif ($blocktype3 == '6 inches Solid Block' || $blocktype3 == '6 inches Hollow Block') {
        $totalblockCOE2 = $othwallcal * $inblck6;
        $totalblockBOQ2 = $boqothwallcal * $boqprice2;
        $coelabourtotal2 = $labourprice5 * $othwallcal;
        $boqlabourtotal2 = $labourprice5 * $boqothwallcal;
    } elseif ($blocktype3 == '5 inches Solid Block') {
        $totalblockCOE2 = $othwallcal * $inblck5;
        $totalblockBOQ2 = $boqothwallcal * $boqprice3;
        $coelabourtotal2 = $othwallcal * $labourprice5;
        $boqlabourtotal2 = $boqothwallcal * $labourprice5;
    } elseif ($blocktype3 == '4 inches Hollow Block') {
        $totalblockCOE2 = $othwallcal * $inblck4;
        $totalblockBOQ2 = $boqothwallcal * $boqprice4;
        $coelabourtotal2 = $labourprice4 * $othwallcal;
        $boqlabourtotal2 = $labourprice4 * $boqothwallcal;
    }

    //--------------------------Insert into wall_calculation-------------------------
    $inst2 = "INSERT INTO wall_calculation (PID, walltype, blocktype, walllength, wallheight, Course) VALUES
    ('$PID', '$A_3', '$blocktype1', '$A_5', '$A_7', '$A_11'),
    ('$PID', '$A_3A', '$blocktype2', '$A_6A', '$A_8A', '$A_12A'),
    ('$PID', '$otherwalls', '$blocktype3', '$A_6', '$A_8', '$A_12')";
    mysqli_query($con, $inst2);

    //---------------------------foundation_labourer-------------------------------
    $coelabourtotal1 = isset($coelabourtotal1) ? $coelabourtotal1 : 0; $boqlabourtotal1 = isset($boqlabourtotal1) ? $boqlabourtotal1 : 0;
    
    $fl = "INSERT INTO foundation_labourer (PID, LabourerDescription, COEQuantity, BOQQuantity, Extra, Price, COETotal, BOQTotal) VALUES
    ('$PID', '$blocktype1a', '$coeextrwallcal2', '$boqextrwallcal', '0', '$labourprice', '$coelabourtotal', '$boqlabourtotal'),
    ('$PID', '$blocktype2a', '$intwallcal', '$boqintwallcal', '0', '$labourprice', '$coelabourtotal1', '$boqlabourtotal1'),
    ('$PID', '$blocktype3a', '$othwallcal', '$boqothwallcal', '0', '$labourprice', '$coelabourtotal2', '$boqlabourtotal2')";
    mysqli_query($con, $fl);

   
    // -------------------------foundation_materials (fixed totals + integrated pricing)-------------------------------

// ✅ Helper function to fetch COE and BOQ prices from upline_app_blocksettings by block name
function getBlockPrices($con, $blockName) {
    $query = "SELECT Block_prices, BOQprice FROM upline_app_blocksettings WHERE Block_name = '$blockName' LIMIT 1";
    $result = mysqli_query($con, $query);
    if ($row = mysqli_fetch_assoc($result)) {
        return [
            'unitprice' => floatval($row['Block_prices']), // COE price numeric
            'boqprice'  => floatval($row['BOQprice'])      // BOQ price numeric
        ];
    } else {
        return [
            'unitprice' => 0.0,
            'boqprice'  => 0.0
        ];
    }
}

// ✅ Fetch block price data for each block type
$block1_prices = getBlockPrices($con, $blocktype1);
$block2_prices = getBlockPrices($con, $blocktype2);
$block3_prices = getBlockPrices($con, $blocktype3);

// ✅ Ensure quantities are numeric and properly formatted
$qty_coe_1  = floatval(str_replace(',', '', $coeextrwallcal2));
$qty_boq_1  = floatval(str_replace(',', '', $boqextrwallcal));

$qty_coe_2  = floatval(str_replace(',', '', $intwallcal));
$qty_boq_2  = floatval(str_replace(',', '', $boqintwallcal));

$qty_coe_3  = floatval(str_replace(',', '', $othwallcal));
$qty_boq_3  = floatval(str_replace(',', '', $boqothwallcal));

// ✅ Compute total costs (COE × unit price and BOQ × BOQ price)
$totalblockCOE  = $qty_coe_1 * $block1_prices['unitprice'];
$totalblockBOQ  = $qty_boq_1 * $block1_prices['boqprice'];

$totalblockCOE1 = $qty_coe_2 * $block2_prices['unitprice'];
$totalblockBOQ1 = $qty_boq_2 * $block2_prices['boqprice'];

$totalblockCOE2 = $qty_coe_3 * $block3_prices['unitprice'];
$totalblockBOQ2 = $qty_boq_3 * $block3_prices['boqprice'];

// ✅ Optionally keep backward-compatible variable names
$unitprice  = $block1_prices['unitprice'];
$unitprice1 = $block2_prices['unitprice'];
$unitprice2 = $block3_prices['unitprice'];

$boqpm  = $block1_prices['boqprice'];
$boqpm2 = $block2_prices['boqprice'];
$boqpm3 = $block3_prices['boqprice'];

// ✅ Insert calculated values into foundation_materials
$inst = "INSERT INTO foundation_materials 
(PID, MaterialDescription, MaterialType, COEQuantity, BOQQuantity, Extra, Price, BOQprice, CETotalAmount, BOQTotalAmount) VALUES
('$PID', '$blocktype1', 'Block', '$qty_coe_1', '$qty_boq_1', '0', '$unitprice', '$boqpm', '$totalblockCOE', '$totalblockBOQ'),
('$PID', '$blocktype2', 'Block', '$qty_coe_2', '$qty_boq_2', '0', '$unitprice1', '$boqpm2', '$totalblockCOE1', '$totalblockBOQ1'),
('$PID', '$blocktype3', 'Block', '$qty_coe_3', '$qty_boq_3', '0', '$unitprice2', '$boqpm3', '$totalblockCOE2', '$totalblockBOQ2')";

$checkmate = mysqli_query($con, $inst);

// ✅ Redirect on success or show diagnostic error
if ($checkmate) {
    header("Location: stagesofproject.php?id=$PID");
    exit;
} else {
    die("Insert Error (foundation_materials): " . mysqli_error($con) . "<br><strong>Query:</strong> " . htmlspecialchars($inst));
}

    
    
    
    
    
}
    
    
    
    
   
?>
