<?php

class ProductStockDeductions {



public static function UpdateDeductions($product_id, $new_qty, $invoice_id) {
    global $db;
    // Fetch existing deductions
    $deductions = self::GetProductStockDeductionByInvoiceIdAndProductId($invoice_id, $product_id);
    
    // Calculate the total deducted quantity
    $total_deducted = array_sum(array_column($deductions, 'deducted_quantity'));

    if ($new_qty > $total_deducted) {
        // Deduct additional quantity
        $deduct_qty = $new_qty - $total_deducted;
        ProducedProducts::DeductStockFIFO($product_id, $deduct_qty, $invoice_id);
    } elseif ($new_qty < $total_deducted) {
        // Restore excess quantity
        $restore_qty = $total_deducted - $new_qty;
        ProducedProducts::RestoreStock($product_id, $restore_qty, $invoice_id);
    }
    
    // Update the deduction entries in the database if necessary
    // (this may involve deleting some rows, adding new ones, etc.)
    // Implementation depends on the specific structure of your database
}

  
 public static function DeleteDeduction($product_id, $invoice_id) {
    global $db;
    $query = "DELETE FROM". TABLE_PRODUCT_STOCK_DEDUCTIONS . "WHERE product_id = '$product_id' AND invoice_id = '$invoice_id'";
    return $db->query($query);
}

  /* This method fetches deduction entries for a specific product and invoice.

 */
  
  
 public static function GetProductStockDeductionByInvoiceIdAndProductId($invoice_id, $product_id) {
    global $db;
    $query = "SELECT * FROM". TABLE_PRODUCT_STOCK_DEDUCTIONS . "WHERE invoice_id = '$invoice_id' AND product_id = '$product_id'";
    $result = $db->query($query);
    return $result->fetch_all(MYSQLI_ASSOC);
}
 
  //***************************************************************

//Delete Product Stock Deduction
 //*****************************************************
 public static function DeleteProductStockDeduction($deduction_id) {
    global $db; // Ensure that the global $db is being used

    // Construct the SQL query to delete the record by deduction ID
    $query = "DELETE FROM " . TABLE_PRODUCT_STOCK_DEDUCTIONS . " WHERE id = '$deduction_id'";

    // Execute the query
    $result = $db->query($query);

    // Check if the deletion was successful
    if ($db->affected_rows > 0) {
        return true; // Return true if the record was successfully deleted
    } else {
        return false; // Return false if no record was deleted
    }
}
 
  


    // Method to add a new stock deduction entry
    public static function AddProductStockDeduction($data) {
        global $db;
        return $db->query_insert(TABLE_PRODUCT_STOCK_DEDUCTIONS, $data);
    }

    // Other methods (UpdateDeductions, DeleteDeduction, etc.) remain the same

  public static function UpdateStockDeduction($deduction_id, $data) {
        global $db;

        // Generate the update query string
        $update_data = [];
        foreach ($data as $key => $value) {
            $update_data[] = "$key = '$value'";
        }
        $update_query = implode(", ", $update_data);

        // Execute the update query
        $query = "UPDATE " . TABLE_PRODUCT_STOCK_DEDUCTIONS . " SET $update_query WHERE id = '$deduction_id'";
        $result = $db->query($query);

        // Return true if the update was successful
        return $db->affected_rows > 0;
    }
  
  public static function GetProductStockDeductionByInvoiceId($invoice_id) {
    global $db;

    // Construct the SQL query to fetch all product stock deductions for the given invoice ID
    $query = "SELECT * FROM " . TABLE_PRODUCT_STOCK_DEDUCTIONS . " WHERE invoice_id = '$invoice_id'";

    // Execute the query
    $result = $db->query($query);

    // Fetch all results as an associative array
    return $result->fetch_all(MYSQLI_ASSOC);
}
  
  public static function GetTotalDeductedByInvoiceAndProduct($invoice_id, $product_id) {
    global $db;

    $invoice_id = (int)$invoice_id;
    $product_id = (int)$product_id;

    $query = "SELECT COALESCE(SUM(deducted_quantity),0) AS total_qty
              FROM " . TABLE_PRODUCT_STOCK_DEDUCTIONS . "
              WHERE invoice_id = '{$invoice_id}'
                AND product_id = '{$product_id}'";
    $row = $db->query_first($query);

    if ($row && isset($row->total_qty)) {
        return (float)$row->total_qty;
    }

    return 0;
}

public static function DeleteProductStockDeductionsByInvoiceIdAndProductId($invoice_id, $product_id) {
    global $db;

    $invoice_id = (int)$invoice_id;
    $product_id = (int)$product_id;

    $query = "DELETE FROM " . TABLE_PRODUCT_STOCK_DEDUCTIONS . "
              WHERE invoice_id = '{$invoice_id}'
                AND product_id = '{$product_id}'";

    $db->query($query);

    // deletion of zero rows is acceptable
    return true;
}

  public static function DeleteProductStockDeductionByInvoiceId($invoice_id) {
    global $db;

    // Construct the SQL query to delete all product stock deductions for the given invoice ID
    $query = "DELETE FROM " . TABLE_PRODUCT_STOCK_DEDUCTIONS . " WHERE invoice_id = '$invoice_id'";

    // Execute the query
    $result = $db->query($query);

    // Check if rows were affected, meaning records were deleted
    if ($db->affected_rows > 0) {
        return true; // Return true if records were deleted
    } else {
        return false; // Return false if no records were deleted
    }
}

  
  
}
  ?>