<?php

function InsertStockDetails(
    $specific_db_conn,
    $workspace_id,
    $company_id,
    $branch_id,
    $book_id,
    $stock_name,
    $default_sp,
    $unit_name,
    $unit_id,
    $default_tax_ledgerid,
    $opening_qty,
    $book_opening_date,
    $created_by,
    $parent_group,
    $opening_balance,
    $current_balance,
    $filesattached,
    $region_id,
    $boolean_inventory,
    $tax_applicable,
    $hsn_code,
    $intra_tax_ledgerids,
    $inter_tax_ledgerids,
    $other_tax_ledgerids,
    $product_type,
    $inventory_batch_details
) {

    // sending openingbalance as currentbalance because UpdateSockBalance will update it accordingly
    try {
        // insert query of stock     
        $sql = "INSERT INTO inventory_stockdetails(workspace_id, company_id, branch_id, book_id, stock_name, current_qty, default_sp, unit_name, unit_id, default_tax_ledgerid, opening_qty, opening_balance, current_balance, date_created, time_created, created_by, parent_group, filesattached, region_id, boolean_inventory, tax_applicable, hsn_code,intra_tax_ledgerids, inter_tax_ledgerids, other_tax_ledgerids, product_type, status)
                     VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $stmt =  $specific_db_conn->prepare($sql);
        $stmt->execute(array(
            $workspace_id, $company_id, $branch_id, $book_id, $stock_name, $opening_qty, $default_sp, $unit_name, $unit_id, $default_tax_ledgerid, $opening_qty, $opening_balance, $current_balance, date("Y-m-d"), time(), $created_by, $parent_group, $filesattached, $region_id, $boolean_inventory, $tax_applicable, $hsn_code, $intra_tax_ledgerids, $inter_tax_ledgerids, $other_tax_ledgerids, $product_type, '1'
        ));

        $stock_id = $specific_db_conn->lastInsertId();
        if ($inventory_batch_details != null) {
            if (!InsertBatchDetails($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $stock_id, $inventory_batch_details, $created_by, 'opening', $index_batch = null, $book_opening_date, null)) {
                errorreturn('Unable to create stock item. Error : 1');
            }
        }
        return $stock_id;
    } catch (Exception $e) {
        errorreturn("Error : " . $e->getMessage());
    }
}

function UpdateStockDetails(
    $specific_db_conn,
    $workspace_id,
    $company_id,
    $branch_id,
    $book_id,
    $stock_id,
    $stock_name,
    $default_sp,
    $unit_name,
    $unit_id,
    $default_tax_ledgerid,
    $opening_qty,
    $book_opening_date,
    $created_by,
    $parent_group,
    $opening_balance,
    $current_balance,
    $region_id,
    $boolean_inventory,
    $tax_applicable,
    $intra_tax_ledgerids,
    $inter_tax_ledgerids,
    $other_tax_ledgerids,
    $hsn_code,
    $product_type,
    $inventory_batch_details

) {

    try {
        $sql = "UPDATE inventory_stockdetails SET stock_name=?,current_qty=?,default_sp=?,unit_name=?,unit_id=?,default_tax_ledgerid=? ,opening_qty =?,opening_balance=?,current_balance= ?,last_modified_by=?,parent_group = ?,region_id=?,boolean_inventory=?,tax_applicable=?,hsn_code=?
        ,intra_tax_ledgerids=?,inter_tax_ledgerids=?,other_tax_ledgerids=?,product_type=? WHERE id=? and workspace_id  =? and company_id =? and branch_id =? and book_id =? ";
        $update = $specific_db_conn->prepare($sql);
        $update->execute(array(
            $stock_name, $opening_qty, $default_sp, $unit_name, $unit_id, $default_tax_ledgerid, $opening_qty, $opening_balance, $current_balance, $created_by, $parent_group, $region_id, $boolean_inventory, $tax_applicable, $hsn_code, $intra_tax_ledgerids,
            $inter_tax_ledgerids, $other_tax_ledgerids, $product_type, $stock_id, $workspace_id, $company_id, $branch_id, $book_id
        ));


        // delete from inventory batch details
        $sql_delete = "Delete from inventory_batch_details where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and stock_id = ? and type = ?";
        $delete = $specific_db_conn->prepare($sql_delete);
        $delete->execute(array($workspace_id, $company_id, $branch_id, $book_id, $stock_id, 'opening'));
        if ($inventory_batch_details != null) {
            if (!InsertBatchDetails($specific_db_conn, $workspace_id, $company_id, $branch_id, $book_id, $stock_id, $inventory_batch_details, $created_by, 'opening', $index_batch = null, $book_opening_date, null, $stock_name)) {
                errorreturn('Unable to create stock item. Error : 2');
            }
        }

        // if ($unit_name != null and $unit_id != null) {
        $sql_units = "UPDATE inventory_stocktransaction SET unit_id=? WHERE stock_id=? and workspace_id  =? and company_id =? and branch_id =? and book_id =? ";
        $updateUnits = $specific_db_conn->prepare($sql_units);
        $updateUnits->execute(array($unit_id, $stock_id, $workspace_id, $company_id, $branch_id, $book_id));
        // }

        return true;
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
}

// this one is for searching throughout
// function GetStockDetail($conn, $workspace_id, $company_id, $branch_id, $book_id, $search_string, $additionaldata, $limit, $offset, $appended_region_bool)
// {

//     // checking if any barcode matches with that of search string 
//     $sql_search_barcode = "Select stock_id from inventory_batch_details where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and stock_barcode_uin = ?";
//     $search_barcode = $conn->prepare($sql_search_barcode);
//     $search_barcode->execute(array($workspace_id, $company_id, $branch_id, $book_id, $search_string));
//     $result_barcode = $search_barcode->fetchAll();

//     $sql = "Select count(*) as total_rows from inventory_stockdetails where workspace_id = ? and company_id =? and branch_id =? and book_id  =? and stock_name like ? ";
//     $array_params = [$workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'];

//     $validate_ledger = $conn->prepare($sql);
//     $validate_ledger->execute($array_params);

//     $result_total = $validate_ledger->fetchAll();
//     $totalrows = $result_total[0]['total_rows'];

//     // if ($limit == 'all') {
//     //     //batch details
//     //     $sql = "Select * FROM  inventory_batch_details where workspace_id = ? and company_id =? and branch_id = ? and book_id=? and stock_barcode_uin = ? ";
//     //      $array_params = [$workspace_id, $company_id, $branch_id, $book_id,$search_string];

//     //     $stmt = $conn->prepare($sql);
//     //     $stmt->execute($array_params);
//     //     $result = $stmt->fetchAll();

//     //     if(count($result) >= 1){
//     //             $stock_barcode_uin = $result[0]['stock_barcode_uin'];
//     //     }else{

//     //          $stock_barcode_uin =  null;
//     //     }
//     //     //stock search
//     //     $sql = "Select ";
//     //     $array_counter = 0;
//     //     foreach ($additionaldata as $column_name) {
//     //         if ($array_counter == 0) {
//     //             $sql = $sql . " " . $column_name;
//     //         } else {
//     //             $sql = $sql . ", " . $column_name;
//     //         }
//     //         $array_counter++;
//     //     }
//     //     if ($appended_region_bool == 1) {
//     //         $sql = $sql . ",region_id";
//     //     }

//     //     $sql = $sql . ", boolean_inventory FROM  inventory_stockdetails where workspace_id = ? and company_id = ? and branch_id = ? and book_id = ? and (stock_name like ?)";
//     //     $array_params = [$workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'];

//     //     $stmt = $conn->prepare($sql);
//     //     $stmt->execute($array_params);
//     //     $result = $stmt->fetchAll();

//     // } else {

//     $sql = "Select * FROM  inventory_batch_details where workspace_id = ? and company_id =? and branch_id = ? and book_id=? and stock_barcode_uin = ? ";
//     $array_params = [$workspace_id, $company_id, $branch_id, $book_id, $search_string];

//     $stmt = $conn->prepare($sql);
//     $stmt->execute($array_params);
//     $result = $stmt->fetchAll();
//     if (count($result) >= 1) {
//         $stock_barcode_uin = $result[0]['stock_barcode_uin'];
//     } else {

//         $stock_barcode_uin =  null;
//     }
//     $sql = "Select ";
//     $array_counter = 0;
//     foreach ($additionaldata as $column_name) {
//         if ($array_counter == 0) {
//             $sql = $sql . " " . $column_name;
//         } else {
//             $sql = $sql . ", " . $column_name;
//         }
//         $array_counter++;
//     }
//     $sql = $sql . " FROM  inventory_stockdetails where workspace_id = ? and company_id =? and branch_id=? and book_id=? and (stock_name LIKE ?) ";
//     $array_params = [$workspace_id, $company_id, $branch_id, $book_id, '%' . $search_string . '%'];
//     if ($limit != "all") {
//         $sql = $sql . " LIMIT " . $offset . "," . $limit;
//     }
//     $stmt = $conn->prepare($sql);
//     $stmt->execute($array_params);
//     $result = $stmt->fetchAll();

//     // }

//     $array_return = [];

//     if (isset($additionaldata['inter_tax_ledgerids']) or isset($additionaldata['intra_tax_ledgerids']) or isset($additionaldata['other_tax_ledgerids'])) {
//         // preparing query
//         //$sql_fetch_tax_details = "Select ledger_name, param_1 from act_ledgerdetails where workspace_id = ? and company_id =? and branch_id=? and book_id=? and id = ?";
//         //$fetch_tax_ledger_details = $conn->prepare($sql_fetch_tax_details);

//     }

//     $tax_ledgerids_array = [];
//     $tax_details_array = [];
//     $items_array = array();
//     $uniqueArrays = [];

//     foreach ($result as $res) {
//         $items_array[] = $res['id'];


//         $fieldarray = [];
//         // get the boolean inventory value here
//         $boolean_inventory = $res['boolean_inventory'];
//         foreach ($additionaldata as $column_name) {

//             if (in_array($column_name, ['inter_tax_ledgerids', 'intra_tax_ledgerids', 'other_tax_ledgerids'])) {
//                 $temp_field__value = null;
//                 foreach (explode(",", $res[$column_name]) as $tax_ledgerid_temp) {

//                     if (in_array(str_replace("'", "", $tax_ledgerid_temp), $tax_ledgerids_array)) {
//                         $temp_field__value[] = $tax_details_array[array_search(str_replace("'", "", $tax_ledgerid_temp), $tax_ledgerids_array) . ""];
//                     } else {
//                         $ledgerid = str_replace("'", "", $tax_ledgerid_temp);

//                         $sql_fetch_tax_details = "Select ledger_name, param_1 from act_ledgerdetails where workspace_id = ? and company_id =? and branch_id=? and book_id=? and id =?  ";
//                         $fetch_tax_ledger_details = $conn->prepare($sql_fetch_tax_details);
//                         $fetch_tax_ledger_details->execute(array($workspace_id, $company_id, $branch_id, $book_id, $ledgerid));
//                         $result_tax_ledgerid = $fetch_tax_ledger_details->fetchAll();

//                         if (count($result_tax_ledgerid) >= 1) {
//                             //  print_r(count($result_tax_ledgerid));die();
//                             $tax_ledgerids_array[] = $tax_ledgerid_temp;
//                             $tax_details_array[] = array('id' => $ledgerid, 'name' => $result_tax_ledgerid[0]['ledger_name'], 'tax_percentage' => $result_tax_ledgerid[0]['param_1']);
//                             $temp_field__value[] = $tax_details_array[count($tax_details_array) - 1];
//                         } else {

//                             //errorreturn("Error at establishing tax information for $tax_ledgerid_temp");
//                         }
//                     }
//                 }
//                 $fieldarray[$column_name] = $temp_field__value;
//             } else {
//                 $fieldarray['stock_barcode_uin'] = $stock_barcode_uin;
//                 $fieldarray[$column_name] = $res[$column_name];

//                 if ($column_name == 'region_id') {
//                     if ($appended_region_bool == 1) {
//                         // append to name if asked
//                         $fieldarray['stock_name'] = $fieldarray['stock_name'] . " (" . getRegionName($workspace_id, $company_id, $branch_id, $book_id, $res[$column_name]) . ")";
//                     } else {
//                         // send region_name seperately

//                         $fieldarray['region_name'] = getRegionName($workspace_id, $company_id, $branch_id, $book_id, $res[$column_name]);
//                     }
//                 }

//                 // if column name == 'current_qty'
//                 // // if inventory applicable , set field value as current_qty received
//                 // $fieldarray[$column_name] = $res[$column_name];
//                 // if not, set as null (NA)
//                 // $fieldarray[$column_name] = 'NA';

//                 // if column name == current balance }}
//                 // if invemntory applicable yes, then get specific stock summary fifi closing and set the value from there
//                 if ($column_name === 'current_qty') {
//                     // Check if 'boolean_inventory' value is 0
//                     if ($res['boolean_inventory'] == 0) {
//                         $fieldarray['current_qty'] = 'NA';
//                     } else {
//                         // If 'boolean_inventory' is not 0 (considered true)
//                         $fieldarray['current_qty'] = $res['current_qty'];
//                     }
//                 }

//                 if ($column_name === 'current_balance') {
//                     if ($res['boolean_inventory'] == 1) {
//                         // Get 'closing_stock' from the specific stock summary
//                         $fieldarray['current_balance'] = getFifoSummaryClosingStockSpecific($conn, null, null, $workspace_id, $company_id, $branch_id, $book_id, [$res['id']])[0]['closing_stock'];
//                     }
//                 }


//                 if ($column_name === 'filesattached') {

//                     $fieldarray['filesattached'] = $res[$column_name];
//                     if ($fieldarray['filesattached'] !=  null) {
//                         $link = 'https://rejoicebilldesk.in/rjlbilldesk_development/';
//                         $fieldarray['filesattached'] = $link . $res[$column_name];
//                     } else {
//                         $fieldarray['filesattached'] =  null;
//                     }
//                 }
//             }
//         }
//         array_push($array_return, $fieldarray);
//     }

//     if (count($result) < 50) {

//         return array('total_rows' => $totalrows, 'stock_info' => $array_return, 'maxreach' => 1);
//     } else {
//         return array('total_rows' => $totalrows, 'stock_info' => $array_return, 'maxreach' => 0);
//     }
// }
