<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
ini_set('display_errors', 0);
Class Action {
	private $db;

	public function __construct() {
		ob_start();
   	include 'db_connect.php';
    
    $this->db = $conn;
	}
	function __destruct() {
	    $this->db->close();
	    ob_end_flush();
	}

	function login(){
		extract($_POST);
		$qry = $this->db->query("SELECT * FROM users where username = '".$username."' and password = '".$password."' ");
		if($qry->num_rows > 0){
			foreach ($qry->fetch_array() as $key => $value) {
				if($key != 'password' && !is_numeric($key))
					$_SESSION['login_'.$key] = $value;
			}
				return 1;
		}else{
			return 3;
		}
	}
	function login2(){
		extract($_POST);
		$qry = $this->db->query("SELECT * FROM user_info where email = '".$email."' and password = '".md5($password)."' ");
		if($qry->num_rows > 0){
			foreach ($qry->fetch_array() as $key => $value) {
				if($key != 'passwors' && !is_numeric($key))
					$_SESSION['login_'.$key] = $value;
			}
			$ip = isset($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']);
			$this->db->query("UPDATE cart set user_id = '".$_SESSION['login_user_id']."' where client_ip ='$ip' ");
				return 1;
		}else{
			return 3;
		}
	}
	function logout(){
		session_destroy();
		foreach ($_SESSION as $key => $value) {
			unset($_SESSION[$key]);
		}
		header("location:login.php");
	}
	function logout2(){
		session_destroy();
		foreach ($_SESSION as $key => $value) {
			unset($_SESSION[$key]);
		}
		header("location:../login");
	}

	function save_user(){
		extract($_POST);
		$data = " name = '$name' ";
		$data .= ", username = '$username' ";
		$data .= ", password = '$password' ";
		if(isset($type))
		$data .= ", type = '$type' ";
		if(empty($id)){
			$save = $this->db->query("INSERT INTO users set ".$data);
		}else{
			$save = $this->db->query("UPDATE users set ".$data." where id = ".$id);
		}
		if($save){
			return 1;
		}
	}
	function signup(){
		extract($_POST);
		$data = " first_name = '$first_name' ";
		$data .= ", last_name = '$last_name' ";
		$data .= ", mobile = '$mobile' ";
		$data .= ", address = '$address' ";
		$data .= ", email = '$email' ";
		$data .= ", password = '".md5($password)."' ";
		$chk = $this->db->query("SELECT * FROM user_info where email = '$email' ")->num_rows;
		if($chk > 0){
			return 2;
			exit;
		}
			$save = $this->db->query("INSERT INTO user_info set ".$data);
		if($save){
			$login = $this->login2();
			return 1;
		}
	}

	function save_settings(){
		extract($_POST);
		$data = " name = '$name' ";
		$data .= ", email = '$email' ";
		$data .= ", contact = '$contact' ";
		$data .= ", about_content = '".htmlentities(str_replace("'","&#x2019;",$about))."' ";
		if($_FILES['img']['tmp_name'] != ''){
						$fname = strtotime(date('y-m-d H:i')).'_'.$_FILES['img']['name'];
						$move = move_uploaded_file($_FILES['img']['tmp_name'],'../assets/img/'. $fname);
					$data .= ", cover_img = '$fname' ";

		}
		
		// echo "INSERT INTO system_settings set ".$data;
		$chk = $this->db->query("SELECT * FROM system_settings");
		if($chk->num_rows > 0){
			$save = $this->db->query("UPDATE system_settings set ".$data." where id =".$chk->fetch_array()['id']);
		}else{
			$save = $this->db->query("INSERT INTO system_settings set ".$data);
		}
		if($save){
		$query = $this->db->query("SELECT * FROM system_settings limit 1")->fetch_array();
		foreach ($query as $key => $value) {
			if(!is_numeric($key))
				$_SESSION['setting_'.$key] = $value;
		}

			return 1;
				}
	}

	
	function save_category(){
		extract($_POST);
		$data = " name = '$name' ";
		if(empty($id)){
			$save = $this->db->query("INSERT INTO category_list set ".$data);
		}else{
			$save = $this->db->query("UPDATE category_list set ".$data." where id=".$id);
		}
		if($save)
			return 1;
	}
	function delete_category(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM category_list where id = ".$id);
		if($delete)
			return 1;
	}
	function save_type(){
		extract($_POST);
		$data = " name = '$name' ";
		if(empty($id)){
			$save = $this->db->query("INSERT INTO type_list set ".$data);
		}else{
			$save = $this->db->query("UPDATE type_list set ".$data." where id=".$id);
		}
		if($save)
			return 1;
	}
	function delete_type(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM type_list where id = ".$id);
		if($delete)
			return 1;
	}
	function save_supplier(){
		extract($_POST);
		$data = " supplier_name = '$name' ";
		$data .= ", contact = '$contact' ";
		$data .= ", address = '$address' ";
		if(empty($id)){
			$save = $this->db->query("INSERT INTO supplier_list set ".$data);
		}else{
			$save = $this->db->query("UPDATE supplier_list set ".$data." where id=".$id);
		}
		if($save)
			return 1;
	}
	function delete_supplier(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM supplier_list where id = ".$id);
		if($delete)
			return 1;
	}
	function save_product(){
		extract($_POST);
		if(empty($sku)){
			$sku = mt_rand(1,99999999);
			$sku = sprintf("%'08d\n", $sku);
			$i = 1;
			while($i == 1){
				$chk = $this->db->query("SELECT * FROM product_list where sku ='$sku'")->num_rows;
				if($chk > 0){
					$sku = mt_rand(1,99999999);
					$sku = sprintf("%'08d\n", $sku);
				}else{
					$i=0;
				}
			}
		}
		$data = " name = '$name' ";
		$data .= ", sku = '$sku' ";
		$data .= ", category_id = '".implode(",",$category_id)."' ";
		$data .= ", type_id = '$type_id' ";
		$data .= ", measurement = '$measurement' ";
		$data .= ", description = '$description' ";
		$data .= ", buying_price = '$buying_price' ";
		$data .= ", selling_price = '$selling_price' ";
		if(isset($prescription))
		$data .= ", prescription = '$prescription' ";

		if(empty($id)){
			$save = $this->db->query("INSERT INTO product_list set ".$data);
		}else{
			$save = $this->db->query("UPDATE product_list set ".$data." where id=".$id);
		}
		if($save)
			return 1;
	}

	function delete_product(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM product_list where id = ".$id);
		if($delete)
			return 1;
	}
	function delete_user(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM users where id = ".$id);
		if($delete)
			return 1;
	}

	function save_receiving(){
		extract($_POST);
		$data = " supplier_id = '$supplier_id' ";
		$data .= ", total_amount = '$tamount' ";

		if(empty($id)){
			$ref_no = sprintf("%'08d\n", $ref_no);
			$i = 1;

			while($i == 1){
				$chk = $this->db->query("SELECT * FROM receiving_list where ref_no ='$ref_no'")->num_rows;
				if($chk > 0){
					$ref_no = mt_rand(1,99999999);
					$ref_no = sprintf("%'.08d\n", $ref_no);
				}else{
					$i=0;
				}
			}
			$data .= ", ref_no = '$ref_no' ";
			$save = $this->db->query("INSERT INTO receiving_list set ".$data);
			$id = $this->db->insert_id;

			foreach($product_id as $k => $v){
				// Get batch number (use default if not provided)
				$batch_num = isset($batch_number[$k]) ? $batch_number[$k] : 'BTH-'.date('YmdHis').'-'.$k;
				$b_price = isset($buying_price[$k]) ? $buying_price[$k] : 0;

				// Get selling price from product (fixed, not from form)
				$prod_info = $this->db->query("SELECT selling_price FROM product_list WHERE id = '".$product_id[$k]."'")->fetch_assoc();
				$s_price = $prod_info ? $prod_info['selling_price'] : 0;

				// Create batch record
				$batch_data = "product_id = '".$product_id[$k]."'";
				$batch_data .= ", batch_number = '".$this->db->real_escape_string($batch_num)."'";
				$batch_data .= ", expiry_date = '".$expiry_date[$k]."'";
				$batch_data .= ", quantity_received = '".$qty[$k]."'";
				$batch_data .= ", purchase_price = '".$b_price."'";
				$batch_data .= ", selling_price = '".$s_price."'";
				$batch_data .= ", receiving_id = '".$id."'";
				$batch_data .= ", status = 'active'";

				$this->db->query("INSERT INTO batch_list SET ".$batch_data);
				$batch_id = $this->db->insert_id;

				// Create inventory record with batch_id
				$inv_data = " form_id = '$id' ";
				$inv_data .= ", product_id = '".$product_id[$k]."' ";
				$inv_data .= ", batch_id = '".$batch_id."' ";
				$inv_data .= ", qty = '".$qty[$k]."' ";
				$inv_data .= ", expiry_date = '".$expiry_date[$k]."' ";
				$inv_data .= ", type = '1' ";
				$inv_data .= ", stock_from = 'receiving' ";
				$details = json_encode(array('buying_price'=>$b_price,'selling_price'=>$s_price,'qty'=>$qty[$k],'batch_number'=>$batch_num));
				$inv_data .= ", other_details = '".$details."' ";
				$inv_data .= ", remarks = 'Stock from Receiving-".$ref_no." Batch: ".$batch_num."' ";

				$save2[] = $this->db->query("INSERT INTO inventory SET ".$inv_data);
			}
			if(isset($save2)){
				return 1;
			}
		}else{
			$save = $this->db->query("UPDATE receiving_list set ".$data." where id =".$id);

			// Get existing inventory IDs
			$existing_inv_ids = isset($inv_id) ? array_filter($inv_id) : [];
			if(!empty($existing_inv_ids)){
				$ids = implode(",", $existing_inv_ids);
				// Delete batches linked to removed inventory items
				$this->db->query("DELETE FROM batch_list WHERE receiving_id = '$id' AND id NOT IN (SELECT batch_id FROM inventory WHERE form_id = '$id' AND id IN ($ids))");
				$this->db->query("DELETE FROM inventory WHERE type = 1 AND form_id = '$id' AND id NOT IN ($ids)");
			}

			foreach($product_id as $k => $v){
				$batch_num = isset($batch_number[$k]) ? $batch_number[$k] : 'BTH-'.date('YmdHis').'-'.$k;
				$b_price = isset($buying_price[$k]) ? $buying_price[$k] : 0;

				// Get selling price from product (fixed, not from form)
				$prod_info = $this->db->query("SELECT selling_price FROM product_list WHERE id = '".$product_id[$k]."'")->fetch_assoc();
				$s_price = $prod_info ? $prod_info['selling_price'] : 0;

				if(!empty($inv_id[$k])){
					// Update existing inventory record
					// Get existing batch_id
					$existing = $this->db->query("SELECT batch_id FROM inventory WHERE id = '".$inv_id[$k]."'")->fetch_assoc();
					$batch_id = isset($existing['batch_id']) ? $existing['batch_id'] : null;

					if($batch_id){
						// Update batch
						$batch_data = "batch_number = '".$this->db->real_escape_string($batch_num)."'";
						$batch_data .= ", expiry_date = '".$expiry_date[$k]."'";
						$batch_data .= ", quantity_received = '".$qty[$k]."'";
						$batch_data .= ", purchase_price = '".$b_price."'";
						$batch_data .= ", selling_price = '".$s_price."'";
						$this->db->query("UPDATE batch_list SET ".$batch_data." WHERE id = ".$batch_id);
					}

					$inv_data = " product_id = '".$product_id[$k]."' ";
					$inv_data .= ", qty = '".$qty[$k]."' ";
					$inv_data .= ", expiry_date = '".$expiry_date[$k]."' ";
					$details = json_encode(array('buying_price'=>$b_price,'selling_price'=>$s_price,'qty'=>$qty[$k],'batch_number'=>$batch_num));
					$inv_data .= ", other_details = '".$details."' ";

					$save2[] = $this->db->query("UPDATE inventory SET ".$inv_data." WHERE id=".$inv_id[$k]);
				}else{
					// Create new batch record
					$batch_data = "product_id = '".$product_id[$k]."'";
					$batch_data .= ", batch_number = '".$this->db->real_escape_string($batch_num)."'";
					$batch_data .= ", expiry_date = '".$expiry_date[$k]."'";
					$batch_data .= ", quantity_received = '".$qty[$k]."'";
					$batch_data .= ", purchase_price = '".$b_price."'";
					$batch_data .= ", selling_price = '".$s_price."'";
					$batch_data .= ", receiving_id = '".$id."'";
					$batch_data .= ", status = 'active'";

					$this->db->query("INSERT INTO batch_list SET ".$batch_data);
					$batch_id = $this->db->insert_id;

					// Create new inventory record
					$inv_data = " form_id = '$id' ";
					$inv_data .= ", product_id = '".$product_id[$k]."' ";
					$inv_data .= ", batch_id = '".$batch_id."' ";
					$inv_data .= ", qty = '".$qty[$k]."' ";
					$inv_data .= ", expiry_date = '".$expiry_date[$k]."' ";
					$inv_data .= ", type = '1' ";
					$inv_data .= ", stock_from = 'receiving' ";
					$details = json_encode(array('buying_price'=>$b_price,'selling_price'=>$s_price,'qty'=>$qty[$k],'batch_number'=>$batch_num));
					$inv_data .= ", other_details = '".$details."' ";
					$inv_data .= ", remarks = 'Stock from Receiving Batch: ".$batch_num."' ";

					$save2[] = $this->db->query("INSERT INTO inventory SET ".$inv_data);
				}
			}
			if(isset($save2)){
				return 1;
			}
		}
	}

	function delete_receiving(){
		extract($_POST);
		// Delete associated batches
		$this->db->query("DELETE FROM batch_list WHERE receiving_id = $id");
		$del1 = $this->db->query("DELETE FROM receiving_list WHERE id = $id");
		$del2 = $this->db->query("DELETE FROM inventory WHERE type = 1 AND form_id = $id");
		if($del1 && $del2)
			return 1;
	}
	function save_customer(){
		extract($_POST);
		$data = " name = '$name' ";
		$data .= ", contact = '$contact' ";
		$data .= ", address = '$address' ";
		if(empty($id)){
			$save = $this->db->query("INSERT INTO customer_list set ".$data);
			if($save)
				return $this->db->insert_id; // Return new customer ID
		}else{
			$save = $this->db->query("UPDATE customer_list set ".$data." where id=".$id);
			if($save)
				return $id; // Return existing ID on update
		}
	}
	function delete_customer(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM customer_list where id = ".$id);
		if($delete)
			return 1;
	}

	function chk_prod_availability(){
		extract($_POST);
		$price = $this->db->query("SELECT * FROM product_list where id = ".$id)->fetch_assoc()['selling_price'];

		// Get available stock from active batches (not expired, not depleted)
		$batches = $this->db->query("SELECT b.*,
			(b.quantity_received - b.quantity_sold - b.quantity_expired) as available_qty
			FROM batch_list b
			WHERE b.product_id = ".$id."
			AND b.status = 'active'
			AND b.expiry_date > CURDATE()
			HAVING available_qty > 0
			ORDER BY b.expiry_date ASC");

		$available = 0;
		$batch_info = [];

		if($batches && $batches->num_rows > 0){
			while($batch = $batches->fetch_assoc()){
				$available += $batch['available_qty'];
				$batch_info[] = array(
					'batch_id' => $batch['id'],
					'batch_number' => $batch['batch_number'],
					'expiry_date' => $batch['expiry_date'],
					'available' => $batch['available_qty']
				);
			}
		}

		// Fallback to old calculation if no batches exist
		if(empty($batch_info)){
			$inn = $this->db->query("SELECT sum(qty) as inn FROM inventory where type = 1 and product_id = ".$id);
			$inn = $inn && $inn->num_rows > 0 ? $inn->fetch_array()['inn'] : 0;
			$out = $this->db->query("SELECT sum(qty) as `out` FROM inventory where type = 2 and product_id = ".$id);
			$out = $out && $out->num_rows > 0 ? $out->fetch_array()['out'] : 0;
			$ex = $this->db->query("SELECT sum(qty) as ex FROM expired_product where product_id = ".$id);
			$ex = $ex && $ex->num_rows > 0 ? $ex->fetch_array()['ex'] : 0;
			$available = $inn - $out - $ex;
		}

		return json_encode(array('available'=>$available, 'price'=>$price, 'batches'=>$batch_info));
	}

	// Helper function to deduct from batches using FIFO
	function deductFromBatches($product_id, $qty_needed, $sales_id){
		$remaining = $qty_needed;
		$deductions = [];

		// Get batches ordered by expiry date (FIFO - First Expiring First Out)
		$batches = $this->db->query("SELECT b.*,
			(b.quantity_received - b.quantity_sold - b.quantity_expired) as available_qty
			FROM batch_list b
			WHERE b.product_id = ".$product_id."
			AND b.status = 'active'
			AND b.expiry_date > CURDATE()
			HAVING available_qty > 0
			ORDER BY b.expiry_date ASC");

		if($batches && $batches->num_rows > 0){
			while($batch = $batches->fetch_assoc()){
				if($remaining <= 0) break;

				$available = $batch['available_qty'];
				$to_deduct = min($remaining, $available);

				// Update batch quantity_sold
				$new_sold = $batch['quantity_sold'] + $to_deduct;
				$this->db->query("UPDATE batch_list SET quantity_sold = ".$new_sold." WHERE id = ".$batch['id']);

				// Check if batch is depleted
				if(($batch['quantity_received'] - $new_sold - $batch['quantity_expired']) <= 0){
					$this->db->query("UPDATE batch_list SET status = 'depleted' WHERE id = ".$batch['id']);
				}

				// Record the deduction in sales_batch_details
				$this->db->query("INSERT INTO sales_batch_details SET
					sales_id = '".$sales_id."',
					batch_id = '".$batch['id']."',
					product_id = '".$product_id."',
					quantity = '".$to_deduct."',
					unit_price = '".$batch['purchase_price']."'");

				$deductions[] = array(
					'batch_id' => $batch['id'],
					'batch_number' => $batch['batch_number'],
					'quantity' => $to_deduct
				);

				$remaining -= $to_deduct;
			}
		}

		return $deductions;
	}
	function save_sales(){
		extract($_POST);

		// Clean amount_tendered - remove any commas or non-numeric characters
		$amount_tendered = preg_replace('/[^0-9.]/', '', $amount_tendered);
		$amount_tendered = floatval($amount_tendered);
		$tamount = floatval($tamount);

		// Calculate change - if negative, it's a debt
		$debt_amount = isset($_POST['debt_amount']) ? floatval($_POST['debt_amount']) : 0;
		$actual_change = $amount_tendered - $tamount;
		$change = $actual_change >= 0 ? $actual_change : 0;

		$data = " customer_id = '$customer_id' ";
		$data .= ", total_amount = '$tamount' ";
		$data .= ", amount_tendered = '$amount_tendered' ";
		$data .= ", amount_change = '$change' ";

		if(empty($id)){
			$ref_no = sprintf("%'.08d\n", $ref_no);
			$i = 1;

			while($i == 1){
				$chk = $this->db->query("SELECT * FROM sales_list where ref_no ='$ref_no'")->num_rows;
				if($chk > 0){
					$ref_no = mt_rand(1,99999999);
					$ref_no = sprintf("%'.08d\n", $ref_no);
				}else{
					$i=0;
				}
			}
			$data .= ", ref_no = '$ref_no' ";
			$save = $this->db->query("INSERT INTO sales_list set ".$data);
			$id = $this->db->insert_id;

			foreach($product_id as $k => $v){
				// Deduct from batches using FIFO
				$batch_deductions = $this->deductFromBatches($product_id[$k], $qty[$k], $id);

				// Create inventory record
				$inv_data = " form_id = '$id' ";
				$inv_data .= ", product_id = '".$product_id[$k]."' ";
				$inv_data .= ", qty = '".$qty[$k]."' ";
				$inv_data .= ", type = '2' ";
				$inv_data .= ", stock_from = 'Sales' ";

				$details = json_encode(array(
					'price' => $price[$k],
					'qty' => $qty[$k],
					'batch_deductions' => $batch_deductions
				));
				$inv_data .= ", other_details = '".$this->db->real_escape_string($details)."' ";
				$inv_data .= ", remarks = 'Stock out from Sales-".$ref_no."' ";

				$save2[] = $this->db->query("INSERT INTO inventory SET ".$inv_data);
			}

			// Create debt record if there's a balance
			if($debt_amount > 0 && $customer_id > 0){
				$debt_status = 'pending';
				$amount_paid = floatval($amount_tendered);

				if($amount_paid > 0 && $amount_paid < floatval($tamount)){
					$debt_status = 'partial';
				}

				$this->db->query("INSERT INTO debt_list SET
					sales_id = '$id',
					customer_id = '$customer_id',
					total_amount = '$tamount',
					amount_paid = '$amount_paid',
					balance = '$debt_amount',
					status = '$debt_status'
				");

				// Record initial payment if any
				if($amount_paid > 0){
					$debt_id = $this->db->insert_id;
					$this->db->query("INSERT INTO debt_payments SET
						debt_id = '$debt_id',
						amount = '$amount_paid',
						payment_method = 'cash',
						remarks = 'Initial payment at sale'
					");
				}
			}

			if(isset($save2)){
				return $id;
			}
		}else{
			// For updates, we need to reverse the old batch deductions first
			// Get old sales batch details
			$old_details = $this->db->query("SELECT * FROM sales_batch_details WHERE sales_id = ".$id);
			while($old = $old_details->fetch_assoc()){
				// Restore quantity to batch
				$this->db->query("UPDATE batch_list SET
					quantity_sold = quantity_sold - ".$old['quantity'].",
					status = 'active'
					WHERE id = ".$old['batch_id']);
			}
			// Delete old sales batch details
			$this->db->query("DELETE FROM sales_batch_details WHERE sales_id = ".$id);

			$save = $this->db->query("UPDATE sales_list SET ".$data." WHERE id=".$id);

			$existing_inv_ids = isset($inv_id) ? array_filter($inv_id) : [];
			if(!empty($existing_inv_ids)){
				$ids = implode(",", $existing_inv_ids);
				$this->db->query("DELETE FROM inventory WHERE type = 2 AND form_id = '$id' AND id NOT IN ($ids)");
			}

			foreach($product_id as $k => $v){
				// Deduct from batches using FIFO
				$batch_deductions = $this->deductFromBatches($product_id[$k], $qty[$k], $id);

				$inv_data = " form_id = '$id' ";
				$inv_data .= ", product_id = '".$product_id[$k]."' ";
				$inv_data .= ", qty = '".$qty[$k]."' ";
				$inv_data .= ", type = '2' ";
				$inv_data .= ", stock_from = 'Sales' ";

				$details = json_encode(array(
					'price' => $price[$k],
					'qty' => $qty[$k],
					'batch_deductions' => $batch_deductions
				));
				$inv_data .= ", other_details = '".$this->db->real_escape_string($details)."' ";
				$inv_data .= ", remarks = 'Stock out from Sales' ";

				if(!empty($inv_id[$k])){
					$save2[] = $this->db->query("UPDATE inventory SET ".$inv_data." WHERE id=".$inv_id[$k]);
				}else{
					$save2[] = $this->db->query("INSERT INTO inventory SET ".$inv_data);
				}
			}
			if(isset($save2)){
				return $id;
			}
		}
	}
	function delete_sales(){
		extract($_POST);

		// Restore batch quantities before deleting
		$batch_details = $this->db->query("SELECT * FROM sales_batch_details WHERE sales_id = ".$id);
		if($batch_details && $batch_details->num_rows > 0){
			while($detail = $batch_details->fetch_assoc()){
				// Restore quantity to batch
				$this->db->query("UPDATE batch_list SET
					quantity_sold = quantity_sold - ".$detail['quantity'].",
					status = 'active'
					WHERE id = ".$detail['batch_id']);
			}
		}

		// Delete sales batch details
		$this->db->query("DELETE FROM sales_batch_details WHERE sales_id = ".$id);

		$del1 = $this->db->query("DELETE FROM sales_list WHERE id = $id");
		$del2 = $this->db->query("DELETE FROM inventory WHERE type = 2 AND form_id = $id");

		if($del1 && $del2)
			return 1;
	}

	function pay_debt(){
		extract($_POST);

		// Get current debt info
		$debt = $this->db->query("SELECT * FROM debt_list WHERE id = ".$debt_id)->fetch_assoc();
		if(!$debt){
			return 0;
		}

		$amount = floatval($amount);
		$current_paid = floatval($debt['amount_paid']);
		$current_balance = floatval($debt['balance']);
		$total = floatval($debt['total_amount']);

		// Validate amount
		if($amount <= 0 || $amount > $current_balance){
			return 0;
		}

		// Calculate new values
		$new_paid = $current_paid + $amount;
		$new_balance = $current_balance - $amount;

		// Determine status
		if($new_balance <= 0){
			$status = 'paid';
			$new_balance = 0;
		} else {
			$status = 'partial';
		}

		// Update debt record
		$update = $this->db->query("UPDATE debt_list SET
			amount_paid = '$new_paid',
			balance = '$new_balance',
			status = '$status'
			WHERE id = '$debt_id'
		");

		// Record payment
		$payment_method = isset($payment_method) ? $this->db->real_escape_string($payment_method) : 'cash';
		$remarks = isset($remarks) ? $this->db->real_escape_string($remarks) : '';

		$payment = $this->db->query("INSERT INTO debt_payments SET
			debt_id = '$debt_id',
			amount = '$amount',
			payment_method = '$payment_method',
			remarks = '$remarks'
		");

		if($update && $payment){
			return 1;
		}
		return 0;
	}

	function save_expired(){
		extract($_POST);
		foreach ($product_id as $key => $value) {
			$data = " product_id = $product_id[$key] ";
			$data .= ", qty = $qty[$key] ";
			$data .= ", date_expired = '$expiry_date[$key]' ";
			
			$save[] = $this->db->query("INSERT INTO expired_product set $data ");
		}
		if(isset($save))
			return 1;
	}
	function delete_expired(){
		extract($_POST);
		$delete = $this->db->query("DELETE FROM expired_product where id = $id ");
		if($delete)
			return 1;
	}

	function mark_batch_expired(){
		extract($_POST);
		$batch_id = intval($batch_id);
		$qty = intval($qty);

		// Get batch info
		$batch = $this->db->query("SELECT * FROM batch_list WHERE id = ".$batch_id)->fetch_assoc();
		if(!$batch) return 0;

		// Update batch
		$new_expired = $batch['quantity_expired'] + $qty;
		$available = $batch['quantity_received'] - $batch['quantity_sold'] - $new_expired;

		$status = $available <= 0 ? 'expired' : 'active';

		$update = $this->db->query("UPDATE batch_list SET
			quantity_expired = ".$new_expired.",
			status = '".$status."'
			WHERE id = ".$batch_id);

		// Also add to expired_product table for tracking
		$this->db->query("INSERT INTO expired_product SET
			product_id = ".$batch['product_id'].",
			qty = ".$qty.",
			date_expired = '".$batch['expiry_date']."'");

		if($update)
			return 1;
	}
}