<?php
include("../../../include/startup.php"); 
if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_po_item'){
	$returnArray = array();
	$po_item_mapping_id = $_REQUEST['po_item_mapping_id'];
	$delete_sql = "DELETE FROM purchase_order_items_mapping WHERE id = '$po_item_mapping_id'";
	if(mysqli_query($conn,$delete_sql)){
		$returnArray["status"] = "success";
	}else{
		$returnArray["status"] = "failure";
	}
	
	echo json_encode($returnArray);
	die;
}elseif(isset($_REQUEST['action']) && $_REQUEST['action']=='get_supplier_address_details'){
	$returnArray = array();
	$supplier_id = $_REQUEST['supplier_id'];
    $sql = "SELECT * FROM supplier_management WHERE id = $supplier_id ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		$row = mysqli_fetch_assoc($rs);
		$row = utility::validate_crypt_data($row);
		
		$subcontractor_detail = "";
		if(isset($row["address1"]) && $row["address1"] !=""){
			$subcontractor_detail .= $row["address1"].", ";
		}
		if(isset($row["address2"]) && $row["address2"] !=""){
			$subcontractor_detail .= $row["address2"].", ";
		}
		if(isset($row["address3"]) && $row["address3"] !=""){
			$subcontractor_detail .= $row["address3"].", ";
		}
		if(isset($row["town_city"]) && $row["town_city"] !=""){
			$subcontractor_detail .= $row["town_city"].", ";
		}
		if(isset($row["postcode"]) && $row["postcode"] !=""){
			$subcontractor_detail .= $row['postcode'].", ";
		}
		if(isset($row["country"]) && $row["country"] !=""){
			$subcontractor_detail .= $gsi->getCountryById($row['country']);
		}
		$returnArray["status"] = "success";
		$returnArray["sub_contractor_telephone"] = $row['account_manager_telephone'];
		$returnArray["sub_contractor_address"] = $subcontractor_detail;
		
	}
	echo json_encode($returnArray);
	die;
}elseif(isset($_REQUEST['action']) && $_REQUEST['action']=='get_site_address_by_site_id'){
	$returnArray = array();
	//$site_sub_contractor_check = $_REQUEST['site_sub_contractor_check'];
	$site_id = $_REQUEST['site_id'];
	$org_id = $_REQUEST['org_id'];
	$sql = "SELECT * FROM site_management WHERE id = $site_id ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		$row = mysqli_fetch_assoc($rs);
		$row = utility::validate_crypt_data($row);
		//$priority_site = $row['priority_site'];
		$site_address_detail = "";
		if(isset($row["address1"]) && $row["address1"] !=""){
			$site_address_detail .= $row["address1"].", ";
		}
		if(isset($row["address2"]) && $row["address2"] !=""){
			$site_address_detail .= $row["address2"].", ";
		}
		if(isset($row["address3"]) && $row["address3"] !=""){
			$site_address_detail .= $row["address3"].", ";
		}
		if(isset($row["address4"]) && $row["address4"] !=""){
			$site_address_detail .= $row["address4"].", ";
		}
		if(isset($row["postcode"]) && $row["postcode"] !=""){
			$site_address_detail .= $row['postcode'].",";
		}
		if(isset($row["country"]) && $row["country"] !=""){
			$site_address_detail .= $gsi->getCountryById($row['country']);
		}
		$returnArray["status"] = "success";
		$returnArray["site_address"] = $site_address_detail;
		$returnArray["is_site_needs_po"] = $row['is_needs_po'];
		$returnArray["contact_name"] = $row['contact_name'];
		$returnArray["telephone"] = $row['telephone'];
		$returnArray["email"] = $row['email'];
		$returnArray["access_times"] = $row['access_times'];
		$returnArray["parking"] = $row['parking'];
		$returnArray["site_encrypt_id"] = urlencode(utility::app_crypt($row['id'],'e'));
		$returnArray["site_priority_site_exist"] = $row['priority_site'];
		
		if($org_id !=""){
			$returnArray["is_client_needs_po"] = utility::getTableFieldById("organisation_management","is_needs_po","id",$org_id);
		}
		
	}
	
	$site_notes_qry = "SELECT id FROM notes WHERE site_id = '$site_id' AND mark_as_important = '1'";
	$site_notes_sql = mysqli_query($conn,$site_notes_qry);
	if(mysqli_num_rows($site_notes_sql) > 0){
		$returnArray["site_important_notes_exist"] = "1";
	}
	echo json_encode($returnArray);
	die;
		
}elseif(isset($_REQUEST['action']) && $_REQUEST['action']=='get_sub_contract_address_by_contract_id'){
	$returnArray = array();
	$sub_contractor_id = $_REQUEST['sub_contractor_id'];
	
	$supplier_sql = "SELECT id,address1,address2,address3,town_city,postcode,country FROM supplier_management WHERE id = '$sub_contractor_id' ";
	$supplier_rs = mysqli_query($conn,$supplier_sql);
	if(mysqli_num_rows($supplier_rs) > 0){
		$supplier_row = mysqli_fetch_assoc($supplier_rs);
		$supplier_row = utility::validate_crypt_data($supplier_row);
		
		$sub_contractor_address = "";
		if(isset($supplier_row["address1"]) && $supplier_row["address1"] !=""){
			$sub_contractor_address .= $supplier_row["address1"].", ";
		}
		if(isset($supplier_row["address2"]) && $supplier_row["address2"] !=""){
			$sub_contractor_address .= $supplier_row["address2"].", ";
		}
		if(isset($supplier_row["address3"]) && $supplier_row["address3"] !=""){
			$sub_contractor_address .= $supplier_row["address3"].", ";
		}
		if(isset($supplier_row["town_city"]) && $supplier_row["town_city"] !=""){
			$sub_contractor_address .= $supplier_row["town_city"].", ";
		}
		if(isset($supplier_row["postcode"]) && $supplier_row["postcode"] !=""){
			$sub_contractor_address .= $supplier_row['postcode'].", ";
		}
		if(isset($supplier_row["country"]) && $supplier_row["country"] !=""){
			$sub_contractor_address .= $gsi->getCountryById($supplier_row['country']);
		}
		$returnArray["status"] = "success";
		$returnArray["sub_contractor_address"] = $sub_contractor_address;
	}
	echo json_encode($returnArray);
	die;
		
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='delete_PO'){
	$po_id = $_REQUEST['po_id'];
	mysqli_query($conn,"DELETE FROM purchase_order WHERE id = '$po_id' ");
	mysqli_query($conn,"DELETE FROM purchase_order_items_mapping WHERE po_id = '".$po_id."' "); 
	
	$returnArray["status"] = "success";
	echo json_encode($returnArray);
}else if(isset($_REQUEST['action']) && $_REQUEST['action']=='get_part_description_by_part_number'){
	$dataArray = array();
	$dataArray["status"] = "failure";
	$part_number = $_REQUEST['part_number'];
    $sql = "SELECT id,product_description FROM item_management WHERE id = '$part_number' ";
	$rs = mysqli_query($conn,$sql);
	if(mysqli_num_rows($rs) > 0){
		$row = mysqli_fetch_assoc($rs);
		$dataArray["status"] = "success";
		$dataArray["product_description"] = $row['product_description'];
	}
	echo json_encode($dataArray);
} else if ($_REQUEST['action'] == 'get_all_slips') {
    $po_id = isset($_POST['po_id']) ? intval($_POST['po_id']) : 0;
    if ($po_id > 0) {
        $result = mysqli_query($conn, "
            SELECT ps.id, ps.purchase_order_mapp_id, ps.qty_received, 
                   ps.received_by, ps.slip_date, ps.supplier_delivery_ref,
                   pom.part_number, pom.po_id, pom.description 
            FROM purchase_slips ps 
            JOIN purchase_order_items_mapping pom ON ps.purchase_order_mapp_id = pom.id 
            WHERE pom.po_id = $po_id 
            ORDER BY ps.purchase_order_mapp_id DESC
        ");

        $grouped_slips = [];
        while ($row = $result->fetch_assoc()) {
            $row['slip_date']  = utility::getFormatedDateReturn($row['slip_date']);
            $row['received_by'] = $gsi->getEmployeeById($row['received_by']);
            $row['order_reff'] = $gsi->getPurchaseById($row['po_id']);
            // supplier_delivery_ref is already in $row from the SELECT
            $grouped_slips[$row['purchase_order_mapp_id']][] = $row;
        }

        echo json_encode([
            "status" => "success",
            "data"   => $grouped_slips
        ]);
    } else {
        echo json_encode([
            "status"  => "error",
            "message" => "Invalid purchase order ID."
        ]);
    }
    exit;
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'mark_email_sent') {
    $returnArray = array();
    $po_id = intval($_REQUEST['po_id']);
    if ($po_id > 0) {
        $sql = "UPDATE purchase_order SET is_emailed = 1 WHERE id = '$po_id'";
        if (mysqli_query($conn, $sql)) {
            $returnArray['status'] = 'success';
        } else {
            $returnArray['status'] = 'failure';
        }
    } else {
        $returnArray['status'] = 'failure';
    }
    echo json_encode($returnArray);
    die;
}else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'bulk_bookin_line') {
    $returnArray = array();
    $order_id    = intval($_REQUEST['order_id']);
    $po_id       = intval($_REQUEST['po_id']);
    $qty         = intval($_REQUEST['qty']);
    $received_by = intval($_REQUEST['received_by']);
    $delivery_ref = mysqli_real_escape_string($conn, $_REQUEST['delivery_ref'] ?? ''); // ★

    if ($order_id > 0 && $qty > 0) {
        $res   = mysqli_query($conn, "SELECT part_number, quantity, received FROM purchase_order_items_mapping WHERE id = $order_id");
        $order = mysqli_fetch_assoc($res);

        $new_received = $order['received'] + $qty;

        // Allow overship (front-end already confirmed)
        mysqli_query($conn, "UPDATE purchase_order_items_mapping SET received = $new_received WHERE id = $order_id");

        mysqli_query($conn,
            "INSERT INTO purchase_slips (purchase_order_mapp_id, qty_received, received_by, slip_date, supplier_delivery_ref)
             VALUES ($order_id, $qty, $received_by, NOW(), '$delivery_ref')"  
        );

        $part_number = mysqli_real_escape_string($conn, $order['part_number']);
        mysqli_query($conn, "UPDATE inventory SET quantity_in_stock = quantity_in_stock + $qty WHERE item_id = '$part_number'");

        mysqli_query($conn, "UPDATE purchase_order_items_mapping SET is_reviewed = 0, review_notes = '' WHERE id = $order_id");

        $all_res   = mysqli_query($conn, "SELECT quantity, received FROM purchase_order_items_mapping WHERE po_id = $po_id");
        $all_equal = true;
        while ($r = mysqli_fetch_assoc($all_res)) {
            if ($r['quantity'] != $r['received']) { $all_equal = false; break; }
        }
        if ($all_equal) mysqli_query($conn, "UPDATE purchase_order SET order_status = 4 WHERE id = $po_id");

        $returnArray['status'] = 'success';
    } else {
        $returnArray['status']  = 'failure';
        $returnArray['message'] = 'Invalid parameters';
    }

    echo json_encode($returnArray);
    die;
}
else if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'get_nominal_by_part_number') {
    $part_number = mysqli_real_escape_string($conn, $_REQUEST['part_number']);

    // Step 1: get product_group from item_management
    $item_sql = mysqli_query($conn, "SELECT product_group FROM item_management WHERE id = '$part_number' LIMIT 1");
    $item_row = mysqli_fetch_assoc($item_sql);

    if($item_row && $item_row['product_group'] != ''){
        $pg_id = intval($item_row['product_group']);

        // Step 2: get nominal_code from product_group table
        $pg_sql = mysqli_query($conn, "SELECT nominal_code FROM product_group WHERE id = $pg_id LIMIT 1");
        $pg_row = mysqli_fetch_assoc($pg_sql);

        if($pg_row && $pg_row['nominal_code'] != ''){
            echo json_encode(['status' => 'success', 'nominal_code' => $pg_row['nominal_code']]);
        } else {
            echo json_encode(['status' => 'error', 'msg' => 'No nominal code on product group']);
        }
    } else {
        echo json_encode(['status' => 'error', 'msg' => 'Part not found or no product group']);
    }
    exit();
}

die;
?>