<?php
ini_set( 'display_errors', 1 );
ini_set( 'display_startup_errors', 1 );
error_reporting( E_ALL );

include __DIR__ . '/../inc/db.php'; // Adjust path as needed

header( 'Content-Type: application/json' );

// Default response
$response = [ 'status' => 'error', 'message' => 'Invalid request' ];

// Handle POST requests
if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ) {
	// Get action type (create, update, delete)
	$action = $_POST[ 'action' ];

	// Create Payment
	if ( $action === 'Create' ) {
		// Required POST values
		$booking_id = $_POST[ 'id' ];
		$customer_id = $_POST[ 'customer_id' ];
		$useridnew = $_POST[ 'useridnew' ];
		$payment_mode = $_POST[ 'payment_mode' ];
		$total = $_POST[ 'total' ];
		$received = $_POST[ 'received' ];
		$gst_included = $_POST[ 'gst_included' ];
		$remarks = $_POST[ 'remarks' ];

		// Optional fields
		$upi_details = $_POST[ 'upi_details' ] ?? '';
		$cheque_no = $_POST[ 'cheque_no' ] ?? '';
		$bank_name = $_POST[ 'bank_name' ] ?? '';

		// Check if received amount is greater than total
		if ( $received > $total ) {
			$response = [
				'status' => 'error',
				'message' => 'Received amount cannot be greater than the total amount.'
			];
			echo json_encode( $response );
			exit;
		}

		// Financial year logic
		$month = date( 'n' );
		$year = date( 'Y' );
		if ( $month < 4 ) {
			$financial_year = ( $year - 1 ) . '-' . substr( $year, 2 );
		} else {
			$financial_year = $year . '-' . substr( $year + 1, 2 );
		}

		// Payment date and type
		$payment_date = date( 'Y-m-d' );
		$payment_type = 'credit';

		// Generate next receipt number
		$stmt = $conn->prepare( "SELECT MAX(CAST(receipt_no AS UNSIGNED)) FROM package_payments WHERE gst_included = ? AND financial_year = ?" );
		$stmt->bind_param( "ss", $gst_included, $financial_year );
		$stmt->execute();
		$stmt->bind_result( $last_receipt_no );
		$stmt->fetch();
		$stmt->close();

		if ( $last_receipt_no === NULL ) {
			$next_receipt_no = str_pad( 1, 4, '0', STR_PAD_LEFT ); // 0001
		} else {
			$next_receipt_no = str_pad( $last_receipt_no + 1, 4, '0', STR_PAD_LEFT );
		}

		// Escape strings safely
		$upi_details_safe = mysqli_real_escape_string( $conn, $upi_details );
		$cheque_no_safe = mysqli_real_escape_string( $conn, $cheque_no );
		$bank_name_safe = mysqli_real_escape_string( $conn, $bank_name );

		// Insert payment query
		$sql = "INSERT INTO package_payments (receipt_no, booking_id, customer_id, type, amount, payment_mode, payment_date, financial_year, upi_details, cheque_no, bank_name, remarks, gst_included, assigned_to)
                VALUES ('$next_receipt_no', '$booking_id', '$customer_id', '$payment_type', '$received', '$payment_mode', '$payment_date', '$financial_year',
                        '$upi_details_safe', '$cheque_no_safe', '$bank_name_safe', '$remarks', '$gst_included', '$useridnew')";

		if ( mysqli_query( $conn, $sql ) ) {
			$last_id = mysqli_insert_id( $conn );
			$response = [
				'status' => 'success',
				'message' => 'Payment added successfully',
				'payment_id' => $last_id,
				'booking_id' => $booking_id
			];
		} else {
			$response = [
				'status' => 'error',
				'message' => 'Database error: ' . mysqli_error( $conn )
			];
		}
	}

	// Update Payment
	if ( $action === 'Update' ) {
		// Sanitize and retrieve POST data
		$id = $_POST[ 'id' ];
		$booking_id = $_POST[ 'booking_id' ];
		$customer_id = $_POST[ 'customer_id' ];
		$payment_mode = $_POST[ 'payment_mode' ];
		$total = $_POST[ 'total' ];
		$received = $_POST[ 'received' ];
		$remarks = $_POST[ 'remarks' ];
		$upi_details = $_POST[ 'upi_details' ];
		$cheque_no = $_POST[ 'cheque_no' ];
		$bank_name = $_POST[ 'bank_name' ];
		$gst_included = $_POST[ 'gst_included' ];

		// Validate data (e.g., check if received <= total)
		if ( $received > $total ) {
			echo json_encode( [ 'status' => 'error', 'message' => 'Received amount cannot be greater than total' ] );
			exit;
		}

		// Prepare SQL query for updating payment record
		$stmt = $conn->prepare( "UPDATE package_payments SET 
            payment_mode = ?, total = ?, amount = ?, upi_details = ?, cheque_no = ?, bank_name = ?, remarks = ?, gst_included = ? 
            WHERE id = ?" );
		$stmt->bind_param( "ssssssssi", $payment_mode, $total, $received, $upi_details, $cheque_no, $bank_name, $remarks, $gst_included, $id );

		if ( $stmt->execute() ) {
			echo json_encode( [ 'status' => 'success', 'message' => 'Payment details updated successfully' ] );
		} else {
			echo json_encode( [ 'status' => 'error', 'message' => 'Database error: ' . $stmt->error ] );
		}
	}

if ( $action === 'Select' ) {
	$id = $_POST[ 'id' ] ?? null;

	$query = "SELECT pp.*, 
	                 totals.total_debit, 
	                 totals.total_credit, 
	                 totals.pending_amount 
	          FROM package_payments pp 
	          JOIN (
		          SELECT booking_id, 
		                 SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) AS total_debit, 
		                 SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END) AS total_credit, 
		                 (SUM(CASE WHEN type = 'debit' THEN amount ELSE 0 END) - 
		                  SUM(CASE WHEN type = 'credit' THEN amount ELSE 0 END)) AS pending_amount 
		          FROM package_payments 
		          WHERE booking_id = (SELECT booking_id FROM package_payments WHERE id = ?) 
		          GROUP BY booking_id
	          ) AS totals ON pp.booking_id = totals.booking_id 
	          WHERE pp.id = ?";

	$stmt = $conn->prepare( $query );
	$stmt->bind_param( "ii", $id, $id ); // bind both ? with $id
	$stmt->execute();
	$result = $stmt->get_result();
	$payment = $result->fetch_assoc();

	if ( $payment ) {
		echo json_encode( $payment );
	} else {
		echo json_encode( null );
	}
	exit;
}

	// Delete Payment
	if ( $action === 'Delete' ) {


		$id = $_POST[ 'id' ];
		$stmt = $conn->prepare( "DELETE FROM package_payments WHERE id = ?" );
		$stmt->bind_param( "i", $id );

		if ( $stmt->execute() ) {
			echo json_encode( [ 'status' => 'success', 'message' => 'Payment record deleted successfully' ] );
		} else {
			echo json_encode( [ 'status' => 'error', 'message' => 'Database error: ' . $stmt->error ] );
		}
		exit;
	}

}

echo json_encode( $response );
?>