:: **Zploit** v1.0 | Current Path: **/home/kreativepixelz/www/kreative_crm/quatation/**
:: Editing File: update_inward.php
<?php // Include necessary files include_once("session.php"); include("db.php"); // Assumed to contain $conn for mysqli connection // Check if the form was submitted via POST if ($_SERVER["REQUEST_METHOD"] != "POST") { $_SESSION['error'] = "Invalid request method."; header("Location: inward_list.php"); exit(); } // ----------------------------------------------------------- // 1. DATA VALIDATION AND INITIAL SETUP // ----------------------------------------------------------- // Basic required fields $required_fields = ['inward_id', 'inward_date', 'vendor_id', 'brand_desc', 'total_box_count', 'cold_storage_id']; // Check for inward_id first to facilitate redirection if (!isset($_POST['inward_id']) || !is_numeric($_POST['inward_id'])) { $_SESSION['error'] = "Invalid Inward ID provided for update."; header("Location: inward_list.php"); exit(); } $inward_id = (int)$_POST['inward_id']; $redirect_url = "edit_inward.php?id=" . $inward_id; foreach ($required_fields as $field) { if (!isset($_POST[$field]) || empty($_POST[$field])) { $_SESSION['error'] = "Missing required field: " . str_replace('_', ' ', $field); header("Location: " . $redirect_url); exit(); } } // Fetch current data for rollback/file deletion purposes $sql_current = "SELECT inward_receipt FROM inward WHERE id = ?"; $stmt_current = mysqli_prepare($conn, $sql_current); mysqli_stmt_bind_param($stmt_current, "i", $inward_id); mysqli_stmt_execute($stmt_current); $result_current = mysqli_stmt_get_result($stmt_current); $current_data = mysqli_fetch_assoc($result_current); mysqli_stmt_close($stmt_current); if (!$current_data) { $_SESSION['error'] = "Inward Bill to update was not found."; header("Location: inward_list.php"); exit(); } $old_inward_receipt = $current_data['inward_receipt']; $inward_receipt_path = $old_inward_receipt; // Sanitize and assign variables for the 'inward' table $inward_date = mysqli_real_escape_string($conn, $_POST['inward_date']); $inward_no = mysqli_real_escape_string($conn, $_POST['inward_no'] ?? ''); $billno = mysqli_real_escape_string($conn, $_POST['billno'] ?? ''); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $brand_desc = mysqli_real_escape_string($conn, $_POST['brand_desc']); $total_box_count = (int) $_POST['total_box_count']; $vendor_id = (int) $_POST['vendor_id']; $cold_storage_id = (int) $_POST['cold_storage_id']; $user_id = (int) $_SESSION['user_id']; // Logistical/Driver details (UPDATED FIELDS) $supervisior_name = mysqli_real_escape_string($conn, $_POST['supervisior_name'] ?? ''); $vehicle_number = mysqli_real_escape_string($conn, $_POST['vehicle_number'] ?? ''); $driver_number = mysqli_real_escape_string($conn, $_POST['driver_number'] ?? ''); $dispatch_time = mysqli_real_escape_string($conn, $_POST['dispatch_time'] ?? ''); // ----------------------------------------------------------- // 2. FILE UPLOAD HANDLING // ----------------------------------------------------------- if (isset($_FILES["inward_receipt"]) && $_FILES["inward_receipt"]["error"] == 0) { $target_dir = "uploads/inward_receipts/"; $file_name = basename($_FILES["inward_receipt"]["name"]); $target_file = $target_dir . time() . "_" . $file_name; $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION)); if ($_FILES["inward_receipt"]["size"] > 5000000) { $uploadOk = 0; $_SESSION['error'] = "File is too large."; } if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "pdf") { $uploadOk = 0; $_SESSION['error'] = "Only JPG, JPEG, PNG, & PDF files are allowed."; } if ($uploadOk == 0) { header("Location: " . $redirect_url); exit(); } else { if (move_uploaded_file($_FILES["inward_receipt"]["tmp_name"], $target_file)) { $inward_receipt_path = $target_file; // Delete old file if ($old_inward_receipt && file_exists($old_inward_receipt)) { unlink($old_inward_receipt); } } else { $_SESSION['error'] = "Sorry, there was an error uploading your file."; header("Location: " . $redirect_url); exit(); } } } // ----------------------------------------------------------- // 3. DATABASE TRANSACTION // ----------------------------------------------------------- mysqli_begin_transaction($conn); $success = true; try { // --- STEP 3A: UPDATE `inward` (Master Record) --- // The UPDATE statement now includes the four logistical fields $sql_inward = "UPDATE inward SET vendor_id=?, inward_date=?, inward_no=?, billno=?, brand_desc=?, total_box_count=?, cold_storage_id=?, inward_receipt=?, user_id=?, supervisior_name=?, vehicle_number=?, driver_number=?, dispatch_time=?, updated_at=CURRENT_TIMESTAMP(), product_name=? WHERE id=?"; $stmt_inward = mysqli_prepare($conn, $sql_inward); if (!$stmt_inward) throw new Exception("Inward statement preparation failed: " . mysqli_error($conn)); // Bind parameters: i s s s s i s s s s s s i mysqli_stmt_bind_param($stmt_inward, "issssissssssssi", $vendor_id, $inward_date, $inward_no, $billno, $brand_desc, $total_box_count, $cold_storage_id, $inward_receipt_path, $user_id, $supervisior_name, $vehicle_number, $driver_number, $dispatch_time, $product_name, $inward_id ); if (!mysqli_stmt_execute($stmt_inward)) throw new Exception("Inward execution failed: " . mysqli_stmt_error($stmt_inward)); mysqli_stmt_close($stmt_inward); // --- STEP 3B: UPDATE `inward_box` (Category Breakdown) --- // (Logic remains the same for dynamic box category handling) $box_categories = []; $update_fields = []; $query = "SELECT category_name FROM box_category WHERE status = 1 ORDER BY id ASC"; $result = mysqli_query($conn, $query); if ($result) { while ($row = mysqli_fetch_assoc($result)) { $category_name = htmlspecialchars($row['category_name']); $input_key = 'box_' . str_replace([' ', '/', '-'], '', $category_name); $box_categories[$input_key] = (int) ($_POST[$input_key] ?? 0); $update_fields[] = $input_key . " = ?"; } } $sql_box = "UPDATE inward_box SET total_box = ?, " . implode(", ", $update_fields) . " WHERE inward_id = ?"; $stmt_box = mysqli_prepare($conn, $sql_box); if (!$stmt_box) throw new Exception("Box statement preparation failed: " . mysqli_error($conn)); $bind_params = array_merge([$total_box_count], array_values($box_categories), [$inward_id]); $bind_types = 'i' . str_repeat('i', count($box_categories)) . 'i'; $refs = []; foreach ($bind_params as $key => $value) { $refs[$key] = &$bind_params[$key]; } array_unshift($refs, $bind_types); if (!call_user_func_array('mysqli_stmt_bind_param', array_merge([$stmt_box], $refs))) { throw new Exception("Box binding failed."); } if (!mysqli_stmt_execute($stmt_box)) throw new Exception("Box execution failed: " . mysqli_stmt_error($stmt_box)); mysqli_stmt_close($stmt_box); // --- STEP 3C: MANAGE `inward_items` (Insert, Update, Delete) --- $posted_item_ids = []; $items_to_process = count($_POST['item_desc'] ?? []); for ($key = 0; $key < $items_to_process; $key++) { $item_id = (int) ($_POST['item_id'][$key] ?? 0); $description = mysqli_real_escape_string($conn, $_POST['item_desc'][$key] ?? ''); $type_of_good = mysqli_real_escape_string($conn, $_POST['item_good'][$key] ?? ''); $item_total_box = (float) ($_POST['item_total_box'][$key] ?? 0.00); $wastage_kg = (float) ($_POST['item_wastage_kg'][$key] ?? 0.00); $actual_wastage_kg= (float) ($_POST['item_actual_wastage_kg'][$key] ?? 0.00); if (empty($description)) continue; if ($item_id > 0) { // --- UPDATE EXISTING ITEM --- $sql_item_update = "UPDATE inward_items SET description=?, type_of_good=?, total_box=?, wastage_kg=?, actual_wastage_kg=? WHERE id=? AND inward_id=?"; $stmt_item_update = mysqli_prepare($conn, $sql_item_update); if (!$stmt_item_update) throw new Exception("Item update statement preparation failed: " . mysqli_error($conn)); mysqli_stmt_bind_param($stmt_item_update, "ssdddii", $description, $type_of_good, $item_total_box, $wastage_kg, $actual_wastage_kg, $item_id, $inward_id); if (!mysqli_stmt_execute($stmt_item_update)) throw new Exception("Item update execution failed for ID $item_id: " . mysqli_stmt_error($stmt_item_update)); mysqli_stmt_close($stmt_item_update); $posted_item_ids[] = $item_id; } else { // --- INSERT NEW ITEM --- $sql_item_insert = "INSERT INTO inward_items (inward_id, description, type_of_good, total_box, wastage_kg, actual_wastage_kg) VALUES (?, ?, ?, ?, ?, ?)"; $stmt_item_insert = mysqli_prepare($conn, $sql_item_insert); if (!$stmt_item_insert) throw new Exception("Item insert statement preparation failed: " . mysqli_error($conn)); mysqli_stmt_bind_param($stmt_item_insert, "issddd", $inward_id, $description, $type_of_good, $item_total_box, $wastage_kg, $actual_wastage_kg); if (!mysqli_stmt_execute($stmt_item_insert)) throw new Exception("Item insert execution failed: " . mysqli_stmt_error($stmt_item_insert)); $posted_item_ids[] = mysqli_insert_id($conn); mysqli_stmt_close($stmt_item_insert); } } // --- DELETE REMOVED ITEMS --- $sql_all_items = "SELECT id FROM inward_items WHERE inward_id = ?"; $stmt_all_items = mysqli_prepare($conn, $sql_all_items); mysqli_stmt_bind_param($stmt_all_items, "i", $inward_id); mysqli_stmt_execute($stmt_all_items); $result_all_items = mysqli_stmt_get_result($stmt_all_items); $current_db_ids = mysqli_fetch_all($result_all_items, MYSQLI_ASSOC); mysqli_stmt_close($stmt_all_items); $ids_to_delete = []; foreach ($current_db_ids as $row) { if (!in_array($row['id'], $posted_item_ids)) { $ids_to_delete[] = $row['id']; } } if (!empty($ids_to_delete)) { $delete_ids_str = implode(',', array_map('intval', $ids_to_delete)); $sql_item_delete = "DELETE FROM inward_items WHERE id IN ($delete_ids_str) AND inward_id = ?"; $stmt_item_delete = mysqli_prepare($conn, $sql_item_delete); if (!$stmt_item_delete) throw new Exception("Item delete statement preparation failed: " . mysqli_error($conn)); mysqli_stmt_bind_param($stmt_item_delete, "i", $inward_id); if (!mysqli_stmt_execute($stmt_item_delete)) throw new Exception("Item delete execution failed: " . mysqli_stmt_error($stmt_item_delete)); mysqli_stmt_close($stmt_item_delete); } // Commit Transaction mysqli_commit($conn); $_SESSION['success'] = "Inward Bill (ID: $inward_id) updated successfully!"; } catch (Exception $e) { // Rollback Transaction on error mysqli_rollback($conn); // Delete newly uploaded file on failure if ($inward_receipt_path !== $old_inward_receipt && $inward_receipt_path && file_exists($inward_receipt_path)) { unlink($inward_receipt_path); } $success = false; $_SESSION['error'] = "Failed to update Inward Bill. Error: " . $e->getMessage(); } // ----------------------------------------------------------- // 4. REDIRECT // ----------------------------------------------------------- if ($success) { header("Location: inward_list.php"); } else { header("Location: " . $redirect_url); } exit(); ?>